Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
30 commits
Select commit Hold shift + click to select a range
e319d9c
Added ability to freeze G and F in SNMF
x-tabdeveloping Nov 20, 2026
069884d
Added row-wise normalization to SNMF instead of whole matrix norm
x-tabdeveloping Nov 20, 2026
ce940db
Added supervised model fitting
x-tabdeveloping Nov 20, 2026
634864a
Replaced merge_vectorizers with UnionVectorizer
x-tabdeveloping Nov 23, 2026
fd90023
Fixed bug with updating
x-tabdeveloping Nov 23, 2026
3763ab7
Bugfixes in UnionVectorizer
x-tabdeveloping Nov 23, 2026
7dbc229
update vocabulary avoids padding components when components_ is a pro…
x-tabdeveloping Nov 23, 2026
2c356e0
Updated sparse diagonal building to new version of scipy
x-tabdeveloping Nov 23, 2026
f4bd5b2
Added map() method to TopicNode
x-tabdeveloping Nov 23, 2026
42bcfb8
Added hierarchy merging
x-tabdeveloping Nov 23, 2026
a19e54c
Added model merging to clustering models
x-tabdeveloping Nov 23, 2026
0d4d86e
Added fit() to UnionVectorizer
x-tabdeveloping Nov 23, 2026
431fa45
Added merging based on topic embeddings
x-tabdeveloping Nov 23, 2026
d3500e2
Added topic embedding-based merging to clustering models
x-tabdeveloping Nov 23, 2026
4d8c818
Added supervised fitting to clustering topic model
x-tabdeveloping Nov 24, 2026
13aa039
Added merge_models to clustering topic models
x-tabdeveloping Nov 24, 2026
10f7cb9
merge_with now returns self
x-tabdeveloping Nov 24, 2026
672f6e8
Corrected return value in merge_with docstring
x-tabdeveloping Nov 24, 2026
bbee6e9
Added 'merge_models' and 'merge_with' to senstopic
x-tabdeveloping Nov 24, 2026
8b35301
Added docstring to merge_models
x-tabdeveloping Nov 24, 2026
985916d
Added model merging to Topeax
x-tabdeveloping Nov 24, 2026
ae545c9
Added supervised modelling to S3
x-tabdeveloping Nov 24, 2026
23e8c04
Implemented model merging for S3
x-tabdeveloping Nov 24, 2026
b6a9c0e
Added tests for merging
x-tabdeveloping Nov 24, 2026
ef7a078
added some docs on model_merging
x-tabdeveloping Nov 24, 2026
86ec6c1
Added more docs
x-tabdeveloping Nov 24, 2026
58626a0
Version bump
x-tabdeveloping Nov 24, 2026
e7df9e9
Fixed parametrize in test
x-tabdeveloping Nov 24, 2026
c6f9ffb
Added from future import annotations to all models
x-tabdeveloping Nov 24, 2026
4dcfb14
Removed Topeax from merge testing and madee batches larger
x-tabdeveloping Nov 24, 2026
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
90 changes: 90 additions & 0 deletions docs/supervised.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
# Supervised Topic Modelling

Some topic models are capable of learning topics from labelled documents.
In these cases, instead of the models recovering latent topics using unsupervised learning, the topic signal is provided to the model, and the model learns topic representations from the given signals.

Currently, a handful of models are supported, each of which have a `fit_supervised()` method.
One has to pass a document-topic-matrix of shape `(n_documents, n_topics)` to this method as a `y`.
If you only have access to categorical labels, you can use `turftopic.utils.safe_binarize` to convert them into a one-hot document-topic-matrix.

Here is an example of 20Newsgroups using different topic models:

=== "SensTopic"

```python
from sklearn.datasets import fetch_20newsgroups

from turftopic import SensTopic
from turftopic.utils import safe_binarize

ds = fetch_20newsgroups(
subset="all",
remove=("headers", "footers", "quotes"),
)
corpus = ds.data
target = ds.target
unique_targets = np.unique(target)
# We use safe_binarize to convert the class labels to a one-hot matrix:
y = safe_binarize(target, unique_targets)

model = SensTopic()
model.fit_supervised(corpus, y=y)
model.rename_topics(ds.target_names)
model.print_topics()
```

