Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 9 additions & 6 deletions bertopic/_bertopic.py
Original file line number Diff line number Diff line change
Expand Up @@ -916,12 +916,15 @@ def topics_over_time(
for topic in overlapping_topics
]

c_tf_idf.tolil()[current_overlap_idx] = (
(
c_tf_idf[current_overlap_idx] + previous_c_tf_idf[previous_overlap_idx] # noqa: F821
)
/ 2.0
).tolil()
if current_overlap_idx:
c_tf_idf_lil = c_tf_idf.tolil()
c_tf_idf_lil[current_overlap_idx] = (
(
c_tf_idf[current_overlap_idx] + previous_c_tf_idf[previous_overlap_idx] # noqa: F821
)
/ 2.0
).tolil()
c_tf_idf = c_tf_idf_lil.tocsr()

# Fine-tune the timestamp c-TF-IDF representation based on the global c-TF-IDF representation
# by simply taking the average of the two
Expand Down
57 changes: 57 additions & 0 deletions tests/test_variations/test_dynamic.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
import copy
import numpy as np
import pytest
from sklearn.cluster import KMeans
from sklearn.decomposition import PCA
from bertopic import BERTopic


@pytest.mark.parametrize(
Expand All @@ -20,3 +24,56 @@ def test_dynamic(model, documents, request):
assert topics_over_time.Frequency.sum() == len(documents)
assert set(topics_over_time.Topic.unique()) == set(topic_model.topics_)
assert len(topics_over_time.Timestamp.unique()) == len(set(timestamps))


def test_evolution_tuning_updates_c_tf_idf():
docs = [
"alpha alpha alpha",
"alpha alpha",
"beta",
"beta",
"gamma gamma gamma",
"gamma gamma",
"delta",
"delta",
]
timestamps = [1, 1, 2, 2, 1, 1, 2, 2]
embeddings = np.array(
[
[10.0, 0.0, 0.1],
[10.1, 0.1, 0.0],
[9.9, -0.1, 0.1],
[10.2, 0.0, -0.1],
[-10.0, 0.0, 0.1],
[-10.1, 0.1, 0.0],
[-9.9, -0.1, 0.1],
[-10.2, 0.0, -0.1],
]
)

topic_model = BERTopic(
umap_model=PCA(n_components=2, random_state=42),
hdbscan_model=KMeans(n_clusters=2, random_state=42, n_init=10),
)
topic_model.fit(docs, embeddings=embeddings)

tot_no_evolution = topic_model.topics_over_time(
docs,
timestamps,
evolution_tuning=False,
global_tuning=False,
)
tot_with_evolution = topic_model.topics_over_time(
docs,
timestamps,
evolution_tuning=True,
global_tuning=False,
)

t2_no_evo = tot_no_evolution.loc[tot_no_evolution.Timestamp == 2].set_index("Topic")["Words"].to_dict()
t2_evo = tot_with_evolution.loc[tot_with_evolution.Timestamp == 2].set_index("Topic")["Words"].to_dict()

assert t2_evo != t2_no_evo
all_t2_evo_words = " ".join(t2_evo.values())
assert "alpha" in all_t2_evo_words
assert "gamma" in all_t2_evo_words