Skip to content

Model Overview

Turftopic contains implementations of a number of contemporary topic models. Some of these models might be similar to each other in a lot of aspects, but they might be different in others. It is quite important that you choose the right topic model for your use case.

āš” Speed šŸ“– Long Documents šŸ˜ Scalability šŸ”© Flexibility
SemanticSignalSeparation KeyNMF KeyNMF ClusteringTopicModel

Table 1: You should tailor your model choice to your needs

Figure 1: Speed of Different Models on 20 Newsgroups
(Documents per Second; Higher is better)

Different models will naturally be good at different things, because they conceptualize topics differently for instance:

  • SemanticSignalSeparation(\(S^3\)) conceptualizes topics as semantic axes, along which topics are distributed
  • ClusteringTopicModel finds clusters of documents and treats those as topics
  • KeyNMF conceptualizes topics as factors, or looked at it from a different angle, it finds clusters of words

You can find a detailed overview of how each of these models work in their respective tabs.

Some models are also capable of being used in a dynamic context, some can be fitted online, some can detect the number of topics for you and some can detect topic hierarchies. You can find an overview of these features in Table 2 below.

Figure 2: Models' Coherence and Diversity on 20 Newsgroups
(Higher is better)

Warning

You should take the results presented here with a grain of salt. A more comprehensive and in-depth analysis can be found in Kardos et al., 2024, though the general tendencies are similar. Note that some topic models are also less stable than others, and they might require tweaking optimal results (like BERTopic), while others perform well out-of-the-box, but are not as flexible (\(S^3\))

The quality of the topics you can get out of your topic model can depend on a lot of things, including your choice of vectorizer and encoder model. More rigorous evaluation regimes can be found in a number of studies on topic modeling.

Two usual metrics to evaluate models by are coherence and diversity. These metrics indicate how easy it is to interpret the topics provided by the topic model. Good models typically balance these to metrics, and should produce highly coherent and diverse topics. On Figure 2 you can see how good different models are on these metrics on 20 Newsgroups.

In general, the most balanced models are \(S^3\), Clustering models with centroid feature importance, GMM and KeyNMF, while FASTopic excels at diversity.


Model šŸ”¢ Multiple Topics per Document #āƒ£ Detecting Number of Topics šŸ“ˆ Dynamic Modeling šŸŒ² Hierarchical Modeling ā­ Inference over New Documents šŸŒ Cross-Lingual šŸŒŠ Online Fitting
KeyNMF āœ” āŒ āœ” āœ” āœ” āŒ āœ”
SemanticSignalSeparation āœ” āŒ āœ” āŒ āœ” āœ” āŒ
ClusteringTopicModel āŒ āœ” āœ” āœ” āŒ āœ” āŒ
GMM āœ” āŒ āœ” āŒ āœ” āœ” āŒ
AutoEncodingTopicModel āœ” āŒ āŒ āŒ āœ” āœ” āŒ
FASTopic āœ” āŒ āŒ āŒ āœ” āœ” āŒ

Table 2: Comparison of the models based on their capabilities

API Reference

turftopic.base.ContextualModel

Bases: BaseEstimator, TransformerMixin, TopicContainer

Base class for contextual topic models in Turftopic.