=== "ClusteringTopicModel (by extension BERTopic and Top2Vec too)"

```python
from sklearn.datasets import fetch_20newsgroups

from turftopic import ClusteringTopicModel
from turftopic.utils import safe_binarize

ds = fetch_20newsgroups(
subset="all",
remove=("headers", "footers", "quotes"),
)
corpus = ds.data
target = ds.target
unique_targets = np.unique(target)
# We use safe_binarize to convert the class labels to a one-hot matrix:
y = safe_binarize(target, unique_targets)

model = ClusteringTopicModel()
model.fit_supervised(corpus, y=y)
model.rename_topics(ds.target_names)
model.print_topics()
```

=== "SemanticSignalSeparation"

```python
from sklearn.datasets import fetch_20newsgroups

from turftopic import SemanticSignalSeparation
from turftopic.utils import safe_binarize

ds = fetch_20newsgroups(
subset="all",
remove=("headers", "footers", "quotes"),
)
corpus = ds.data
target = ds.target
unique_targets = np.unique(target)
# We use safe_binarize to convert the class labels to a one-hot matrix:
y = safe_binarize(target, unique_targets)

model = SemanticSignalSeparation(10)
model.fit_supervised(corpus, y=y)
model.rename_topics(ds.target_names)
model.print_topics()
```

| Topic ID | Topic Name | Highest Ranking |
| - | - | - |
| 0 | alt.atheism | intellectually, sophistication, terminology, hypothesis, atheists, rationality, analogies, theoretical, exists, irrational |
| 1 | comp.graphics | zooming, plots, plotting, procedural, frames, animations, animation, animated, visuals, visualization |
| | ... |
| 18 | talk.politics.misc | hillary, republican, parties, clinton, libertarian, unions, reagan, politician, president, trickle |
| 19 | talk.religion.misc | beneath, ancestor, noble, born, childhood, servants, father, teach, comprised, instructed |
119 changes: 116 additions & 3 deletions docs/topic_merging.md
Original file line number Diff line number Diff line change
@@ -1,11 +1,124 @@
# Model/Topic Merging

In Turftopic, some models allow you to merge information from multiple topic models into one.
Currently, this can be done with SensTopic's `partial_fit` method, which updates a topic model by merging it with an identically initialized model
on a new batch of data.
More models will be implemented in the future.
This guide teaches you about the different methods for merging topics and explanations on why they are useful, and how you should use them.

This can be done with the models' classes' `merge_models()` method or a given model's `merge_with(other)` method.
Currently a limited number of models are supported but we are working on extending model merging to as many models as possible.

=== "SensTopic"

```python
from turftopic import SensTopic
from sentence_transformers import SentenceTransformer

encoder = SentenceTransformer("all-MiniLM-L6-v2")
batch_size = 2500
model_kwargs = dict(
n_components="auto",
random_state=42,
encoder=encoder,
)
models = []
for batch_start in range(0, len(corpus), batch_size):
batch_end = batch_start + batch_size
batch_model = SemanticSignalSeparation(**model_kwargs)
# Calculating doc_topic_matrix for current batch
batch_model.fit(
corpus[batch_start:batch_end],
embeddings=embeddings[batch_start:batch_end],
)
models.append(batch_model)
model = SensTopic.merge_models(models, merge_method="symmetric_mean", match_threshold=0.8)
model.print_topics()
```

=== "ClusteringTopicModel (by extension BERTopic and Top2Vec too)"

```python
from turftopic import ClusteringTopicModel
from sentence_transformers import SentenceTransformer

encoder = SentenceTransformer("all-MiniLM-L6-v2")
batch_size = 2500
model_kwargs = dict(
random_state=42,
encoder=encoder,
)
models = []
for batch_start in range(0, len(corpus), batch_size):
batch_end = batch_start + batch_size
batch_model = ClusteringTopicModel(**model_kwargs)
batch_model.fit(
corpus[batch_start:batch_end],
embeddings=embeddings[batch_start:batch_end],
)
models.append(batch_model)
model = ClusteringTopicModel.merge_models(models, merge_method="symmetric_mean", match_threshold=0.7)
model.print_topics()
```

