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 fe3f720..46d1ccf 100644 --- a/docs/topic_merging.md +++ b/docs/topic_merging.md @@ -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** 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: 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" } diff --git a/tests/test_integration.py b/tests/test_integration.py index 4020f09..61e86ef 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, 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", diff --git a/turftopic/base.py b/turftopic/base.py index 7f60230..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 @@ -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] @@ -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_, @@ -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() 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]), 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. diff --git a/turftopic/merging.py b/turftopic/merging.py index e2bfbf7..c7bebef 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,9 +79,10 @@ 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, + topic_embeddings=None, ) -> tuple[np.ndarray, MergeHistory]: """Performs a symmetric merge on a number of topic models. @@ -82,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 ------- @@ -93,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: @@ -120,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): @@ -132,7 +167,8 @@ def asymmetric_merge( weights=None, match_threshold: float = 0.7, agg=keep_first, - sim_fn=cosine_similarity, + sim_fn=safe_cosine, + topic_embeddings=None, ) -> tuple[np.ndarray, MergeHistory]: """Performs an asymmetric merge on a number of topic models. @@ -150,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 ------- @@ -161,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): @@ -187,25 +235,45 @@ 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 = { "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 +316,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) diff --git a/turftopic/models/_snmf.py b/turftopic/models/_snmf.py index 5e134b0..ac0148b 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,14 +73,15 @@ 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 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: @@ -106,6 +110,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 +160,16 @@ def _body_fn(state): "n_iter": state["n_iter"] + 1, } + if freeze_G: + F = update_F(X.T, 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 +194,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 +268,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 +279,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, diff --git a/turftopic/models/cluster.py b/turftopic/models/cluster.py index ca828fb..2ea18d1 100644 --- a/turftopic/models/cluster.py +++ b/turftopic/models/cluster.py @@ -1,16 +1,20 @@ +from __future__ import annotations + import tempfile import time 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 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 +from sklearn.base import ClusterMixin, TransformerMixin, clone from sklearn.cluster import HDBSCAN from sklearn.exceptions import NotFittedError from sklearn.feature_extraction.text import CountVectorizer @@ -31,6 +35,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, @@ -429,6 +434,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: @@ -478,6 +530,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, @@ -505,6 +558,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( @@ -737,6 +791,157 @@ 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 + ------- + 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 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"): + 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, + ) + return self + + @classmethod + def merge_models( + cls, + models: list[ClusteringTopicModel], + 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 + class BERTopic(ClusteringTopicModel): """Convenience function to construct a BERTopic model in Turftopic. diff --git a/turftopic/models/decomp.py b/turftopic/models/decomp.py index 00d150a..77aa6d0 100644 --- a/turftopic/models/decomp.py +++ b/turftopic/models/decomp.py @@ -1,11 +1,14 @@ +from __future__ import annotations + 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 +19,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, @@ -30,6 +34,58 @@ ) +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) + + +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 ): @@ -186,9 +242,63 @@ 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 + 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], @@ -258,6 +368,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): @@ -644,6 +755,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, 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/senstopic.py b/turftopic/models/senstopic.py index 5784c0e..e475bf5 100644 --- a/turftopic/models/senstopic.py +++ b/turftopic/models/senstopic.py @@ -1,4 +1,7 @@ +from __future__ import annotations + import warnings +from copy import deepcopy from datetime import datetime, timedelta from functools import partial from typing import Callable, Literal, Optional, Union @@ -17,6 +20,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, @@ -169,6 +173,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 +274,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( @@ -437,7 +506,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) @@ -511,6 +580,126 @@ 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, + ): + """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]) + 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) diff --git a/turftopic/models/topeax.py b/turftopic/models/topeax.py index e3c7cc0..169de1c 100644 --- a/turftopic/models/topeax.py +++ b/turftopic/models/topeax.py @@ -1,4 +1,7 @@ -from typing import Optional, Union +from __future__ import annotations + +from copy import deepcopy +from typing import Callable, Optional, Union import numpy as np from scipy.ndimage import ( @@ -19,6 +22,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 +204,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 +220,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 diff --git a/turftopic/vectorizers/merging.py b/turftopic/vectorizers/merging.py index a4787da..c9aee64 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,98 @@ 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(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 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) + 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.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.issparse(joint_X): + joint_X = spr.csr_array(joint_X) + return joint_X + + def pad_right(self, right_X, pad_value=0): + if spr.issparse(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.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_) + + @property + def vocabulary_(self): + return dict(zip(self.joint_terms_, range(len(self.joint_terms_))))