Source code in turftopic/base.py
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
class ContextualModel(BaseEstimator, TransformerMixin, TopicContainer):
    """Base class for contextual topic models in Turftopic."""

    @property
    def has_negative_side(self) -> bool:
        return False

    def encode_documents(self, raw_documents: Iterable[str]) -> np.ndarray:
        """Encodes documents with the sentence encoder of the topic model.

        Parameters
        ----------
        raw_documents: iterable of str
            Textual documents to encode.

        Return
        ------
        ndarray of shape (n_documents, n_dimensions)
            Matrix of document embeddings.
        """
        return self.encoder_.encode(raw_documents)

    @abstractmethod
    def fit_transform(
        self, raw_documents, y=None, embeddings: Optional[np.ndarray] = None
    ) -> np.ndarray:
        """Fits model and infers topic importances for each document.

        Parameters
        ----------
        raw_documents: iterable of str
            Documents to fit the model on.
        y: None
            Ignored, exists for sklearn compatibility.
        embeddings: ndarray of shape (n_documents, n_dimensions), optional
            Precomputed document encodings.

        Returns
        -------
        ndarray of shape (n_documents, n_topics)
            Document-topic matrix.
        """
        pass

    def fit(
        self, raw_documents, y=None, embeddings: Optional[np.ndarray] = None
    ):
        """Fits model on the given corpus.

        Parameters
        ----------
        raw_documents: iterable of str
            Documents to fit the model on.
        y: None
            Ignored, exists for sklearn compatibility.
        embeddings: ndarray of shape (n_documents, n_dimensions), optional
            Precomputed document encodings.
        """
        self.fit_transform(raw_documents, y, embeddings)
        return self

    def get_vocab(self) -> np.ndarray:
        """Get vocabulary of the model.

        Returns
        -------
        ndarray of shape (n_vocab)
            All terms in the vocabulary.
        """
        return self.vectorizer.get_feature_names_out()

    def get_feature_names_out(self) -> np.ndarray:
        """Get topic ids.

        Returns
        -------
        ndarray of shape (n_topics)
            IDs for each output feature of the model.
            This is useful, since some models have outlier
            detection, and this gets -1 as ID, instead of
            its index.
        """
        n_topics = self.components_.shape[0]
        try:
            classes = self.classes_
        except AttributeError:
            classes = list(range(n_topics))
        return np.asarray(classes)

    def prepare_topic_data(
        self,
        corpus: List[str],
        embeddings: Optional[np.ndarray] = None,
    ) -> TopicData:
        """Produces topic inference data for a given corpus, that can be then used and reused.
        Exists to allow visualizations out of the box with topicwizard.

        Parameters
        ----------
        corpus: list of str
            Documents to infer topical content for.
        embeddings: ndarray of shape (n_documents, n_dimensions)
            Embeddings of documents.

        Returns
        -------
        TopicData
            Information about topical inference in a dictionary.
        """
        if embeddings is None:
            embeddings = self.encode_documents(corpus)
        try:
            document_topic_matrix = self.transform(
                corpus, embeddings=embeddings
            )
        except (AttributeError, NotFittedError):
            document_topic_matrix = self.fit_transform(
                corpus, embeddings=embeddings
            )
        dtm = self.vectorizer.transform(corpus)  # type: ignore
        try:
            classes = self.classes_
        except AttributeError:
            classes = list(range(self.components_.shape[0]))
        res = TopicData(
            corpus=corpus,
            document_term_matrix=dtm,
            vocab=self.get_vocab(),
            document_topic_matrix=document_topic_matrix,
            document_representation=embeddings,
            topic_term_matrix=self.components_,  # type: ignore
            transform=getattr(self, "transform", None),
            topic_names=self.topic_names,
            classes=classes,
            has_negative_side=self.has_negative_side,
            hierarchy=getattr(self, "hierarchy", None),
        )
        return res

    def to_disk(self, out_dir: Union[Path, str]):
        """Persists model to directory on your machine.

        Parameters
        ----------
        out_dir: Path | str
            Directory to save the model to.
        """
        out_dir = Path(out_dir)
        out_dir.mkdir(exist_ok=True)
        package_versions = get_package_versions()
        with out_dir.joinpath("package_versions.json").open("w") as ver_file:
            ver_file.write(json.dumps(package_versions))
        joblib.dump(self, out_dir.joinpath("model.joblib"))

    def push_to_hub(self, repo_id: str):
        """Uploads model to HuggingFace Hub

        Parameters
        ----------
        repo_id: str
            Repository to upload the model to.
        """
        api = HfApi()
        api.create_repo(repo_id, exist_ok=True)
        with tempfile.TemporaryDirectory() as tmp_dir:
            readme_path = Path(tmp_dir).joinpath("README.md")
            with readme_path.open("w") as readme_file:
                readme_file.write(create_readme(self, repo_id))
            self.to_disk(tmp_dir)
            api.upload_folder(
                folder_path=tmp_dir,
                repo_id=repo_id,
                repo_type="model",
            )