=== "SemanticSignalSeparation"

```python
from turftopic import SemanticSignalSeparation
from sentence_transformers import SentenceTransformer

encoder = SentenceTransformer("all-MiniLM-L6-v2")
batch_size = 2500
model_kwargs = dict(
n_components=10,
random_state=42,
encoder=encoder,
)
models = []
for batch_start in range(0, len(corpus), batch_size):
batch_end = batch_start + batch_size
batch_model = SemanticSignalSeparation(**model_kwargs)
batch_model.fit(
corpus[batch_start:batch_end],
embeddings=embeddings[batch_start:batch_end],
)
models.append(batch_model)
model = SemanticSignalSeparation.merge_models(models, merge_method="symmetric_mean", match_threshold=0.7)
model.print_topics()
```

=== "Topeax"

```python
from turftopic import Topeax
from sentence_transformers import SentenceTransformer

encoder = SentenceTransformer("all-MiniLM-L6-v2")
batch_size = 2500
model_kwargs = dict(
n_components=10,
random_state=42,
encoder=encoder,
)
models = []
for batch_start in range(0, len(corpus), batch_size):
batch_end = batch_start + batch_size
batch_model = Topeax(**model_kwargs)
batch_model.fit(
corpus[batch_start:batch_end],
embeddings=embeddings[batch_start:batch_end],
)
models.append(batch_model)
model = Topeax.merge_models(models, merge_method="symmetric_mean", match_threshold=0.7)
model.print_topics()
```

| Topic ID | Highest Ranking |
| - | - |
| 0 | stream, broadcast, fm, interference, stations, mono, soc, wire, tv, clock |
| 1 | preferably, speculation, wondered, suggests, rumors, interesting, mentioned, btw, ask, rumor |
| | ... |
| 19 | mph, mileage, speeds, specs, steering, motorcycle, symptoms, vehicles, driving, tires |
| 20 | bigotry, immoral, morality, morals, abortion, skepticism, homosexuality, homosexuals, philosophy, judgment |
| 21 | cite, cited, writer, records, literature, fields, saves, writes, reports, references |

Topic merging consists of the following steps:

