| 23 | |
| 24 | |
| 25 | class TopicModel: |
| 26 | def __init__(self, config): |
| 27 | self.config = config |
| 28 | |
| 29 | def __repr__(self) -> str: |
| 30 | return f"TopicModel(config={self.config})" |
| 31 | |
| 32 | def fit_topic_model(self, topic_model, data, embeddings, key="query"): |
| 33 | topics, probs = topic_model.fit_transform(data[key].to_list(), embeddings) |
| 34 | return topics, probs |
| 35 | |
| 36 | def get_topic_info(self, topic_model): |
| 37 | return topic_model.get_topic_info() |
| 38 | |
| 39 | def reduce_topics(self, topic_model, data, nr_topics, key="query"): |
| 40 | topic_model.reduce_topics(data[key].to_list(), nr_topics) |
| 41 | return topic_model |
| 42 | |
| 43 | def get_representative_docs(self, topic_model): |
| 44 | return topic_model.get_representative_docs() |
| 45 | |
| 46 | def reduce_outliers(self, topic_model, data, topics, probs, key="query", strategy="c-tf-idf"): |
| 47 | if strategy == "c-tf-idf": |
| 48 | new_topics = topic_model.reduce_outliers(data[key].to_list(), topics, strategy, threshold=0.1) |
| 49 | elif strategy == "embeddings": |
| 50 | new_topics = topic_model.reduce_outliers(data[key].to_list(), topics, strategy) |
| 51 | elif strategy == "distributions": |
| 52 | new_topics = topic_model.reduce_outliers( |
| 53 | data[key].to_list(), topics, probabilities=probs, strategy=strategy |
| 54 | ) |
| 55 | else: |
| 56 | raise ValueError("Invalid strategy") |
| 57 | topic_model.update_topics( |
| 58 | data[key].to_list(), |
| 59 | topics=new_topics, |
| 60 | representation_model=self.representation_model, |
| 61 | vectorizer_model=self.vectorizer_model, |
| 62 | ctfidf_model=self.ctfidf_model, |
| 63 | ) |
| 64 | return topic_model, new_topics |
| 65 | |
| 66 | def compute_hierarchical_topic_tree(self, topic_model, data, key="query"): |
| 67 | hierarchical_topics = topic_model.hierarchical_topics(data[key].to_list()) |
| 68 | tree = topic_model.get_topic_tree(hierarchical_topics) |
| 69 | return hierarchical_topics, tree |
| 70 | |
| 71 | def run(self, data, gnn_outputs: Tuple[np.ndarray, np.ndarray], key="query") -> dict: |
| 72 | """ |
| 73 | Run the topic modeling. |
| 74 | """ |
| 75 | # Prepare the data |
| 76 | if self.config["auto_cluster"]: |
| 77 | if self.config["representation_model"].split("(")[0] == "pipeline": |
| 78 | generator = self.config["representation_model"] |
| 79 | representation_model = [MaximalMarginalRelevance(diversity=0.3), TextGeneration(eval(generator))] |
| 80 | elif self.config["representation_model"].split("(")[0] == "OpenAI": |
| 81 | representation_model = [ |
| 82 | MaximalMarginalRelevance(diversity=0.3), |
nothing calls this directly
no outgoing calls
no test coverage detected