Skip to content

Commit fa11651

Browse files
committed
Fix the representation pipeline: aspects from c-TF-IDF candidates, aspect labels and PartOfSpeech rows, an opt-in representation model over time and per class, and retire WordDocEmbedder
1 parent af7d541 commit fa11651

10 files changed

Lines changed: 140 additions & 76 deletions

File tree

‎bertopic/_bertopic.py‎

Lines changed: 23 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -850,6 +850,7 @@ def topics_over_time(
850850
datetime_format: str | None = None,
851851
evolution_tuning: bool = True,
852852
global_tuning: bool = True,
853+
use_representation_model: bool = False,
853854
) -> IntoDataFrame:
854855
return variations.topics_over_time(
855856
topic_model=self,
@@ -860,6 +861,7 @@ def topics_over_time(
860861
datetime_format=datetime_format,
861862
evolution_tuning=evolution_tuning,
862863
global_tuning=global_tuning,
864+
use_representation_model=use_representation_model,
863865
)
864866

865867
@wraps(variations.topics_per_class)
@@ -868,12 +870,14 @@ def topics_per_class(
868870
docs: list[str],
869871
classes: list[int | str],
870872
global_tuning: bool = True,
873+
use_representation_model: bool = False,
871874
) -> IntoDataFrame:
872875
return variations.topics_per_class(
873876
topic_model=self,
874877
docs=docs,
875878
classes=classes,
876879
global_tuning=global_tuning,
880+
use_representation_model=use_representation_model,
877881
)
878882

879883
@wraps(variations.approximate_distribution)
@@ -1593,15 +1597,12 @@ def generate_topic_labels(
15931597
check_is_fitted(self)
15941598
topic_labels = []
15951599
for topic in self._topics:
1596-
if aspect:
1597-
representation = topic.representations.get(aspect)
1598-
else:
1599-
representation = topic.representations.get("Main")
1600+
representation = topic.representations.get(aspect or "Main")
16001601

1601-
# For non-keyword representations (Label, StructuredJSON), use the
1602-
# topic label directly since word-level operations don't apply.
1602+
# For non-keyword representations (Label, StructuredJSON), use their
1603+
# label directly since word-level operations don't apply.
16031604
if representation and not isinstance(representation, Keywords):
1604-
label = topic.label
1605+
label = representation.label
16051606
if topic_prefix:
16061607
topic_label = f"{topic.id}{separator}{label}"
16071608
else:
@@ -2974,8 +2975,8 @@ def _extract_words_per_topic(
29742975
indices = np.take_along_axis(indices, sorted_indices, axis=1)
29752976
scores = np.take_along_axis(scores, sorted_indices, axis=1)
29762977

2977-
# Get top 30 words per topic based on c-TF-IDF score
2978-
topic_representations = {
2978+
# Get top 30 words per topic based on c-TF-IDF score, the candidates every representation starts from
2979+
candidates = {
29792980
topic_id: Keywords(
29802981
[
29812982
(words[word_index], score) if word_index is not None and score > 0 else ("", 0.00001)
@@ -2993,7 +2994,7 @@ def _extract_words_per_topic(
29932994
topic_representations = self._apply_representation_models(
29942995
representation_models=self.representation_model,
29952996
corpus=corpus,
2996-
topic_representations=topic_representations,
2997+
topic_representations=candidates.copy(),
29972998
c_tf_idf=c_tf_idf,
29982999
name="Main",
29993000
)
@@ -3002,10 +3003,10 @@ def _extract_words_per_topic(
30023003
# so cut the extra candidates back to the `top_n_words` that were asked for
30033004
topic_representations = {
30043005
topic_id: Keywords(keywords.data[: self.top_n_words])
3005-
for topic_id, keywords in topic_representations.items()
3006+
for topic_id, keywords in candidates.items()
30063007
}
30073008

3008-
# Extract topic representations other than the Main one (called aspects)
3009+
# Extract topic representations other than the Main one (called aspects), each from the candidates
30093010
if calculate_aspects and isinstance(self.representation_model, dict):
30103011
if aspect_to_return is not None:
30113012
if aspect_to_return not in self.representation_model:
@@ -3016,20 +3017,21 @@ def _extract_words_per_topic(
30163017
return self._apply_representation_models(
30173018
representation_models=self.representation_model[aspect_to_return],
30183019
corpus=corpus,
3019-
topic_representations=topic_representations.copy(),
3020+
topic_representations=candidates.copy(),
30203021
c_tf_idf=c_tf_idf,
30213022
name=aspect_to_return,
30223023
)
30233024
else:
30243025
for name, aspect_model in self.representation_model.items():
3025-
aspect = self._apply_representation_models(
3026-
representation_models=aspect_model,
3027-
corpus=corpus,
3028-
topic_representations=topic_representations.copy(),
3029-
c_tf_idf=c_tf_idf,
3030-
name=name,
3031-
)
3032-
self._topics.set_data(representations={name: aspect})
3026+
if name != "Main":
3027+
aspect = self._apply_representation_models(
3028+
representation_models=aspect_model,
3029+
corpus=corpus,
3030+
topic_representations=candidates.copy(),
3031+
c_tf_idf=c_tf_idf,
3032+
name=name,
3033+
)
3034+
self._topics.set_data(representations={name: aspect})
30333035

30343036
return topic_representations
30353037

‎bertopic/_topics.py‎

Lines changed: 22 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,11 @@ def word_scores(self) -> list[tuple[str, float]]:
4646
"""Words paired with their scores, which is how `get_topic` returns a topic."""
4747
return list(zip(self.words, self.scores))
4848

49+
@property
50+
def label(self) -> str:
51+
"""A short name for the topic, which only some representations can give."""
52+
return "No label could be created"
53+
4954
def __str__(self) -> str:
5055
"""String representation of the topic representation."""
5156
return str(self.data)
@@ -80,6 +85,11 @@ def scores(self) -> list[float]:
8085
"""Get just the keyword scores."""
8186
return [score for _, score in self.data]
8287

88+
@property
89+
def label(self) -> str:
90+
"""The top four keywords joined, which is how a topic is named by default."""
91+
return "_".join(self.words[:4])
92+
8393
def __str__(self) -> str:
8494
"""String representation of the top 5 keywords."""
8595
return ", ".join([word for word, _ in self.top_n(5)])
@@ -103,6 +113,11 @@ def words(self) -> list[str]:
103113
"""Return the label as a single-element list."""
104114
return [self.data] if self.data else []
105115

116+
@property
117+
def label(self) -> str:
118+
"""The label itself."""
119+
return self.data
120+
106121
def to_dict(self) -> dict:
107122
return {"type": "label", "data": self.data}
108123

@@ -122,6 +137,11 @@ def words(self) -> list[str]:
122137
"""Return the values of the structured JSON as a list of strings."""
123138
return [str(v) for v in self.data.values()] if self.data else []
124139

140+
@property
141+
def label(self) -> str:
142+
"""The `topic_label` or `label` field, or the whole JSON when it has neither."""
143+
return self.data.get("topic_label", self.data.get("label", str(self.data)))
144+
125145
def to_dict(self) -> dict:
126146
return {"type": "structured_json", "data": self.data}
127147

@@ -356,23 +376,12 @@ def label(self) -> str:
356376
"""Get the label of the topic.
357377
358378
If a custom label was set via `_label`, return it.
359-
Otherwise, generate a label from the Main representation.
379+
Otherwise, the Main representation gives the label.
360380
"""
361381
if self._label is not None:
362382
return self._label
363-
364-
# Generate label from representation
365383
representation = self.representations.get("Main")
366-
if isinstance(representation, Label):
367-
return representation.data
368-
elif isinstance(representation, StructuredJSON):
369-
return representation.data.get(
370-
"topic_label", representation.data.get("label", str(representation.data))
371-
)
372-
elif isinstance(representation, Keywords):
373-
return "_".join(representation.words[:4])
374-
else:
375-
return "No label could be created"
384+
return representation.label if representation else "No label could be created"
376385

377386
@property
378387
def name(self) -> str:

‎bertopic/backend/__init__.py‎

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
11
from ._base import BaseEmbedder
2-
from ._word_doc import WordDocEmbedder
32
from ._utils import languages
43
from bertopic._utils import NotInstalled
54

@@ -55,6 +54,5 @@
5554
"Model2VecBackend",
5655
"MultiModalBackend",
5756
"OpenAIBackend",
58-
"WordDocEmbedder",
5957
"languages",
6058
]

‎bertopic/backend/_base.py‎

Lines changed: 1 addition & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -8,15 +8,10 @@ class BaseEmbedder:
88
Arguments:
99
embedding_model: The main embedding model to be used for extracting
1010
document and word embedding
11-
word_embedding_model: The embedding model used for extracting word
12-
embeddings only. If this model is selected,
13-
then the `embedding_model` is purely used for
14-
creating document embeddings.
1511
"""
1612

17-
def __init__(self, embedding_model=None, word_embedding_model=None):
13+
def __init__(self, embedding_model=None):
1814
self.embedding_model = embedding_model
19-
self.word_embedding_model = word_embedding_model
2015

2116
def embed(self, documents: List[str], verbose: bool = False) -> np.ndarray:
2217
"""Embed a list of n documents/words into an n-dimensional

‎bertopic/backend/_word_doc.py‎

Lines changed: 0 additions & 28 deletions
This file was deleted.

‎bertopic/representation/_pos.py‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -110,7 +110,7 @@ def extract_topics(
110110
topic_model: A BERTopic model
111111
corpus: The input documents including (calculated) embeddings
112112
topic_representations: The candidate topic representations
113-
c_tf_idf: Not used
113+
c_tf_idf: The topic c-TF-IDF representation, with a row per topic in `topic_representations`
114114
embeddings: Not used
115115
116116
Returns:
@@ -156,11 +156,11 @@ def extract_topics(
156156
words_lookup = dict(zip(words, range(len(words))))
157157
updated_topics = {}
158158

159-
for topic, candidate_keywords in candidate_topics.items():
159+
for index, (topic, candidate_keywords) in enumerate(candidate_topics.items()):
160160
word_indices = np.sort(
161161
[words_lookup.get(keyword) for keyword in candidate_keywords if keyword in words_lookup]
162162
)
163-
vals = topic_model.c_tf_idf_[:, word_indices][topic + corpus._outliers]
163+
vals = c_tf_idf[:, word_indices][index]
164164
indices = np.argsort(np.array(vals.todense().reshape(1, -1))[0])[-self.top_n_words :][::-1]
165165
vals = np.sort(np.array(vals.todense().reshape(1, -1))[0])[-self.top_n_words :][::-1]
166166
topic_words = [(words[word_indices[index]], val) for index, val in zip(indices, vals)]

‎bertopic/variations/_topics_over_time.py‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,7 @@ def topics_over_time(
3232
datetime_format: str | None = None,
3333
evolution_tuning: bool = True,
3434
global_tuning: bool = True,
35+
use_representation_model: bool = False,
3536
) -> IntoDataFrame:
3637
"""Create topics over time.
3738
@@ -68,6 +69,10 @@ def topics_over_time(
6869
global_tuning: Fine-tune each topic representation at timestamp *t* by averaging its c-TF-IDF matrix
6970
with the global c-TF-IDF matrix. Turn this off if you want to prevent words in
7071
topic representations that could not be found in the documents at timestamp *t*.
72+
use_representation_model: Whether to use the representation model to extract topic words at each
73+
timestamp. This can yield better topic representations, but the model then
74+
runs for every topic at every timestamp, which is slow and, with an LLM,
75+
costly.
7176
7277
Returns:
7378
topics_over_time: A polars DataFrame with columns:
@@ -152,7 +157,7 @@ def topics_over_time(
152157

153158
# Extract the words per topic
154159
topic_representations = topic_model._extract_words_per_topic(
155-
words, selected_corpus, c_tf_idf, calculate_aspects=False, fine_tune=False
160+
words, selected_corpus, c_tf_idf, calculate_aspects=False, fine_tune=use_representation_model
156161
)
157162
new_topics = Topics().initialize(selected_corpus.topics)
158163
new_topics.set_data(representations={"Main": topic_representations})

‎bertopic/variations/_topics_per_class.py‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@ def topics_per_class(
2828
docs: list[str],
2929
classes: list[int | str],
3030
global_tuning: bool = True,
31+
use_representation_model: bool = False,
3132
) -> IntoDataFrame:
3233
"""Create topics per class.
3334
@@ -50,6 +51,10 @@ def topics_per_class(
5051
global_tuning: Fine-tune each topic representation for class c by averaging its c-TF-IDF matrix
5152
with the global c-TF-IDF matrix. Turn this off if you want to prevent words in
5253
topic representations that could not be found in the documents for class c.
54+
use_representation_model: Whether to use the representation model to extract topic words for each
55+
class. This can yield better topic representations, but the model then
56+
runs for every topic in every class, which is slow and, with an LLM,
57+
costly.
5358
5459
Returns:
5560
topics_per_class: A polars DataFrame with columns:
@@ -88,7 +93,7 @@ def topics_per_class(
8893

8994
# Extract the words per topic
9095
topic_representations = topic_model._extract_words_per_topic(
91-
words, selected_corpus, c_tf_idf, calculate_aspects=False, fine_tune=False
96+
words, selected_corpus, c_tf_idf, calculate_aspects=False, fine_tune=use_representation_model
9297
)
9398
new_topics = Topics().initialize(selected_corpus.topics)
9499
new_topics.set_data(representations={"Main": topic_representations})

‎tests/conftest.py‎

Lines changed: 22 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,8 @@
1010
from sklearn.cluster import KMeans, MiniBatchKMeans
1111
from sklearn.decomposition import PCA
1212
from bertopic.vectorizers import OnlineCountVectorizer
13-
from bertopic.representation import KeyBERTInspired, MaximalMarginalRelevance
13+
from bertopic.representation import BaseRepresentation, KeyBERTInspired, MaximalMarginalRelevance
14+
from bertopic._topics import Label
1415
from bertopic.dimensionality import BaseDimensionalityReduction
1516
from sklearn.linear_model import LogisticRegression
1617

@@ -41,6 +42,26 @@ def cuml_available():
4142
]
4243

4344

45+
class UppercaseLabel(BaseRepresentation):
46+
"""Labels each topic with its top two keywords in uppercase, and records the keywords it was handed."""
47+
48+
def __init__(self):
49+
self.calls = []
50+
51+
def extract_topics(self, topic_model, corpus, topic_representations, c_tf_idf):
52+
self.calls.append(topic_representations)
53+
return {
54+
topic: Label(" ".join(keywords.words[:2]).upper())
55+
for topic, keywords in topic_representations.items()
56+
}
57+
58+
59+
@pytest.fixture
60+
def uppercase_label():
61+
"""A representation model whose output is easy to recognize, so a test can tell whether it ran."""
62+
return UppercaseLabel()
63+
64+
4465
@pytest.fixture(scope="session")
4566
def embedding_model():
4667
model = SentenceTransformer("all-MiniLM-L6-v2")

0 commit comments

Comments
 (0)