1. Determine topic matches based on some **topic representations** (typically a model's `components_` attribute) and a **similarity threshold**
Expand Down
1 change: 1 addition & 0 deletions mkdocs.yml
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ nav:
- Concept Induction: concept_induction.md
- Multimodal Modeling (Experimental): multimodal.md
- Model Merging: topic_merging.md
- Supervised Topic Modeling: supervised.md
- Distribution Learning: distribution_learning.md
- Implement a Wrapper/Custom Model: custom_model.md
- Examples:
Expand Down
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ profile = "black"

[project]
name = "turftopic"
version = "0.30.0"
version = "0.31.0"
description = "Topic modeling with contextual representations from sentence transformers."
authors = [
{ name = "Márton Kardos <power.up1163@gmail.com>", email = "martonkardos@cas.au.dk" }
Expand Down
20 changes: 19 additions & 1 deletion tests/test_integration.py
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,7 @@ def generate_dates(
KeyNMF(3, encoder=trf),
]

online_models = [KeyNMF(3, encoder=trf)]
online_models = [KeyNMF(3, encoder=trf), SensTopic(3, encoder=trf)]

late_models = [
CTop2Vec(encoder=trf),
Expand Down Expand Up @@ -152,6 +152,24 @@ def test_fit_online(model):
df = pd.read_csv(out_path)


supports_merging = [SensTopic, ClusteringTopicModel]


@pytest.mark.parametrize("model_cls", supports_merging)
def test_merging(model_cls):
model_kwargs = dict(encoder=trf)
models = []
for batch in batched(zip(texts, embeddings), 100):
batch_text, batch_embedding = zip(*batch)
batch_text = list(batch_text)
batch_embedding = np.stack(batch_embedding)
new_model = model_cls(**model_kwargs)
new_model.fit(batch_text, embeddings=batch_embedding)
models.append(new_model)
model = model_cls.merge_models(models)
model.print_topics()


OPTIONAL_FIELDS = [
"topic_names",
"classes",
Expand Down
21 changes: 13 additions & 8 deletions turftopic/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
from abc import ABC, abstractmethod
from functools import partial
from pathlib import Path
from typing import Iterable, List, Optional, Union
from typing import Callable, Iterable, List, Optional, Union

import joblib
import numpy as np
Expand All @@ -16,7 +16,7 @@
from turftopic.data import TopicData
from turftopic.encoders import ExternalEncoder
from turftopic.serialization import create_readme, get_package_versions
from turftopic.vectorizers.merging import merge_vectorizers
from turftopic.vectorizers.merging import UnionVectorizer

Encoder = Union[ExternalEncoder, SentenceTransformer]

Expand Down Expand Up @@ -125,11 +125,16 @@ def _update_vocab_embeddings(self, diff_terms, diff_vocab_embeddings=None):
def _pad_components(self, n_diff_terms: int):
NO_PADDING = (0, 0)
if getattr(self, "components_", None) is not None:
self.components_ = np.pad(
self.components_,
# (n_timebins, n_components, n_terms)
[NO_PADDING, (0, n_diff_terms)],
)
# In some cases, components_ is a property
# in those cases we will not update.
try:
self.components_ = np.pad(
self.components_,
# (n_timebins, n_components, n_terms)
[NO_PADDING, (0, n_diff_terms)],
)
except AttributeError:
pass
if getattr(self, "temporal_components_", None) is not None:
self.temporal_components_ = np.pad(
self.temporal_components_,
Expand Down Expand Up @@ -161,7 +166,7 @@ def update_vocabulary(self, other_vectorizer_or_model):
else:
other_vectorizer = other_vectorizer_or_model
# Joining vectorizers
joint_vectorizer = merge_vectorizers(self.vectorizer, other_vectorizer)
joint_vectorizer = UnionVectorizer(self.vectorizer, other_vectorizer)
# Finding term difference
old_vectorizer = self.vectorizer
old_terms = old_vectorizer.get_feature_names_out()
Expand Down
4 changes: 2 additions & 2 deletions turftopic/feature_importance.py
Original file line number Diff line number Diff line change
Expand Up @@ -149,7 +149,7 @@ def soft_ctf_idf(
tf = (term_importance.T / (overall_in_topic + eps)).T
idf = np.log(n_docs / (np.abs(term_importance).sum(axis=0) + eps))
ctf_idf = tf * idf
idf_diag = spr.diags(
idf_diag = spr.diags_array(
idf,
offsets=0,
shape=(doc_term_matrix.shape[1], doc_term_matrix.shape[1]),
Expand Down Expand Up @@ -194,7 +194,7 @@ def ctf_idf(
component = freq * np.log(1 + average / overall_freq)
components.append(component)
idf = np.log((average / overall_freq) + 1)
idf_diag = spr.diags(
idf_diag = spr.diags_array(
idf,
offsets=0,
shape=(doc_term_matrix.shape[1], doc_term_matrix.shape[1]),
Expand Down
14 changes: 13 additions & 1 deletion turftopic/hierarchical.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
from __future__ import annotations

from dataclasses import dataclass
from typing import Optional
from typing import Callable, Optional

import numpy as np
from rich.console import Console
Expand Down Expand Up @@ -318,6 +318,18 @@ def _append_path(self, path_prefix: int):
for child in self.children:
child._append_path(path_prefix)

def map(self, f: Callable[TopicNode, TopicNode]) -> TopicNode:
"""Maps a function to each node of the hierarchy.
This function could be in-place or not, the original hierarchy will not be modified.
"""
res = self.copy(deep=False)
if res.children is None:
return f(res)
else:
children = [child.map(f) for child in res.children]
res.children = children
return res

def copy(self, deep: bool = True) -> TopicNode:
"""Creates a copy of the given node.

Expand Down
Loading
Loading