encode_documents(raw_documents)

Encodes documents with the sentence encoder of the topic model.

Parameters:

Name Type Description Default
raw_documents Iterable[str]

Textual documents to encode.

required
Return

ndarray of shape (n_documents, n_dimensions) Matrix of document embeddings.

Source code in turftopic/base.py
29
30
31
32
33
34
35
36
37
38
39
40
41
42
def encode_documents(self, raw_documents: Iterable[str]) -> np.ndarray:
    """Encodes documents with the sentence encoder of the topic model.

    Parameters
    ----------
    raw_documents: iterable of str
        Textual documents to encode.

    Return
    ------
    ndarray of shape (n_documents, n_dimensions)
        Matrix of document embeddings.
    """
    return self.encoder_.encode(raw_documents)

fit(raw_documents, y=None, embeddings=None)

Fits model on the given corpus.

Parameters:

Name Type Description Default
raw_documents

Documents to fit the model on.

required
y

Ignored, exists for sklearn compatibility.

None
embeddings Optional[ndarray]

Precomputed document encodings.

None
Source code in turftopic/base.py
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
def fit(
    self, raw_documents, y=None, embeddings: Optional[np.ndarray] = None
):
    """Fits model on the given corpus.

    Parameters
    ----------
    raw_documents: iterable of str
        Documents to fit the model on.
    y: None
        Ignored, exists for sklearn compatibility.
    embeddings: ndarray of shape (n_documents, n_dimensions), optional
        Precomputed document encodings.
    """
    self.fit_transform(raw_documents, y, embeddings)
    return self

fit_transform(raw_documents, y=None, embeddings=None) abstractmethod

Fits model and infers topic importances for each document.

Parameters:

Name Type Description Default
raw_documents

Documents to fit the model on.

required
y

Ignored, exists for sklearn compatibility.

None
embeddings Optional[ndarray]

Precomputed document encodings.

None

Returns:

Type Description
ndarray of shape (n_documents, n_topics)

Document-topic matrix.

Source code in turftopic/base.py
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
@abstractmethod
def fit_transform(
    self, raw_documents, y=None, embeddings: Optional[np.ndarray] = None
) -> np.ndarray:
    """Fits model and infers topic importances for each document.

    Parameters
    ----------
    raw_documents: iterable of str
        Documents to fit the model on.
    y: None
        Ignored, exists for sklearn compatibility.
    embeddings: ndarray of shape (n_documents, n_dimensions), optional
        Precomputed document encodings.

    Returns
    -------
    ndarray of shape (n_documents, n_topics)
        Document-topic matrix.
    """
    pass

get_feature_names_out()

Get topic ids.

Returns:

Type Description
ndarray of shape (n_topics)

IDs for each output feature of the model. This is useful, since some models have outlier detection, and this gets -1 as ID, instead of its index.

Source code in turftopic/base.py
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
def get_feature_names_out(self) -> np.ndarray:
    """Get topic ids.

    Returns
    -------
    ndarray of shape (n_topics)
        IDs for each output feature of the model.
        This is useful, since some models have outlier
        detection, and this gets -1 as ID, instead of
        its index.
    """
    n_topics = self.components_.shape[0]
    try:
        classes = self.classes_
    except AttributeError:
        classes = list(range(n_topics))
    return np.asarray(classes)

get_vocab()

Get vocabulary of the model.

Returns:

Type Description
ndarray of shape (n_vocab)

