From e319d9c9b396b010f20b0e92631b2905d7f24712 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?M=C3=A1rton=20Kardos?= Date: Fri, 20 Nov 2026 13:58:31 +0100 Subject: [PATCH 01/30] Added ability to freeze G and F in SNMF --- turftopic/models/_snmf.py | 77 ++++++++++++++++++++++++++++++++++----- 1 file changed, 68 insertions(+), 9 deletions(-) diff --git a/turftopic/models/_snmf.py b/turftopic/models/_snmf.py index 5e134b0..84ade55 100644 --- a/turftopic/models/_snmf.py +++ b/turftopic/models/_snmf.py @@ -37,7 +37,9 @@ def init_G( ) -> np.ndarray: """Returns W""" if n_components > X.shape[1]: - return np.random.default_rng(random_state).normal(0, 1, size=(X.shape[1], n_components)) + return np.random.default_rng(random_state).normal( + 0, 1, size=(X.shape[1], n_components) + ) kmeans = KMeans(n_components, random_state=random_state).fit(X.T) # n_components, n_columns G = safe_binarize(kmeans.labels_, classes=np.arange(n_components)) @@ -60,7 +62,8 @@ def separate(A): def update_F(X, G, F, n_freeze=None): - F_new = X @ G @ jnp.linalg.pinv(G.T @ G) + inv = jnp.linalg.pinv(G.T @ G) + F_new = jnp.linalg.multi_dot([X, G, inv]) if n_freeze is None: return F_new else: @@ -70,7 +73,7 @@ def update_F(X, G, F, n_freeze=None): def update_G(X, G, F, sparsity=0, n_freeze=None): G_new = G pos_xtf, neg_xtf = separate(X.T @ F) - pos_gftf, neg_gftf = separate(G_new @ (F.T @ F)) + pos_gftf, neg_gftf = separate(jnp.linalg.multi_dot([G_new, F.T, F])) numerator = pos_xtf + neg_gftf denominator = neg_xtf + pos_gftf denominator += sparsity @@ -106,6 +109,7 @@ def inference_loop( max_iter=200, track_convergence=True, freeze_F=False, + freeze_G=False, ): init_error = rec_err(X.T, F, G) init_state = { @@ -155,6 +159,16 @@ def _body_fn(state): "n_iter": state["n_iter"] + 1, } + if freeze_G: + F = update_F(X, G, F, n_freeze=n_freeze) + new_error = rec_err(X.T, F, G) + return { + "G": G, + "F": F, + "error": new_error, + "error_diff": init_state["error"] - new_error, + "n_iter": 1, + } return while_loop(_cond_fn, _body_fn, init_state) @@ -179,6 +193,28 @@ def infer_doc_topic( ) +@jit +def infer_components( + X, + G, + F, + sparsity=0, + tol=1e-5, + max_iter=200, +): + return inference_loop( + X, + G, + F, + sparsity=sparsity, + tol=tol, + max_iter=max_iter, + track_convergence=True, + freeze_F=False, + freeze_G=True, + ) + + @jit def infer_model( X, @@ -231,6 +267,8 @@ def __init__( progress_bar: bool = True, random_state: Optional[int] = None, sparsity: float = 0.0, + F=None, + G=None, verbose: bool = False, ): self.n_components = n_components @@ -240,15 +278,36 @@ def __init__( self.random_state = random_state self.sparsity = sparsity self.verbose = verbose + self.F = F + self.G = G + self.freeze_G = False + self.freeze_F = False + if self.F is not None: + self.components_ = np.array(F).T + self.freeze_F = True + if self.G is not None: + self.freeze_G = True def fit_transform(self, X: np.ndarray, y=None): - G = init_G(X.T, self.n_components, random_state=self.random_state) - F = update_F(X.T, G, F=None) + if self.G is None: + G = init_G(X.T, self.n_components, random_state=self.random_state) + else: + G = jnp.array(self.G) + if self.F is None: + F = update_F(X.T, G, F=None) + else: + F = self.F self.error_at_init = rec_err(X.T, F, G) - last_state = infer_model( - X=X, - G=G, - F=F, + if not (self.freeze_F or self.freeze_G): + inference_fn = infer_model + elif self.freeze_F: + inference_fn = infer_doc_topic + else: + inference_fn = infer_components + last_state = inference_fn( + X, + G, + F, sparsity=self.sparsity, tol=self.tol, max_iter=self.max_iter, From 069884d5d634ca5dbcf5954714d1efc505df679d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?M=C3=A1rton=20Kardos?= Date: Fri, 20 Nov 2026 14:14:32 +0100 Subject: [PATCH 02/30] Added row-wise normalization to SNMF instead of whole matrix norm --- turftopic/models/_snmf.py | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/turftopic/models/_snmf.py b/turftopic/models/_snmf.py index 84ade55..ac0148b 100644 --- a/turftopic/models/_snmf.py +++ b/turftopic/models/_snmf.py @@ -80,7 +80,8 @@ def update_G(X, G, F, sparsity=0, n_freeze=None): denominator = jnp.maximum(denominator, EPSILON) delta_G_new = jnp.sqrt(numerator / denominator) G_new *= delta_G_new - G_new = G_new / jnp.maximum(jnp.linalg.norm(G_new), EPSILON) + row_norms = jnp.maximum(jnp.linalg.norm(G_new, axis=1), EPSILON) + G_new = (G_new.T / row_norms).T if n_freeze is None: return G_new else: @@ -160,7 +161,7 @@ def _body_fn(state): } if freeze_G: - F = update_F(X, G, F, n_freeze=n_freeze) + F = update_F(X.T, G, F, n_freeze=n_freeze) new_error = rec_err(X.T, F, G) return { "G": G, From ce940db81237475c9199ea411af10ae199cc4a29 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?M=C3=A1rton=20Kardos?= Date: Fri, 20 Nov 2026 14:14:55 +0100 Subject: [PATCH 03/30] Added supervised model fitting --- turftopic/models/senstopic.py | 67 ++++++++++++++++++++++++++++++++++- 1 file changed, 66 insertions(+), 1 deletion(-) diff --git a/turftopic/models/senstopic.py b/turftopic/models/senstopic.py index 5784c0e..83416bf 100644 --- a/turftopic/models/senstopic.py +++ b/turftopic/models/senstopic.py @@ -169,6 +169,71 @@ def estimate_components( ) return self.components_ + def fit_supervised( + self, + raw_documents, + y: np.ndarray, + embeddings: Optional[np.ndarray] = None, + ): + console = Console() + self.embeddings = embeddings + with console.status("Fitting model") as status: + if self.embeddings is None: + status.update("Encoding documents") + self.embeddings = self.encode_documents(raw_documents) + console.log("Documents encoded.") + doc_topic = y + self.n_components_ = y.shape[1] + self.decomposition = SNMF( + self.n_components_, + max_iter=self.max_iter, + sparsity=self.sparsity, + random_state=self.random_state, + G=y, + ) + status.update("Calculating components") + self.decomposition.fit(embeddings) + console.log("Components calculated.") + status.update("Extracting terms.") + vocab = self.vectorizer.fit(raw_documents).get_feature_names_out() + console.log("Term extraction done.") + if getattr(self, "vocab_embeddings", None) is None: + status.update("Encoding vocabulary") + self.vocab_embeddings = self.encode_vocabulary_items(vocab) + if self.vocab_embeddings.shape[1] != self.embeddings.shape[1]: + raise ValueError( + NOT_MATCHING_ERROR.format( + n_dims=self.embeddings.shape[1], + n_word_dims=self.vocab_embeddings.shape[1], + ) + ) + console.log("Vocabulary encoded.") + status.update("Estimating term importances") + vocab_topic = self.decomposition.transform(self.vocab_embeddings) + self.axial_components_ = vocab_topic.T + if self.feature_importance == "axial": + self.components_ = self.axial_components_ + elif self.feature_importance == "angular": + self.components_ = self.angular_components_ + elif self.feature_importance == "combined": + self.components_ = ( + np.square(self.axial_components_) + * self.angular_components_ + ) + self.top_documents = self.get_top_documents( + raw_documents, document_topic_matrix=doc_topic + ) + self.document_topic_matrix = doc_topic + console.log("Model fitting done.") + self.hierarchy = TopicNode.create_root( + self, self.components_, self.document_topic_matrix + ) + if self.multilevel: + status.update("Estimating subtopics.") + self.add_subtopics() + console.log("Subtopics estimated.") + return self + def fit_transform( self, raw_documents, y=None, embeddings: Optional[np.ndarray] = None ) -> np.ndarray: @@ -205,7 +270,7 @@ def fit_transform( console.log("Term extraction done.") if getattr(self, "vocab_embeddings", None) is None: status.update("Encoding vocabulary") - self.vocab_embeddings = self.encode_documents(vocab) + self.vocab_embeddings = self.encode_vocabulary_items(vocab) if self.vocab_embeddings.shape[1] != self.embeddings.shape[1]: raise ValueError( NOT_MATCHING_ERROR.format( From 634864acef624914d4ac7e9becf1661674c8fd4a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?M=C3=A1rton=20Kardos?= Date: Mon, 23 Nov 2026 09:35:49 +0100 Subject: [PATCH 04/30] Replaced merge_vectorizers with UnionVectorizer --- turftopic/base.py | 4 +- turftopic/vectorizers/merging.py | 91 ++++++++++++++++++++++++++++++++ 2 files changed, 93 insertions(+), 2 deletions(-) diff --git a/turftopic/base.py b/turftopic/base.py index 7f60230..8ca6efd 100644 --- a/turftopic/base.py +++ b/turftopic/base.py @@ -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] @@ -161,7 +161,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() diff --git a/turftopic/vectorizers/merging.py b/turftopic/vectorizers/merging.py index a4787da..ead4a22 100644 --- a/turftopic/vectorizers/merging.py +++ b/turftopic/vectorizers/merging.py @@ -1,6 +1,7 @@ import warnings import numpy as np +import scipy.sparse as spr from sklearn.base import BaseEstimator, TransformerMixin from sklearn.feature_extraction.text import CountVectorizer @@ -74,3 +75,93 @@ def merge_vectorizers( "At least one vectorizer is not a CountVectorizer, returning a VocabStore object." ) return VocabStore.from_merge(left_vectorizer, right_vectorizer) + + +class UnionVectorizer(BaseEstimator, TransformerMixin): + def __init__(self, left: TransformerMixin, right: TransformerMixin): + self.left = left + self.right = right + if (getattr(self.left, "vocabulary_", None) is not None) and ( + (getattr(self.right, "vocabulary_", None) is not None) + ): + self.merge_vocab(self.left, self.right) + + def merge_vocab(self, left: TransformerMixin, right: TransformerMixin): + left_terms = left.get_feature_names_out() + right_terms = right.get_feature_names_out() + # Extracting terms present in right but not in left + self.diff_terms_ = list(set(right_terms) - set(left_terms)) + self.joint_terms_ = list(left_terms) + self.diff_terms_ + left_terms_to_idx = {term: i for i, term in enumerate(left_terms)} + right_terms_to_idx = {term: i for i, term in enumerate(right_terms)} + self.joint_to_left_ = [ + left_terms_to_idx.get(term, None) for term in self.joint_terms_ + ] + self.joint_to_right_ = [ + right_terms_to_idx.get(term, None) for term in self.joint_terms_ + ] + joint_to_idx = self.vocabulary_ + self.left_to_joint_ = { + left_idx: joint_to_idx[left_term] + for left_term, left_idx in left_terms_to_idx.items() + } + self.right_to_joint_ = { + right_idx: joint_to_idx[right_term] + for right_term, right_idx in right_terms_to_idx.items() + } + self.diff_indices_ = np.array( + [right_terms_to_idx[term] for term in self.diff_terms_] + ) + + def fit_transform(self, raw_documents, y=None): + left_X = self.left.fit_transform(raw_documents) + right_X = self.right.fit_transform(raw_documents) + self.merge_vocab(left_X, right_X) + hstack = spr.hstack if spr.is_sparse(left_X) else np.hstack + return hstack([left_X, right_X[:, self.diff_indices_]]) + + def transform(self, raw_documents, y=None): + left_X = self.left.transform(raw_documents) + right_X = self.right.transform(raw_documents) + hstack = spr.hstack if spr.is_sparse(left_X) else np.hstack + return hstack([left_X, right_X[:, self.diff_indices_]]) + + def pad_left(self, left_X, pad_value=0): + if spr.is_sparse(left_X): + joint_X = spr.lil_array( + (left_X.shape[0], self.n_vocab), dtype=left_X.dtype + ) + else: + joint_X = np.full((left_X.shape[0], self.n_vocab), pad_value) + joint_X[:, : left_X.shape[1]] = left_X + if spr.is_sparse(joint_X): + joint_X = spr.csr_array(joint_X) + return joint_X + + def pad_right(self, right_X, pad_value=0): + if spr.is_sparse(right_X): + joint_X = spr.lil_array( + (right_X.shape[0], self.n_vocab), dtype=right_X.dtype + ) + else: + joint_X = np.full( + (right_X.shape[0], self.n_vocab), + pad_value, + dtype=right_X.dtype, + ) + for joint_idx, right_idx in enumerate(self.joint_to_right_): + if right_idx is not None: + joint_X[:, joint_idx] = right_X[:, right_idx] + if spr.is_sparse(joint_X): + joint_X = spr.csr_array(joint_X) + return joint_X + + def get_feature_names_out(self): + return np.array(self.joint_terms_) + + def n_vocab(self): + return len(self.joint_terms_) + + @property + def vocabulary_(self): + return dict(zip(self.joint_terms_, range(len(self.joint_terms_)))) From fd900230de7ef6f37423aca4b20fc1e9b3602a6d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?M=C3=A1rton=20Kardos?= Date: Mon, 23 Nov 2026 10:43:23 +0100 Subject: [PATCH 05/30] Fixed bug with updating --- turftopic/models/senstopic.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/turftopic/models/senstopic.py b/turftopic/models/senstopic.py index 83416bf..7ca01e1 100644 --- a/turftopic/models/senstopic.py +++ b/turftopic/models/senstopic.py @@ -502,7 +502,7 @@ def partial_fit_transform( t_dt = np.zeros( (new_doc_topic.shape[0], self.decomposition.n_components) ) - for i_new, joint_index in enumerate(merge_history[1]): + for i_new, joint_index in enumerate(self.merge_history_[1]): t_dt[:, joint_index] = new_doc_topic[:, i_new] new_imp, new_comp = self._fit_timebin(embeddings, t_dt) t_components.append(new_comp) From 3763ab7d9da743eeb9fd634acec2428ae33ae13a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?M=C3=A1rton=20Kardos?= Date: Mon, 23 Nov 2026 16:44:30 +0100 Subject: [PATCH 06/30] Bugfixes in UnionVectorizer --- turftopic/vectorizers/merging.py | 15 ++++++++------- 1 file changed, 8 insertions(+), 7 deletions(-) diff --git a/turftopic/vectorizers/merging.py b/turftopic/vectorizers/merging.py index ead4a22..0cb4577 100644 --- a/turftopic/vectorizers/merging.py +++ b/turftopic/vectorizers/merging.py @@ -116,30 +116,30 @@ def merge_vocab(self, left: TransformerMixin, right: TransformerMixin): def fit_transform(self, raw_documents, y=None): left_X = self.left.fit_transform(raw_documents) right_X = self.right.fit_transform(raw_documents) - self.merge_vocab(left_X, right_X) - hstack = spr.hstack if spr.is_sparse(left_X) else np.hstack + self.merge_vocab(self.left, self.right) + hstack = spr.hstack if spr.issparse(left_X) else np.hstack return hstack([left_X, right_X[:, self.diff_indices_]]) def transform(self, raw_documents, y=None): left_X = self.left.transform(raw_documents) right_X = self.right.transform(raw_documents) - hstack = spr.hstack if spr.is_sparse(left_X) else np.hstack + hstack = spr.hstack if spr.issparse(left_X) else np.hstack return hstack([left_X, right_X[:, self.diff_indices_]]) def pad_left(self, left_X, pad_value=0): - if spr.is_sparse(left_X): + if spr.issparse(left_X): joint_X = spr.lil_array( (left_X.shape[0], self.n_vocab), dtype=left_X.dtype ) else: joint_X = np.full((left_X.shape[0], self.n_vocab), pad_value) joint_X[:, : left_X.shape[1]] = left_X - if spr.is_sparse(joint_X): + if spr.issparse(joint_X): joint_X = spr.csr_array(joint_X) return joint_X def pad_right(self, right_X, pad_value=0): - if spr.is_sparse(right_X): + if spr.issparse(right_X): joint_X = spr.lil_array( (right_X.shape[0], self.n_vocab), dtype=right_X.dtype ) @@ -152,13 +152,14 @@ def pad_right(self, right_X, pad_value=0): for joint_idx, right_idx in enumerate(self.joint_to_right_): if right_idx is not None: joint_X[:, joint_idx] = right_X[:, right_idx] - if spr.is_sparse(joint_X): + if spr.issparse(joint_X): joint_X = spr.csr_array(joint_X) return joint_X def get_feature_names_out(self): return np.array(self.joint_terms_) + @property def n_vocab(self): return len(self.joint_terms_) From 7dbc229c6e708e3c042f8efe8bfdf85fb83f2be7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?M=C3=A1rton=20Kardos?= Date: Mon, 23 Nov 2026 16:45:31 +0100 Subject: [PATCH 07/30] update vocabulary avoids padding components when components_ is a property --- turftopic/base.py | 17 +++++++++++------ 1 file changed, 11 insertions(+), 6 deletions(-) diff --git a/turftopic/base.py b/turftopic/base.py index 8ca6efd..1282235 100644 --- a/turftopic/base.py +++ b/turftopic/base.py @@ -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 @@ -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_, From 2c356e0960dc36cbc8cca2194df173f20711d421 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?M=C3=A1rton=20Kardos?= Date: Mon, 23 Nov 2026 16:45:52 +0100 Subject: [PATCH 08/30] Updated sparse diagonal building to new version of scipy --- turftopic/feature_importance.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/turftopic/feature_importance.py b/turftopic/feature_importance.py index 76de68a..8a588f7 100644 --- a/turftopic/feature_importance.py +++ b/turftopic/feature_importance.py @@ -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]), @@ -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]), From f4bd5b2987c8e00a45544638132580df689e7029 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?M=C3=A1rton=20Kardos?= Date: Mon, 23 Nov 2026 16:46:25 +0100 Subject: [PATCH 09/30] Added map() method to TopicNode --- turftopic/hierarchical.py | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/turftopic/hierarchical.py b/turftopic/hierarchical.py index 36ee245..126fc41 100644 --- a/turftopic/hierarchical.py +++ b/turftopic/hierarchical.py @@ -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 @@ -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. From 42bcfb84ed22afbfca79e4db2765c217e695ad73 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?M=C3=A1rton=20Kardos?= Date: Mon, 23 Nov 2026 16:46:45 +0100 Subject: [PATCH 10/30] Added hierarchy merging --- turftopic/merging.py | 109 ++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 102 insertions(+), 7 deletions(-) diff --git a/turftopic/merging.py b/turftopic/merging.py index e2bfbf7..7657d05 100644 --- a/turftopic/merging.py +++ b/turftopic/merging.py @@ -9,6 +9,17 @@ import scipy.sparse as spr from sklearn.metrics.pairwise import cosine_similarity +from turftopic.hierarchical import TopicNode +from turftopic.vectorizers.merging import UnionVectorizer + + +def nanaverage(a, weights=None, axis=0): + if weights is None: + return np.nanmean(a, axis=axis) + scaled_sum = np.nansum(a * weights[:, None], axis=axis) + denominator = weights.sum() + return scaled_sum / denominator + def safe_agg(a, agg, weights, axis=0): try: @@ -17,6 +28,12 @@ def safe_agg(a, agg, weights, axis=0): return agg(a, axis=axis) +def safe_cosine(a, b): + a = np.where(np.isfinite(a), a, np.zeros_like(a)) + b = np.where(np.isfinite(b), b, np.zeros_like(b)) + return cosine_similarity(a, b) + + MergeHistory = list[list[int]] @@ -31,7 +48,7 @@ def merge_from_history( component_matrices: list[np.ndarray], merge_history: MergeHistory, weights=None, - agg=np.average, + agg=nanaverage, ) -> np.ndarray: stacked_components, old_labels = stack_components(component_matrices) flat_merge_hist = list(itertools.chain.from_iterable(merge_history)) @@ -62,8 +79,8 @@ def symmetric_merge( component_matrices: list[np.ndarray], weights=None, match_threshold: float = 0.7, - agg=np.average, - sim_fn=cosine_similarity, + agg=nanaverage, + sim_fn=safe_cosine, allow_within_model_match=False, ) -> tuple[np.ndarray, MergeHistory]: """Performs a symmetric merge on a number of topic models. @@ -132,7 +149,7 @@ def asymmetric_merge( weights=None, match_threshold: float = 0.7, agg=keep_first, - sim_fn=cosine_similarity, + sim_fn=safe_cosine, ) -> tuple[np.ndarray, MergeHistory]: """Performs an asymmetric merge on a number of topic models. @@ -199,13 +216,13 @@ def asymmetric_merge( NAMED_METHODS = { "keep_first": partial( - asymmetric_merge, sim_fn=cosine_similarity, agg=keep_first + asymmetric_merge, sim_fn=safe_cosine, agg=keep_first ), "asymmetric_mean": partial( - asymmetric_merge, sim_fn=cosine_similarity, agg=np.nanmean + asymmetric_merge, sim_fn=safe_cosine, agg=nanaverage ), "symmetric_mean": partial( - symmetric_merge, sim_fn=cosine_similarity, agg=np.nanmean + symmetric_merge, sim_fn=safe_cosine, agg=nanaverage ), } @@ -248,3 +265,81 @@ def __call__(self, component_matrices, weights=None, match_threshold=0.7): weights=decayed_weights, match_threshold=match_threshold, ) + + +def merge_hierarchies( + left: TopicNode, + right: TopicNode, + new_components: np.ndarray, + merge_history: MergeHistory, + joint_vectorizer: UnionVectorizer, + joint_model, +) -> TopicNode: + """Merges all hierarchies from the merged models into one.""" + assert len(merge_history) == 2, "The merge has to be over two models." + left_to_joint, right_to_joint = merge_history + flat_merge_hist = list(itertools.chain.from_iterable(merge_history)) + unique_components = np.unique(flat_merge_hist) + assert unique_components[0] == 0 + + def _change_model(node): + node.model = joint_model + # Since the number of documents is very probably different in the two models, + # we remove the document topic vector from each node + node.document_topic_vector = None + return node + + def _pad_left(node): + if node.word_importance is not None: + padded = np.ravel( + joint_vectorizer.pad_left( + np.atleast_2d(node.word_importance), pad_value=np.nan + ) + ) + node.word_importance = padded + return node + + def _pad_right(node): + if node.word_importance is not None: + padded = np.ravel( + joint_vectorizer.pad_right( + np.atleast_2d(node.word_importance), pad_value=np.nan + ) + ) + node.word_importance = padded + return node + + left = left.map(_change_model).map(_pad_left) + right = right.map(_change_model).map(_pad_right) + if right.children is None: + return left.copy(deep=True) + if left.children is None: + return right.copy(deep=True) + flat_children = [*left.children, *right.children] + flat_to_joint = [*left_to_joint, *right_to_joint] + joint_to_flat = defaultdict(list) + for flat_idx, joint_idx in enumerate(flat_to_joint): + joint_to_flat[joint_idx].append(flat_idx) + joint_children = [] + for (i_topic, old_children), comp in zip( + joint_to_flat.items(), new_components + ): + + def _indent(node): + node.path = (i_topic, *node.path) + return node + + children = None + if len(old_children) > 1: + children = [ + flat_children[i_child].map(_indent) for i_child in old_children + ] + child = TopicNode( + joint_model, + path=(i_topic,), + word_importance=comp, + document_topic_vector=None, + children=children, + ) + joint_children.append(child) + return TopicNode(joint_model, path=(), children=joint_children) From a19e54cb153e1db64ab264f18641adbc9a5732dc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?M=C3=A1rton=20Kardos?= Date: Mon, 23 Nov 2026 16:47:13 +0100 Subject: [PATCH 11/30] Added model merging to clustering models --- turftopic/models/cluster.py | 114 ++++++++++++++++++++++++++++++++++++ 1 file changed, 114 insertions(+) diff --git a/turftopic/models/cluster.py b/turftopic/models/cluster.py index ca828fb..4d63355 100644 --- a/turftopic/models/cluster.py +++ b/turftopic/models/cluster.py @@ -8,6 +8,7 @@ from typing import Any, Callable, Iterable, Literal, Optional, Sequence, Union import numpy as np +import scipy.sparse as spr from rich.console import Console from sentence_transformers import SentenceTransformer from sklearn.base import ClusterMixin, TransformerMixin @@ -31,6 +32,7 @@ soft_ctf_idf, ) from turftopic.late import LateSentenceTransformer, LateWrapper +from turftopic.merging import get_merge_fn, merge_hierarchies from turftopic.models._hierarchical_clusters import ( VALID_LINKAGE_METHODS, ClusterNode, @@ -478,6 +480,7 @@ def fit_predict( doc_topic_matrix = safe_binarize( self.labels_, classes=self.classes_ ) + self.n_documents_ = doc_topic_matrix.shape[0] if self.feature_importance == "c-tf-idf": _, self._idf_diag = ctf_idf( doc_topic_matrix, @@ -737,6 +740,117 @@ def transform( ) return doc_topic_matrix + def merge_with( + self, + other: ClusteringTopicModel, + match_threshold=0.7, + merge_method: str | Callable = "asymmetric_mean", + weighted=True, + ): + """Updates topic model by merging it with another one trained on the new data. + + !!! warning: + Only static properties of a model will be taken into account when merging. + Attributes associated with top exemplars and temporal data will be **DELETED** from the model. + The model will be modified in-place. + We recommend that you save the original model to disk to avoid losing data. + + Parameters + ---------- + other: ClusteringTopicModel + Other clustering topic model to merge this one with. + match_threshold: float, default 0.7 + Cosine similarity threshold, above which topics are to be considered the same. + merge_method: {'symmetric_mean', 'asymmetric_mean', 'keep_first'} or Callable, default 'symmetric_mean' + Method for merging the two topic models. + - `'symmetric_mean'` Treats the two models as equal, and takes the mean of matching topics. + Matches are found by building a graph of topic connections based on the similarity threshold. + Each new topic will be one graph component. + - `'asymmetric_mean'` Merges new topics into the old topics and takes their mean. + - `'keep_first'` Keeps all components untouched in the current model, + and only adds new components from the new model that do not match. + weighted: bool, default True + Indicates whether the merge aggregation should be weighted by the number of documents the + two models have seen. + + Returns + ------- + ndarray of shape (n_documents, n_topics) + Document-topic matrix. + """ + self.update_vocabulary(other) + if weighted: + try: + weights = np.array( + [ + self.n_documents_, + other.n_documents_, + ] + ) + self.n_documents_ = self.n_documents_ + other.n_documents_ + except Exception: + weights = None + else: + weights = None + merge_fn = get_merge_fn(merge_method) + left_components = self.vectorizer.pad_left( + self.components_, pad_value=np.nan + ) + right_components = self.vectorizer.pad_right( + other.components_, pad_value=np.nan + ) + # Filtering out zeros, as the cosine similarity would be zero + left_components = left_components[ + ~np.all( + (left_components == 0) | (~np.isfinite(left_components)), + axis=1, + ) + ] + right_components = right_components[ + ~np.all( + (right_components == 0) | (~np.isfinite(right_components)), + axis=1, + ) + ] + new_components, self.merge_history_ = merge_fn( + [left_components, right_components], + match_threshold=match_threshold, + weights=weights, + ) + if hasattr(self, "top_documents"): + delattr(self, "top_documents") + if hasattr(self, "top_images"): + delattr(self, "top_images") + if hasattr(self, "temporal_components_"): + delattr(self, "temporal_components_") + if hasattr(self, "temporal_importance_"): + delattr(self, "temporal_importance_") + self.hierarchy = merge_hierarchies( + self.hierarchy, + other.hierarchy, + new_components, + self.merge_history_, + self.vectorizer, + self, + ) + if hasattr(self, "_idf_diag") and hasattr(other, "_idf_diag"): + self_idf = np.atleast_2d(self._idf_diag.diagonal()) + other_idf = np.atleast_2d(other._idf_diag.diagonal()) + self_idf = self.vectorizer.pad_left(self_idf) + other_idf = self.vectorizer.pad_right(other_idf) + new_idf, _ = merge_fn( + [self_idf, other_idf], match_threshold=-np.inf, weights=weights + ) + new_idf = np.ravel(new_idf) + n_vocab = len(self.get_vocab()) + self._idf_diag = spr.diags_array( + new_idf, + offsets=0, + shape=(n_vocab, n_vocab), + format="csr", + dtype=self._idf_diag.dtype, + ) + class BERTopic(ClusteringTopicModel): """Convenience function to construct a BERTopic model in Turftopic. From 0d4d86e1a6610e7c326572233277ead7577f5b8d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?M=C3=A1rton=20Kardos?= Date: Mon, 23 Nov 2026 17:41:16 +0100 Subject: [PATCH 12/30] Added fit() to UnionVectorizer --- turftopic/vectorizers/merging.py | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/turftopic/vectorizers/merging.py b/turftopic/vectorizers/merging.py index 0cb4577..c9aee64 100644 --- a/turftopic/vectorizers/merging.py +++ b/turftopic/vectorizers/merging.py @@ -120,6 +120,10 @@ def fit_transform(self, raw_documents, y=None): hstack = spr.hstack if spr.issparse(left_X) else np.hstack return hstack([left_X, right_X[:, self.diff_indices_]]) + def fit(self, raw_documents, y=None): + self.fit_transform(raw_documents) + return self + def transform(self, raw_documents, y=None): left_X = self.left.transform(raw_documents) right_X = self.right.transform(raw_documents) From 431fa45653413110b52acd65d258d969a2e8b63a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?M=C3=A1rton=20Kardos?= Date: Mon, 23 Nov 2026 17:41:34 +0100 Subject: [PATCH 13/30] Added merging based on topic embeddings --- turftopic/merging.py | 61 ++++++++++++++++++++++++++++++++++++++++---- 1 file changed, 56 insertions(+), 5 deletions(-) diff --git a/turftopic/merging.py b/turftopic/merging.py index 7657d05..c7bebef 100644 --- a/turftopic/merging.py +++ b/turftopic/merging.py @@ -82,6 +82,7 @@ def symmetric_merge( agg=nanaverage, sim_fn=safe_cosine, allow_within_model_match=False, + topic_embeddings=None, ) -> tuple[np.ndarray, MergeHistory]: """Performs a symmetric merge on a number of topic models. @@ -99,6 +100,10 @@ def symmetric_merge( Function to produce the similarity matrix. allow_within_model_match: bool, default False Determines whether matches can happen within models. + topic_embeddings: list[np.ndarray] + Topic representations for calculating similarity. + This can be useful when you want to merge components in vocab space, + but want to calculate similarities based on embedding space. Returns ------- @@ -110,9 +115,17 @@ def symmetric_merge( each of the original topics were merged into. e.g. [[0,2,1], [3,2]] would indicate that the topics of the first model were merged into topics 0, 2 and 1 in the joint model, while the second model's topics were merged into 3 and 2. + OPTIONAL: ndarray of shape (n_new_topics, n_dims) + New topic embeddings. """ stacked_components, old_labels = stack_components(component_matrices) - similarity = sim_fn(stacked_components, stacked_components) + if topic_embeddings is None: + similarity = sim_fn(stacked_components, stacked_components) + else: + stacked_embeddings, old_embedding_labels = stack_components( + topic_embeddings + ) + similarity = sim_fn(stacked_components, stacked_components) if not allow_within_model_match: i_processed = 0 for comp in component_matrices: @@ -137,7 +150,12 @@ def symmetric_merge( new_components = merge_from_history( component_matrices, merge_history, weights=weights, agg=agg ) - return new_components, merge_history + if topic_embeddings is None: + return new_components, merge_history + new_embeddings = merge_from_history( + topic_embeddings, merge_history, weights=weights, agg=agg + ) + return new_components, merge_history, new_embeddings def keep_first(a, axis=0): @@ -150,6 +168,7 @@ def asymmetric_merge( match_threshold: float = 0.7, agg=keep_first, sim_fn=safe_cosine, + topic_embeddings=None, ) -> tuple[np.ndarray, MergeHistory]: """Performs an asymmetric merge on a number of topic models. @@ -167,6 +186,10 @@ def asymmetric_merge( Function to produce the similarity matrix. allow_within_model_match: bool, default False Determines whether matches can happen within models. + topic_embeddings: list[np.ndarray] + Topic representations for calculating similarity. + This can be useful when you want to merge components in vocab space, + but want to calculate similarities based on embedding space. Returns ------- @@ -178,15 +201,23 @@ def asymmetric_merge( each of the original topics were merged into. e.g. [[0,2,1], [3,2]] would indicate that the topics of the first model were merged into topics 0, 2 and 1 in the joint model, while the second model's topics were merged into 3 and 2. + OPTIONAL: ndarray of shape (n_new_topics, n_dims) + New topic embeddings. """ merge_history = [] components = np.copy(component_matrices[0]) + if topic_embeddings is not None: + embeddings = np.copy(topic_embeddings[0]) # First components will just be kept merge_history.append(list(range(components.shape[0]))) - for incoming_components in component_matrices[1:]: + for i_model, incoming_components in enumerate(component_matrices[1:]): n_current = components.shape[0] _merge_inst = [] - similarity = sim_fn(components, incoming_components) + if topic_embeddings is None: + similarity = sim_fn(components, incoming_components) + else: + incoming_embeddings = topic_embeddings[i_model] + similarity = sim_fn(embeddings, incoming_embeddings) maxsim_ind = np.argmax(similarity.T, axis=1) to_add = [] for i_new_comp, ind_most_similar_old in enumerate(maxsim_ind): @@ -204,14 +235,34 @@ def asymmetric_merge( axis=0, ) _merge_inst.append(ind_most_similar_old) + if topic_embeddings is not None: + embeddings[ind_most_similar_old] = safe_agg( + np.concatenate( + [ + embeddings[[ind_most_similar_old], :], + incoming_embeddings[[i_new_comp], :], + ], + axis=0, + ), + agg=agg, + weights=weights, + axis=0, + ) else: _merge_inst.append(n_current + len(to_add)) to_add.append(i_new_comp) components = np.concatenate( [components, incoming_components[to_add]], axis=0 ) + if topic_embeddings is not None: + embeddings = np.concatenate( + [embeddings, incoming_embeddings[to_add]], axis=0 + ) merge_history.append(_merge_inst) - return components, merge_history + if topic_embeddings is None: + return components, merge_history + else: + return components, merge_history, embeddings NAMED_METHODS = { From d3500e28a123cf992f24cf50d6e345356c2b5768 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?M=C3=A1rton=20Kardos?= Date: Mon, 23 Nov 2026 17:41:55 +0100 Subject: [PATCH 14/30] Added topic embedding-based merging to clustering models --- turftopic/models/cluster.py | 23 +++++++++-------------- 1 file changed, 9 insertions(+), 14 deletions(-) diff --git a/turftopic/models/cluster.py b/turftopic/models/cluster.py index 4d63355..825fd0b 100644 --- a/turftopic/models/cluster.py +++ b/turftopic/models/cluster.py @@ -508,6 +508,7 @@ def fit_predict( f"Topic reduction done from {n_topics} to {self.n_reduce_to}." ) console.log("Model fitting done.") + self.topic_vectors_ = self._calculate_topic_vectors() self.top_documents = self.get_top_documents( raw_documents=raw_documents, document_topic_matrix=self.transform( @@ -799,24 +800,18 @@ def merge_with( right_components = self.vectorizer.pad_right( other.components_, pad_value=np.nan ) - # Filtering out zeros, as the cosine similarity would be zero - left_components = left_components[ - ~np.all( - (left_components == 0) | (~np.isfinite(left_components)), - axis=1, - ) - ] - right_components = right_components[ - ~np.all( - (right_components == 0) | (~np.isfinite(right_components)), - axis=1, - ) - ] - new_components, self.merge_history_ = merge_fn( + new_components, self.merge_history_, new_topic_embeddings = merge_fn( [left_components, right_components], match_threshold=match_threshold, weights=weights, + topic_embeddings=[self.topic_vectors_, other.topic_vectors_], ) + self.topic_vectors_ = new_topic_embeddings + if self.feature_importance == "centroid": + new_components = cluster_centroid_distance( + self.topic_vectors_, + self.vocab_embeddings, + ) if hasattr(self, "top_documents"): delattr(self, "top_documents") if hasattr(self, "top_images"): From 4d8c8187416e7ed47a4ef93d8311be082390af38 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?M=C3=A1rton=20Kardos?= Date: Tue, 24 Nov 2026 09:47:30 +0100 Subject: [PATCH 15/30] Added supervised fitting to clustering topic model --- turftopic/models/cluster.py | 47 +++++++++++++++++++++++++++++++++++++ 1 file changed, 47 insertions(+) diff --git a/turftopic/models/cluster.py b/turftopic/models/cluster.py index 825fd0b..3d9b903 100644 --- a/turftopic/models/cluster.py +++ b/turftopic/models/cluster.py @@ -431,6 +431,53 @@ def join_topics( """ self.hierarchy.join_topics(to_join, joint_id=joint_id) + def fit_supervised( + self, + raw_documents, + y: np.ndarray, + embeddings: Optional[np.ndarray] = None, + ): + console = Console() + with console.status("Fitting model") as status: + if embeddings is None: + status.update("Encoding documents") + embeddings = self.encode_documents(raw_documents) + console.log("Encoding done.") + self.embeddings = embeddings + status.update("Extracting terms") + self.doc_term_matrix = self.vectorizer.fit_transform(raw_documents) + console.log("Term extraction done.") + status.update("Estimating parameters.") + labels = np.argmax(y, axis=1) + # Initializing hierarchy + self.hierarchy = ClusterNode.create_root(self, labels=labels) + doc_topic_matrix = safe_binarize( + self.labels_, classes=self.classes_ + ) + self.n_documents_ = doc_topic_matrix.shape[0] + if self.feature_importance == "c-tf-idf": + _, self._idf_diag = ctf_idf( + doc_topic_matrix, + self.doc_term_matrix, + return_idf=True, + ) + if self.feature_importance == "soft-c-tf-idf": + _, self._idf_diag = soft_ctf_idf( + doc_topic_matrix, + self.doc_term_matrix, + return_idf=True, + ) + console.log("Parameter estimation done.") + console.log("Model fitting done.") + self.topic_vectors_ = self._calculate_topic_vectors() + self.top_documents = self.get_top_documents( + raw_documents=raw_documents, + document_topic_matrix=self.transform( + raw_documents, embeddings=self.embeddings + ), + ) + return self + def fit_predict( self, raw_documents, y=None, embeddings: Optional[np.ndarray] = None ) -> np.ndarray: From 13aa039c2ddd366f51a6170b623c08ceda367319 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?M=C3=A1rton=20Kardos?= Date: Tue, 24 Nov 2026 10:15:12 +0100 Subject: [PATCH 16/30] Added merge_models to clustering topic models --- turftopic/models/cluster.py | 23 ++++++++++++++++++++++- 1 file changed, 22 insertions(+), 1 deletion(-) diff --git a/turftopic/models/cluster.py b/turftopic/models/cluster.py index 3d9b903..121fef8 100644 --- a/turftopic/models/cluster.py +++ b/turftopic/models/cluster.py @@ -3,6 +3,7 @@ import typing import warnings import webbrowser +from copy import deepcopy from datetime import datetime from pathlib import Path from typing import Any, Callable, Iterable, Literal, Optional, Sequence, Union @@ -11,7 +12,7 @@ import scipy.sparse as spr from rich.console import Console from sentence_transformers import SentenceTransformer -from sklearn.base import ClusterMixin, TransformerMixin +from sklearn.base import ClusterMixin, TransformerMixin, clone from sklearn.cluster import HDBSCAN from sklearn.exceptions import NotFittedError from sklearn.feature_extraction.text import CountVectorizer @@ -893,6 +894,26 @@ def merge_with( dtype=self._idf_diag.dtype, ) + @classmethod + def merge_models( + cls, + models: list[ClusteringTopicModel], + match_threshold=0.7, + merge_method: str | Callable = "asymmetric_mean", + weighted=True, + ): + if len(models) == 0: + raise ValueError("List is empty, cannot merge zero topic models.") + model = deepcopy(models[0]) + for new_model in models[1:]: + model.merge_with( + new_model, + match_threshold=match_threshold, + merge_method=merge_method, + weighted=weighted, + ) + return model + class BERTopic(ClusteringTopicModel): """Convenience function to construct a BERTopic model in Turftopic. From 10f7cb9278650e3b876ba6a62c41a4bafb425f88 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?M=C3=A1rton=20Kardos?= Date: Tue, 24 Nov 2026 10:22:26 +0100 Subject: [PATCH 17/30] merge_with now returns self --- turftopic/models/cluster.py | 1 + 1 file changed, 1 insertion(+) diff --git a/turftopic/models/cluster.py b/turftopic/models/cluster.py index 121fef8..5834873 100644 --- a/turftopic/models/cluster.py +++ b/turftopic/models/cluster.py @@ -893,6 +893,7 @@ def merge_with( format="csr", dtype=self._idf_diag.dtype, ) + return self @classmethod def merge_models( From 672f6e8e8302f1cc33b1cd8c8ac1e38999142950 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?M=C3=A1rton=20Kardos?= Date: Tue, 24 Nov 2026 10:23:16 +0100 Subject: [PATCH 18/30] Corrected return value in merge_with docstring --- turftopic/models/cluster.py | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/turftopic/models/cluster.py b/turftopic/models/cluster.py index 5834873..dff233a 100644 --- a/turftopic/models/cluster.py +++ b/turftopic/models/cluster.py @@ -824,8 +824,7 @@ def merge_with( Returns ------- - ndarray of shape (n_documents, n_topics) - Document-topic matrix. + Self """ self.update_vocabulary(other) if weighted: From bbee6e934047dd8eb87a70ed7825b6955a6d7cd9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?M=C3=A1rton=20Kardos?= Date: Tue, 24 Nov 2026 10:24:58 +0100 Subject: [PATCH 19/30] Added 'merge_models' and 'merge_with' to senstopic --- turftopic/models/senstopic.py | 96 +++++++++++++++++++++++++++++++++++ 1 file changed, 96 insertions(+) diff --git a/turftopic/models/senstopic.py b/turftopic/models/senstopic.py index 7ca01e1..bbc073d 100644 --- a/turftopic/models/senstopic.py +++ b/turftopic/models/senstopic.py @@ -1,4 +1,5 @@ import warnings +from copy import deepcopy from datetime import datetime, timedelta from functools import partial from typing import Callable, Literal, Optional, Union @@ -17,6 +18,7 @@ from turftopic.dynamic import DynamicTopicModel from turftopic.encoders.multimodal import MultimodalEncoder from turftopic.hierarchical import TopicNode +from turftopic.merging import merge_hierarchies from turftopic.models._snmf import SNMF from turftopic.multimodal import ( ImageRepr, @@ -576,6 +578,100 @@ def partial_fit( ) return self + def merge_with( + self, + other: SensTopic, + match_threshold=0.7, + merge_method: str | Callable = "asymmetric_mean", + weighted=True, + ): + """Updates topic model by merging it with another one trained on the new data. + + !!! warning: + Only static properties of a model will be taken into account when merging. + Attributes associated with top exemplars and temporal data will be **DELETED** from the model. + The model will be modified in-place. + We recommend that you save the original model to disk to avoid losing data. + + Parameters + ---------- + other: SensTopic + Other topic model to merge this one with. + match_threshold: float, default 0.7 + Cosine similarity threshold, above which topics are to be considered the same. + merge_method: {'symmetric_mean', 'asymmetric_mean', 'keep_first'} or Callable, default 'symmetric_mean' + Method for merging the two topic models. + - `'symmetric_mean'` Treats the two models as equal, and takes the mean of matching topics. + Matches are found by building a graph of topic connections based on the similarity threshold. + Each new topic will be one graph component. + - `'asymmetric_mean'` Merges new topics into the old topics and takes their mean. + - `'keep_first'` Keeps all components untouched in the current model, + and only adds new components from the new model that do not match. + weighted: bool, default True + Indicates whether the merge aggregation should be weighted by the number of documents the + two models have seen. + + Returns + ------- + Self + """ + self.update_vocabulary(other) + self.decomposition, self.merge_history_ = ( + self.decomposition.merge_with( + other.decomposition, + match_threshold=match_threshold, + merge_method=merge_method, + weighted=weighted, + ) + ) + vocab_topic = self.decomposition.transform(self.vocab_embeddings) + self.axial_components_ = vocab_topic.T + if self.feature_importance == "axial": + self.components_ = self.axial_components_ + elif self.feature_importance == "angular": + self.components_ = self.angular_components_ + elif self.feature_importance == "combined": + self.components_ = ( + np.square(self.axial_components_) * self.angular_components_ + ) + if hasattr(self, "top_documents"): + delattr(self, "top_documents") + if hasattr(self, "top_images"): + delattr(self, "top_images") + if hasattr(self, "temporal_components_"): + delattr(self, "temporal_components_") + if hasattr(self, "temporal_importance_"): + delattr(self, "temporal_importance_") + self.hierarchy = merge_hierarchies( + self.hierarchy, + other.hierarchy, + self.components_, + self.merge_history_, + self.vectorizer, + self, + ) + return self + + @classmethod + def merge_models( + cls, + models: list[SensTopic], + match_threshold=0.7, + merge_method: str | Callable = "asymmetric_mean", + weighted=True, + ): + if len(models) == 0: + raise ValueError("List is empty, cannot merge zero topic models.") + model = deepcopy(models[0]) + for new_model in models[1:]: + model.merge_with( + new_model, + match_threshold=match_threshold, + merge_method=merge_method, + weighted=weighted, + ) + return model + def transform(self, raw_documents, embeddings=None): if embeddings is None: embeddings = self.encode_documents(raw_documents) From 8b353019ce27e7721c572faeb4c0f0f9ef2ffd25 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?M=C3=A1rton=20Kardos?= Date: Tue, 24 Nov 2026 10:27:20 +0100 Subject: [PATCH 20/30] Added docstring to merge_models --- turftopic/models/cluster.py | 26 ++++++++++++++++++++++++++ turftopic/models/senstopic.py | 26 ++++++++++++++++++++++++++ 2 files changed, 52 insertions(+) diff --git a/turftopic/models/cluster.py b/turftopic/models/cluster.py index dff233a..1432b5b 100644 --- a/turftopic/models/cluster.py +++ b/turftopic/models/cluster.py @@ -902,6 +902,32 @@ def merge_models( merge_method: str | Callable = "asymmetric_mean", weighted=True, ): + """Merges multiple ClusteringTopicModel models together. + The original models will not be modified. + + Parameters + ---------- + models: list[ClusteringTopicModel] + ClusteringTopicModel models to merge together. + match_threshold: float, default 0.7 + Cosine similarity threshold, above which topics are to be considered the same. + merge_method: {'symmetric_mean', 'asymmetric_mean', 'keep_first'} or Callable, default 'symmetric_mean' + Method for merging the two topic models. + - `'symmetric_mean'` Treats the two models as equal, and takes the mean of matching topics. + Matches are found by building a graph of topic connections based on the similarity threshold. + Each new topic will be one graph component. + - `'asymmetric_mean'` Merges new topics into the old topics and takes their mean. + - `'keep_first'` Keeps all components untouched in the current model, + and only adds new components from the new model that do not match. + weighted: bool, default True + Indicates whether the merge aggregation should be weighted by the number of documents the + two models have seen. + + Returns + ------- + ClusteringTopicModel + Merged model. + """ if len(models) == 0: raise ValueError("List is empty, cannot merge zero topic models.") model = deepcopy(models[0]) diff --git a/turftopic/models/senstopic.py b/turftopic/models/senstopic.py index bbc073d..72aa5b0 100644 --- a/turftopic/models/senstopic.py +++ b/turftopic/models/senstopic.py @@ -660,6 +660,32 @@ def merge_models( merge_method: str | Callable = "asymmetric_mean", weighted=True, ): + """Merges multiple SensTopic models together. + The original models will not be modified. + + Parameters + ---------- + models: list[SensTopic] + SensTopic models to merge together. + match_threshold: float, default 0.7 + Cosine similarity threshold, above which topics are to be considered the same. + merge_method: {'symmetric_mean', 'asymmetric_mean', 'keep_first'} or Callable, default 'symmetric_mean' + Method for merging the two topic models. + - `'symmetric_mean'` Treats the two models as equal, and takes the mean of matching topics. + Matches are found by building a graph of topic connections based on the similarity threshold. + Each new topic will be one graph component. + - `'asymmetric_mean'` Merges new topics into the old topics and takes their mean. + - `'keep_first'` Keeps all components untouched in the current model, + and only adds new components from the new model that do not match. + weighted: bool, default True + Indicates whether the merge aggregation should be weighted by the number of documents the + two models have seen. + + Returns + ------- + SensTopic + Merged model. + """ if len(models) == 0: raise ValueError("List is empty, cannot merge zero topic models.") model = deepcopy(models[0]) From 985916d5750e9dc07643182d9252f76fdbef3830 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?M=C3=A1rton=20Kardos?= Date: Tue, 24 Nov 2026 11:35:13 +0100 Subject: [PATCH 21/30] Added model merging to Topeax --- turftopic/models/gmm.py | 2 + turftopic/models/topeax.py | 133 +++++++++++++++++++++++++++++++++++-- 2 files changed, 130 insertions(+), 5 deletions(-) diff --git a/turftopic/models/gmm.py b/turftopic/models/gmm.py index 04d5210..74a872a 100644 --- a/turftopic/models/gmm.py +++ b/turftopic/models/gmm.py @@ -240,6 +240,7 @@ def fit_transform( self.top_documents = self.get_top_documents( raw_documents, document_topic_matrix=self.doc_topic_matrix ) + self.n_documents_ = self.embeddings.shape[0] return self.doc_topic_matrix def fit_transform_multimodal( @@ -297,6 +298,7 @@ def fit_transform_multimodal( self.top_documents = self.get_top_documents( raw_documents, document_topic_matrix=self.doc_topic_matrix ) + self.n_documents_ = self.embeddings.shape[0] console.log("Transformation done.") return self.doc_topic_matrix diff --git a/turftopic/models/topeax.py b/turftopic/models/topeax.py index e3c7cc0..a9883cc 100644 --- a/turftopic/models/topeax.py +++ b/turftopic/models/topeax.py @@ -1,4 +1,5 @@ -from typing import Optional, Union +from copy import deepcopy +from typing import Callable, Optional, Union import numpy as np from scipy.ndimage import ( @@ -19,6 +20,7 @@ from turftopic.base import Encoder from turftopic.encoders.multimodal import MultimodalEncoder +from turftopic.merging import get_merge_fn from turftopic.models.gmm import GMM, LexicalWordImportance @@ -200,14 +202,14 @@ def estimate_components( self.vocab_embeddings.shape[0] != vocab.shape[0] ): self.vocab_embeddings = self.encode_documents(vocab) - topic_embeddings = [] + topic_vectors = [] for weight in doc_topic_matrix.T: - topic_embeddings.append( + topic_vectors.append( np.average(self.embeddings, axis=0, weights=weight) ) - self.topic_embeddings = np.stack(topic_embeddings) + self.topic_vectors_ = np.stack(topic_vectors) semantic_components = cosine_similarity( - self.topic_embeddings, self.vocab_embeddings + self.topic_vectors_, self.vocab_embeddings ) # Transforming to positive values from 0 to 1 # Then taking geometric average of the two values @@ -216,6 +218,127 @@ def estimate_components( ) return self.components_ + def merge_with( + self, + other: Topeax, + match_threshold=0.7, + merge_method: str | Callable = "asymmetric_mean", + weighted=True, + ): + """Updates topic model by merging it with another one trained on the new data. + + !!! warning: + Only static properties of a model will be taken into account when merging. + Attributes associated with top exemplars and temporal data will be **DELETED** from the model. + The model will be modified in-place. + We recommend that you save the original model to disk to avoid losing data. + + Parameters + ---------- + other: Topeax + Other Topeax model to merge this one with. + match_threshold: float, default 0.7 + Cosine similarity threshold, above which topics are to be considered the same. + merge_method: {'symmetric_mean', 'asymmetric_mean', 'keep_first'} or Callable, default 'symmetric_mean' + Method for merging the two topic models. + - `'symmetric_mean'` Treats the two models as equal, and takes the mean of matching topics. + Matches are found by building a graph of topic connections based on the similarity threshold. + Each new topic will be one graph component. + - `'asymmetric_mean'` Merges new topics into the old topics and takes their mean. + - `'keep_first'` Keeps all components untouched in the current model, + and only adds new components from the new model that do not match. + weighted: bool, default True + Indicates whether the merge aggregation should be weighted by the number of documents the + two models have seen. + + Returns + ------- + Self + """ + self.update_vocabulary(other) + if weighted: + try: + weights = np.array( + [ + self.n_documents_, + other.n_documents_, + ] + ) + self.n_documents_ = self.n_documents_ + other.n_documents_ + except Exception: + weights = None + else: + weights = None + merge_fn = get_merge_fn(merge_method) + left_components = self.vectorizer.pad_left( + self.components_, pad_value=np.nan + ) + right_components = self.vectorizer.pad_right( + other.components_, pad_value=np.nan + ) + new_components, self.merge_history_, new_topic_embeddings = merge_fn( + [left_components, right_components], + match_threshold=match_threshold, + weights=weights, + topic_embeddings=[self.topic_vectors_, other.topic_vectors_], + ) + self.topic_vectors_ = new_topic_embeddings + if hasattr(self, "top_documents"): + delattr(self, "top_documents") + if hasattr(self, "top_images"): + delattr(self, "top_images") + if hasattr(self, "temporal_components_"): + delattr(self, "temporal_components_") + if hasattr(self, "temporal_importance_"): + delattr(self, "temporal_importance_") + return self + + @classmethod + def merge_models( + cls, + models: list[Topeax], + match_threshold=0.7, + merge_method: str | Callable = "asymmetric_mean", + weighted=True, + ): + """Merges multiple ClusteringTopicModel models together. + The original models will not be modified. + + Parameters + ---------- + models: list[ClusteringTopicModel] + ClusteringTopicModel models to merge together. + match_threshold: float, default 0.7 + Cosine similarity threshold, above which topics are to be considered the same. + merge_method: {'symmetric_mean', 'asymmetric_mean', 'keep_first'} or Callable, default 'symmetric_mean' + Method for merging the two topic models. + - `'symmetric_mean'` Treats the two models as equal, and takes the mean of matching topics. + Matches are found by building a graph of topic connections based on the similarity threshold. + Each new topic will be one graph component. + - `'asymmetric_mean'` Merges new topics into the old topics and takes their mean. + - `'keep_first'` Keeps all components untouched in the current model, + and only adds new components from the new model that do not match. + weighted: bool, default True + Indicates whether the merge aggregation should be weighted by the number of documents the + two models have seen. + + Returns + ------- + ClusteringTopicModel + Merged model. + """ + if len(models) == 0: + raise ValueError("List is empty, cannot merge zero topic models.") + model = deepcopy(models[0]) + for new_model in models[1:]: + model.merge_with( + new_model, + match_threshold=match_threshold, + merge_method=merge_method, + weighted=weighted, + ) + return model + def _init_model(self, n_components: int): mixture = Peax() return mixture From ae545c908afab57c710c95664f7baacf8c2fc238 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?M=C3=A1rton=20Kardos?= Date: Tue, 24 Nov 2026 11:35:33 +0100 Subject: [PATCH 22/30] Added supervised modelling to S3 --- turftopic/models/decomp.py | 63 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 63 insertions(+) diff --git a/turftopic/models/decomp.py b/turftopic/models/decomp.py index 00d150a..997bfc3 100644 --- a/turftopic/models/decomp.py +++ b/turftopic/models/decomp.py @@ -30,6 +30,16 @@ ) +class DecompLinearRegression(LinearRegression): + """Linear regression, but has a transform method.""" + + def transform(self, X): + return self.predict(X) + + def fit_transform(self, X, y): + return self.fit(X, y).transform(X) + + class SemanticSignalSeparation( ContextualModel, DynamicTopicModel, MultimodalModel ): @@ -189,6 +199,59 @@ def fit_transform( console.log("Model fitting done.") return doc_topic + def fit_supervised( + self, + raw_documents, + y: np.ndarray, + embeddings: Optional[np.ndarray] = None, + ): + console = Console() + self.embeddings = embeddings + self.n_components = y.shape[1] + with console.status("Fitting model") as status: + if self.embeddings is None: + status.update("Encoding documents") + self.embeddings = self.encode_documents(raw_documents) + console.log("Documents encoded.") + status.update("Solving OLS") + self.decomposition = DecompLinearRegression(fit_intercept=False) + doc_topic = self.decomposition.fit_transform(self.embeddings, y=y) + console.log("OLS done.") + status.update("Extracting terms.") + vocab = self.vectorizer.fit(raw_documents).get_feature_names_out() + console.log("Term extraction done.") + status.update("Encoding vocabulary") + self.vocab_embeddings = self.encode_documents(vocab) + if self.vocab_embeddings.shape[1] != self.embeddings.shape[1]: + raise ValueError( + NOT_MATCHING_ERROR.format( + n_dims=self.embeddings.shape[1], + n_word_dims=self.vocab_embeddings.shape[1], + ) + ) + console.log("Vocabulary encoded.") + status.update("Estimating term importances") + vocab_topic = self.decomposition.transform(self.vocab_embeddings) + self.axial_components_ = vocab_topic.T + if self.feature_importance == "axial": + self.components_ = self.axial_components_ + elif self.feature_importance == "angular": + self.components_ = self.angular_components_ + elif self.feature_importance == "combined": + self.components_ = ( + np.square(self.axial_components_) + * self.angular_components_ + ) + self.top_documents = self.get_top_documents( + raw_documents, document_topic_matrix=doc_topic + ) + self.negative_documents = self.get_top_documents( + raw_documents, document_topic_matrix=doc_topic, positive=False + ) + self.document_topic_matrix = doc_topic + console.log("Model fitting done.") + return self + def fit_transform_multimodal( self, raw_documents: list[str], From 23e8c04d28d4ca6ef4efafa6b4f863e40f8cd768 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?M=C3=A1rton=20Kardos?= Date: Tue, 24 Nov 2026 12:08:19 +0100 Subject: [PATCH 23/30] Implemented model merging for S3 --- turftopic/models/decomp.py | 164 ++++++++++++++++++++++++++++++++++++- 1 file changed, 162 insertions(+), 2 deletions(-) diff --git a/turftopic/models/decomp.py b/turftopic/models/decomp.py index 997bfc3..9d5a58f 100644 --- a/turftopic/models/decomp.py +++ b/turftopic/models/decomp.py @@ -1,11 +1,12 @@ import warnings +from copy import deepcopy from datetime import datetime -from typing import Literal, Optional, Union +from typing import Callable, Literal, Optional, Union import numpy as np from rich.console import Console from sentence_transformers import SentenceTransformer -from sklearn.base import TransformerMixin +from sklearn.base import TransformerMixin, clone from sklearn.decomposition import FastICA from sklearn.exceptions import NotFittedError from sklearn.feature_extraction.text import CountVectorizer @@ -16,6 +17,7 @@ from turftopic.base import ContextualModel, Encoder from turftopic.dynamic import DynamicTopicModel from turftopic.encoders.multimodal import MultimodalEncoder +from turftopic.merging import get_merge_fn from turftopic.multimodal import ( ImageRepr, MultimodalEmbeddings, @@ -40,6 +42,48 @@ def fit_transform(self, X, y): return self.fit(X, y).transform(X) +def merge_fastica( + left: FastICA, right: FastICA, merge_method, match_threshold, weights +): + if not (isinstance(left, FastICA) and isinstance(right, FastICA)): + raise TypeError("Can only merge S3 models that use FastICA.") + if left.whiten != right.whiten: + raise ValueError( + "Cannot merge FastICA instances because one of them uses whitening while the other doesn't." + ) + use_whitening = left.whiten and right.whiten + new_decomp = clone(left) + merge_fn = get_merge_fn(merge_method) + if use_whitening: + whitening_means = np.stack([left.mean_, right.mean_]) + if weights is not None: + new_mean = np.average(whitening_means, weights=weights, axis=0) + else: + new_mean = np.mean(whitening_means, axis=0) + new_whitening, merge_history, new_components = merge_fn( + [left.whitening_, right.whitening_], + match_threshold=match_threshold, + weights=weights, + topic_embeddings=[left.components_, right.components_], + ) + new_decomp.components_ = new_components + new_decomp.n_components = new_components.shape[0] + new_decomp.mean_ = new_mean + new_decomp.whitening_ = new_whitening + else: + new_whitening, merge_history = merge_fn( + [left.components_, right.components_], + match_threshold=match_threshold, + weights=weights, + ) + new_decomp.components_ = new_components + new_decomp.n_components = new_components.shape[0] + new_decomp.mixing_ = np.linalg.pinv(new_decomp.components_) + new_decomp.n_iter_ = left.n_iter_ + right.n_iter_ + new_decomp.n_features_in_ = left.n_features_in_ + return new_decomp, merge_history + + class SemanticSignalSeparation( ContextualModel, DynamicTopicModel, MultimodalModel ): @@ -196,6 +240,7 @@ def fit_transform( raw_documents, document_topic_matrix=doc_topic, positive=False ) self.document_topic_matrix = doc_topic + self.n_documents_ = doc_topic.shape[0] console.log("Model fitting done.") return doc_topic @@ -321,6 +366,7 @@ def fit_transform_multimodal( raw_documents, document_topic_matrix=doc_topic, positive=False ) console.log("Images transformed") + self.n_documents_ = doc_topic.shape[0] return doc_topic def plot_topics_with_images(self, n_columns: int = 3, grid_size: int = 4): @@ -707,6 +753,120 @@ def transform( embeddings = self.encode_documents(raw_documents) return self.decomposition.transform(embeddings) + def merge_with( + self, + other: SemanticSignalSeparation, + match_threshold=0.7, + merge_method: str | Callable = "asymmetric_mean", + weighted=True, + ): + """Updates topic model by merging it with another one trained on the new data. + + !!! warning: + Only static properties of a model will be taken into account when merging. + Attributes associated with top exemplars and temporal data will be **DELETED** from the model. + The model will be modified in-place. + We recommend that you save the original model to disk to avoid losing data. + + Parameters + ---------- + other: SemanticSignalSeparation + Other SemanticSignalSeparation model to merge this one with. + match_threshold: float, default 0.7 + Cosine similarity threshold, above which topics are to be considered the same. + merge_method: {'symmetric_mean', 'asymmetric_mean', 'keep_first'} or Callable, default 'symmetric_mean' + Method for merging the two topic models. + - `'symmetric_mean'` Treats the two models as equal, and takes the mean of matching topics. + Matches are found by building a graph of topic connections based on the similarity threshold. + Each new topic will be one graph component. + - `'asymmetric_mean'` Merges new topics into the old topics and takes their mean. + - `'keep_first'` Keeps all components untouched in the current model, + and only adds new components from the new model that do not match. + weighted: bool, default True + Indicates whether the merge aggregation should be weighted by the number of documents the + two models have seen. + + Returns + ------- + Self + """ + self.update_vocabulary(other) + if weighted: + try: + weights = np.array( + [ + self.n_documents_, + other.n_documents_, + ] + ) + self.n_documents_ = self.n_documents_ + other.n_documents_ + except Exception: + weights = None + else: + weights = None + self.decomposition, self.merge_history_ = merge_fastica( + self.decomposition, + other.decomposition, + merge_method, + match_threshold, + weights, + ) + if hasattr(self, "top_documents"): + delattr(self, "top_documents") + if hasattr(self, "top_images"): + delattr(self, "top_images") + if hasattr(self, "temporal_components_"): + delattr(self, "temporal_components_") + if hasattr(self, "temporal_importance_"): + delattr(self, "temporal_importance_") + return self + + @classmethod + def merge_models( + cls, + models: list[SemanticSignalSeparation], + match_threshold=0.7, + merge_method: str | Callable = "asymmetric_mean", + weighted=True, + ): + """Merges multiple SemanticSignalSeparation models together. + The original models will not be modified. + + Parameters + ---------- + models: list[SemanticSignalSeparation] + SemanticSignalSeparation models to merge together. + match_threshold: float, default 0.7 + Cosine similarity threshold, above which topics are to be considered the same. + merge_method: {'symmetric_mean', 'asymmetric_mean', 'keep_first'} or Callable, default 'symmetric_mean' + Method for merging the two topic models. + - `'symmetric_mean'` Treats the two models as equal, and takes the mean of matching topics. + Matches are found by building a graph of topic connections based on the similarity threshold. + Each new topic will be one graph component. + - `'asymmetric_mean'` Merges new topics into the old topics and takes their mean. + - `'keep_first'` Keeps all components untouched in the current model, + and only adds new components from the new model that do not match. + weighted: bool, default True + Indicates whether the merge aggregation should be weighted by the number of documents the + two models have seen. + + Returns + ------- + SemanticSignalSeparation + Merged model. + """ + if len(models) == 0: + raise ValueError("List is empty, cannot merge zero topic models.") + model = deepcopy(models[0]) + for new_model in models[1:]: + model.merge_with( + new_model, + match_threshold=match_threshold, + merge_method=merge_method, + weighted=weighted, + ) + return model + def print_topics( self, top_k: int = 10, From b6a9c0e80dd6dc2abfd3359600331a094c439ae8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?M=C3=A1rton=20Kardos?= Date: Tue, 24 Nov 2026 15:39:44 +0100 Subject: [PATCH 24/30] Added tests for merging --- tests/test_integration.py | 20 +++++++++++++++++++- 1 file changed, 19 insertions(+), 1 deletion(-) diff --git a/tests/test_integration.py b/tests/test_integration.py index 4020f09..3b322b3 100644 --- a/tests/test_integration.py +++ b/tests/test_integration.py @@ -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), @@ -152,6 +152,24 @@ def test_fit_online(model): df = pd.read_csv(out_path) +supports_merging = [SensTopic, Topeax, ClusteringTopicModel] + + +@pytest.mark.parametrize("model", supports_merging) +def test_merging(model_cls): + model_kwargs = dict(encoder=trf) + models = [] + for batch in batched(zip(texts, embeddings), 50): + 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", From ef7a0785447de337a1cb0b9bf1d735a6921c2b80 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?M=C3=A1rton=20Kardos?= Date: Tue, 24 Nov 2026 15:55:17 +0100 Subject: [PATCH 25/30] added some docs on model_merging --- docs/topic_merging.md | 111 ++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 108 insertions(+), 3 deletions(-) diff --git a/docs/topic_merging.md b/docs/topic_merging.md index fe3f720..dddb87e 100644 --- a/docs/topic_merging.md +++ b/docs/topic_merging.md @@ -1,11 +1,116 @@ # 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.7) + 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 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** From 86ec6c119be929c397383e704df12cbcd3d82adf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?M=C3=A1rton=20Kardos?= Date: Tue, 24 Nov 2026 16:11:09 +0100 Subject: [PATCH 26/30] Added more docs --- docs/supervised.md | 90 +++++++++++++++++++++++++++++++++++++++++++ docs/topic_merging.md | 10 ++++- mkdocs.yml | 1 + 3 files changed, 100 insertions(+), 1 deletion(-) create mode 100644 docs/supervised.md diff --git a/docs/supervised.md b/docs/supervised.md new file mode 100644 index 0000000..a3a076a --- /dev/null +++ b/docs/supervised.md @@ -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 | diff --git a/docs/topic_merging.md b/docs/topic_merging.md index dddb87e..46d1ccf 100644 --- a/docs/topic_merging.md +++ b/docs/topic_merging.md @@ -29,7 +29,7 @@ Currently a limited number of models are supported but we are working on extendi embeddings=embeddings[batch_start:batch_end], ) models.append(batch_model) - model = SensTopic.merge_models(models, merge_method="symmetric_mean", match_threshold=0.7) + model = SensTopic.merge_models(models, merge_method="symmetric_mean", match_threshold=0.8) model.print_topics() ``` @@ -110,6 +110,14 @@ Currently a limited number of models are supported but we are working on extendi 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: diff --git a/mkdocs.yml b/mkdocs.yml index 3026a1d..6f424ce 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -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: From 58626a049a1fdbd847feb20ee02e80cf95355e8b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?M=C3=A1rton=20Kardos?= Date: Tue, 24 Nov 2026 16:11:26 +0100 Subject: [PATCH 27/30] Version bump --- pyproject.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pyproject.toml b/pyproject.toml index 48f3d57..f1f54e3 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -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 ", email = "martonkardos@cas.au.dk" } From e7df9e9c24abbd965fecd6c07fca3915a71a30b4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?M=C3=A1rton=20Kardos?= Date: Tue, 24 Nov 2026 16:14:25 +0100 Subject: [PATCH 28/30] Fixed parametrize in test --- tests/test_integration.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/test_integration.py b/tests/test_integration.py index 3b322b3..d2c010c 100644 --- a/tests/test_integration.py +++ b/tests/test_integration.py @@ -155,7 +155,7 @@ def test_fit_online(model): supports_merging = [SensTopic, Topeax, ClusteringTopicModel] -@pytest.mark.parametrize("model", supports_merging) +@pytest.mark.parametrize("model_cls", supports_merging) def test_merging(model_cls): model_kwargs = dict(encoder=trf) models = [] From c6f9ffbc4d4ea9ffa01cdb5affd3a208326163af Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?M=C3=A1rton=20Kardos?= Date: Tue, 24 Nov 2026 16:25:02 +0100 Subject: [PATCH 29/30] Added from future import annotations to all models --- turftopic/models/cluster.py | 2 ++ turftopic/models/decomp.py | 2 ++ turftopic/models/senstopic.py | 2 ++ turftopic/models/topeax.py | 2 ++ 4 files changed, 8 insertions(+) diff --git a/turftopic/models/cluster.py b/turftopic/models/cluster.py index 1432b5b..2ea18d1 100644 --- a/turftopic/models/cluster.py +++ b/turftopic/models/cluster.py @@ -1,3 +1,5 @@ +from __future__ import annotations + import tempfile import time import typing diff --git a/turftopic/models/decomp.py b/turftopic/models/decomp.py index 9d5a58f..77aa6d0 100644 --- a/turftopic/models/decomp.py +++ b/turftopic/models/decomp.py @@ -1,3 +1,5 @@ +from __future__ import annotations + import warnings from copy import deepcopy from datetime import datetime diff --git a/turftopic/models/senstopic.py b/turftopic/models/senstopic.py index 72aa5b0..e475bf5 100644 --- a/turftopic/models/senstopic.py +++ b/turftopic/models/senstopic.py @@ -1,3 +1,5 @@ +from __future__ import annotations + import warnings from copy import deepcopy from datetime import datetime, timedelta diff --git a/turftopic/models/topeax.py b/turftopic/models/topeax.py index a9883cc..169de1c 100644 --- a/turftopic/models/topeax.py +++ b/turftopic/models/topeax.py @@ -1,3 +1,5 @@ +from __future__ import annotations + from copy import deepcopy from typing import Callable, Optional, Union From 4dcfb148b20650fda08dc38dea9fb68ea6f75c57 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?M=C3=A1rton=20Kardos?= Date: Tue, 24 Nov 2026 17:22:46 +0100 Subject: [PATCH 30/30] Removed Topeax from merge testing and madee batches larger --- tests/test_integration.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tests/test_integration.py b/tests/test_integration.py index d2c010c..61e86ef 100644 --- a/tests/test_integration.py +++ b/tests/test_integration.py @@ -152,14 +152,14 @@ def test_fit_online(model): df = pd.read_csv(out_path) -supports_merging = [SensTopic, Topeax, ClusteringTopicModel] +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), 50): + 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)