|
| 1 | +#!/usr/bin/env python |
| 2 | +# -*- coding: utf-8 -*- |
| 3 | +# |
| 4 | +# Copyright (C) 2010 Radim Rehurek <[email protected]> |
| 5 | +# Licensed under the GNU LGPL v2.1 - http://www.gnu.org/licenses/lgpl.html |
| 6 | + |
| 7 | +""" |
| 8 | +Module for calculating topic coherence in python. This is the implementation of |
| 9 | +the four stage topic coherence pipeline from the paper [1]. |
| 10 | +The four stage pipeline is basically: |
| 11 | +
|
| 12 | +Segmentation -> Probability Estimation -> Confirmation Measure -> Aggregation. |
| 13 | +
|
| 14 | +Implementation of this pipeline allows for the user to in essence "make" a |
| 15 | +coherence measure of his/her choice by choosing a method in each of the pipelines. |
| 16 | +
|
| 17 | +[1] Michael Roeder, Andreas Both and Alexander Hinneburg. Exploring the space of topic |
| 18 | +coherence measures. http://svn.aksw.org/papers/2015/WSDM_Topic_Evaluation/public.pdf. |
| 19 | +""" |
| 20 | + |
| 21 | +import logging |
| 22 | + |
| 23 | +from gensim import interfaces |
| 24 | +from gensim.topic_coherence import (segmentation, probability_estimation, |
| 25 | + direct_confirmation_measure, indirect_confirmation_measure, |
| 26 | + aggregation) |
| 27 | +from gensim.corpora import Dictionary |
| 28 | +from gensim.matutils import argsort |
| 29 | +from gensim.utils import is_corpus |
| 30 | +from gensim.models.ldamodel import LdaModel |
| 31 | +from gensim.models.wrappers import LdaVowpalWabbit |
| 32 | + |
| 33 | +logger = logging.getLogger(__name__) |
| 34 | + |
| 35 | + |
| 36 | +class CoherenceModel(interfaces.TransformationABC): |
| 37 | + """ |
| 38 | + Objects of this class allow for building and maintaining a model for topic |
| 39 | + coherence. |
| 40 | +
|
| 41 | + The main methods are: |
| 42 | +
|
| 43 | + 1. constructor, which initializes the four stage pipeline by accepting a coherence measure, |
| 44 | + 2. the ``get_coherence()`` method, which returns the topic coherence. |
| 45 | +
|
| 46 | + >>> cm = CoherenceModel(model=tm, corpus=corpus, coherence='u_mass') # tm is the trained topic model |
| 47 | + >>> cm.get_coherence() |
| 48 | +
|
| 49 | + Model persistency is achieved via its load/save methods. |
| 50 | + """ |
| 51 | + def __init__(self, model, texts=None, corpus=None, dictionary=None, coherence='c_v'): |
| 52 | + """ |
| 53 | + Args: |
| 54 | + ---- |
| 55 | + model : Pre-trained topic model. |
| 56 | + texts : Tokenized texts. Needed for coherence models that use sliding window based probability estimator. |
| 57 | + corpus : Gensim document corpus. |
| 58 | + dictionary : Gensim dictionary mapping of id word to create corpus. |
| 59 | + coherence : Coherence measure to be used. Supported values are: |
| 60 | + u_mass |
| 61 | + c_v |
| 62 | + """ |
| 63 | + if texts is None and corpus is None: |
| 64 | + raise ValueError("One of texts or corpus has to be provided.") |
| 65 | + if coherence == 'u_mass': |
| 66 | + if is_corpus(corpus)[0]: |
| 67 | + if dictionary is None: |
| 68 | + if model.id2word[0] == 0: |
| 69 | + raise ValueError("The associated dictionary should be provided with the corpus or 'id2word' for topic model" |
| 70 | + "should be set as the dictionary.") |
| 71 | + else: |
| 72 | + self.dictionary = model.id2word |
| 73 | + else: |
| 74 | + self.dictionary = dictionary |
| 75 | + self.corpus = corpus |
| 76 | + elif texts is not None: |
| 77 | + self.texts = texts |
| 78 | + if dictionary is None: |
| 79 | + self.dictionary = Dictionary(self.texts) |
| 80 | + else: |
| 81 | + self.dictionary = dictionary |
| 82 | + self.corpus = [self.dictionary.doc2bow(text) for text in self.texts] |
| 83 | + else: |
| 84 | + raise ValueError("Either 'corpus' with 'dictionary' or 'texts' should be provided for %s coherence." % coherence) |
| 85 | + |
| 86 | + elif coherence == 'c_v': |
| 87 | + if texts is None: |
| 88 | + raise ValueError("'texts' should be provided for %s coherence." % coherence) |
| 89 | + else: |
| 90 | + self.texts = texts |
| 91 | + self.dictionary = Dictionary(self.texts) |
| 92 | + self.corpus = [self.dictionary.doc2bow(text) for text in self.texts] |
| 93 | + |
| 94 | + else: |
| 95 | + raise ValueError("%s coherence is not currently supported." % coherence) |
| 96 | + |
| 97 | + self.model = model |
| 98 | + self.topics = self._get_topics() |
| 99 | + self.coherence = coherence |
| 100 | + # Set pipeline parameters: |
| 101 | + if self.coherence == 'u_mass': |
| 102 | + self.seg = segmentation.s_one_pre |
| 103 | + self.prob = probability_estimation.p_boolean_document |
| 104 | + self.conf = direct_confirmation_measure.log_conditional_probability |
| 105 | + self.aggr = aggregation.arithmetic_mean |
| 106 | + |
| 107 | + elif self.coherence == 'c_v': |
| 108 | + self.seg = segmentation.s_one_set |
| 109 | + self.prob = probability_estimation.p_boolean_sliding_window |
| 110 | + self.conf = indirect_confirmation_measure.cosine_similarity |
| 111 | + self.aggr = aggregation.arithmetic_mean |
| 112 | + |
| 113 | + def __str__(self): |
| 114 | + return "CoherenceModel(segmentation=%s, probability estimation=%s, confirmation measure=%s, aggregation=%s)" % ( |
| 115 | + self.seg, self.prob, self.conf, self.aggr) |
| 116 | + |
| 117 | + def _get_topics(self): |
| 118 | + """Internal helper function to return topics from a trained topic model.""" |
| 119 | + topics = [] # FIXME : Meant to work for LDAModel, LdaVowpalWabbit right now. Make it work for others. |
| 120 | + if isinstance(self.model, LdaModel): |
| 121 | + for topic in self.model.state.get_lambda(): |
| 122 | + bestn = argsort(topic, topn=10, reverse=True) |
| 123 | + topics.append(bestn) |
| 124 | + elif isinstance(self.model, LdaVowpalWabbit): |
| 125 | + for topic in self.model._get_topics(): |
| 126 | + bestn = argsort(topic, topn=10, reverse=True) |
| 127 | + topics.append(bestn) |
| 128 | + return topics |
| 129 | + |
| 130 | + def get_coherence(self): |
| 131 | + if self.coherence == 'u_mass': |
| 132 | + segmented_topics = self.seg(self.topics) |
| 133 | + per_topic_postings, num_docs = self.prob(self.corpus, segmented_topics) |
| 134 | + confirmed_measures = self.conf(segmented_topics, per_topic_postings, num_docs) |
| 135 | + return self.aggr(confirmed_measures) |
| 136 | + |
| 137 | + elif self.coherence == 'c_v': |
| 138 | + segmented_topics = self.seg(self.topics) |
| 139 | + per_topic_postings, num_windows = self.prob(texts=self.texts, segmented_topics=segmented_topics, |
| 140 | + dictionary=self.dictionary, window_size=2) # FIXME : Change window size to 110 finally. |
| 141 | + confirmed_measures = self.conf(self.topics, segmented_topics, per_topic_postings, 'nlr', 1, num_windows) |
| 142 | + return self.aggr(confirmed_measures) |
0 commit comments