All terms in the vocabulary.

Source code in turftopic/base.py
83
84
85
86
87
88
89
90
91
def get_vocab(self) -> np.ndarray:
    """Get vocabulary of the model.

    Returns
    -------
    ndarray of shape (n_vocab)
        All terms in the vocabulary.
    """
    return self.vectorizer.get_feature_names_out()

prepare_topic_data(corpus, embeddings=None)

Produces topic inference data for a given corpus, that can be then used and reused. Exists to allow visualizations out of the box with topicwizard.

Parameters:

Name Type Description Default
corpus List[str]

Documents to infer topical content for.

required
embeddings Optional[ndarray]

Embeddings of documents.

None

Returns:

Type Description
TopicData

Information about topical inference in a dictionary.

Source code in turftopic/base.py
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
def prepare_topic_data(
    self,
    corpus: List[str],
    embeddings: Optional[np.ndarray] = None,
) -> TopicData:
    """Produces topic inference data for a given corpus, that can be then used and reused.
    Exists to allow visualizations out of the box with topicwizard.

    Parameters
    ----------
    corpus: list of str
        Documents to infer topical content for.
    embeddings: ndarray of shape (n_documents, n_dimensions)
        Embeddings of documents.

    Returns
    -------
    TopicData
        Information about topical inference in a dictionary.
    """
    if embeddings is None:
        embeddings = self.encode_documents(corpus)
    try:
        document_topic_matrix = self.transform(
            corpus, embeddings=embeddings
        )
    except (AttributeError, NotFittedError):
        document_topic_matrix = self.fit_transform(
            corpus, embeddings=embeddings
        )
    dtm = self.vectorizer.transform(corpus)  # type: ignore
    try:
        classes = self.classes_
    except AttributeError:
        classes = list(range(self.components_.shape[0]))
    res = TopicData(
        corpus=corpus,
        document_term_matrix=dtm,
        vocab=self.get_vocab(),
        document_topic_matrix=document_topic_matrix,
        document_representation=embeddings,
        topic_term_matrix=self.components_,  # type: ignore
        transform=getattr(self, "transform", None),
        topic_names=self.topic_names,
        classes=classes,
        has_negative_side=self.has_negative_side,
        hierarchy=getattr(self, "hierarchy", None),
    )
    return res

push_to_hub(repo_id)

Uploads model to HuggingFace Hub

Parameters:

Name Type Description Default
repo_id str

Repository to upload the model to.

required
Source code in turftopic/base.py
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
def push_to_hub(self, repo_id: str):
    """Uploads model to HuggingFace Hub

    Parameters
    ----------
    repo_id: str
        Repository to upload the model to.
    """
    api = HfApi()
    api.create_repo(repo_id, exist_ok=True)
    with tempfile.TemporaryDirectory() as tmp_dir:
        readme_path = Path(tmp_dir).joinpath("README.md")
        with readme_path.open("w") as readme_file:
            readme_file.write(create_readme(self, repo_id))
        self.to_disk(tmp_dir)
        api.upload_folder(
            folder_path=tmp_dir,
            repo_id=repo_id,
            repo_type="model",
        )

to_disk(out_dir)

Persists model to directory on your machine.

Parameters:

Name Type Description Default
out_dir Union[Path, str]

Directory to save the model to.

required
Source code in turftopic/base.py
161
162
163
164
165
166
167
168
169
170
171
172
173
174
def to_disk(self, out_dir: Union[Path, str]):
    """Persists model to directory on your machine.

    Parameters
    ----------
    out_dir: Path | str
        Directory to save the model to.
    """
    out_dir = Path(out_dir)
    out_dir.mkdir(exist_ok=True)
    package_versions = get_package_versions()
    with out_dir.joinpath("package_versions.json").open("w") as ver_file:
        ver_file.write(json.dumps(package_versions))
    joblib.dump(self, out_dir.joinpath("model.joblib"))