├── text ├── __init__.py ├── stopwords.txt └── util.py ├── unsupervised ├── __init__.py ├── nmf.py ├── util.py ├── rankings.py └── hungarian.py ├── data └── sample-text.zip ├── .gitignore ├── display-top-documents.py ├── display-top-terms.py ├── parse-file.py ├── eval-partition-stability.py ├── eval-term-difference.py ├── eval-term-stability.py ├── README.md ├── parse-directory.py ├── eval-partition-accuracy.py ├── generate-kfold.py ├── generate-nmf.py ├── combine-nmf.py └── LICENSE /text/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /unsupervised/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /data/sample-text.zip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/derekgreene/topic-ensemble/HEAD/data/sample-text.zip -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | env/ 12 | build/ 13 | develop-eggs/ 14 | dist/ 15 | downloads/ 16 | eggs/ 17 | .eggs/ 18 | lib/ 19 | lib64/ 20 | parts/ 21 | sdist/ 22 | var/ 23 | *.egg-info/ 24 | .installed.cfg 25 | *.egg 26 | 27 | # PyInstaller 28 | # Usually these files are written by a python script from a template 29 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 30 | *.manifest 31 | *.spec 32 | 33 | # Installer logs 34 | pip-log.txt 35 | pip-delete-this-directory.txt 36 | 37 | # Unit test / coverage reports 38 | htmlcov/ 39 | .tox/ 40 | .coverage 41 | .coverage.* 42 | .cache 43 | nosetests.xml 44 | coverage.xml 45 | *,cover 46 | .hypothesis/ 47 | 48 | # Translations 49 | *.mo 50 | *.pot 51 | 52 | # Django stuff: 53 | *.log 54 | local_settings.py 55 | 56 | # Flask stuff: 57 | instance/ 58 | .webassets-cache 59 | 60 | # Scrapy stuff: 61 | .scrapy 62 | 63 | # Sphinx documentation 64 | docs/_build/ 65 | 66 | # PyBuilder 67 | target/ 68 | 69 | # IPython Notebook 70 | .ipynb_checkpoints 71 | 72 | # pyenv 73 | .python-version 74 | 75 | # celery beat schedule file 76 | celerybeat-schedule 77 | 78 | # dotenv 79 | .env 80 | 81 | # virtualenv 82 | venv/ 83 | ENV/ 84 | 85 | # Spyder project settings 86 | .spyderproject 87 | 88 | # Rope project settings 89 | .ropeproject 90 | -------------------------------------------------------------------------------- /display-top-documents.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | """ 3 | Simple tool to display document rankings generated by NMF stored in one or more PKL 4 | files. 5 | 6 | Sample usage: 7 | python display-top-documents.py base-nmf/factors_1000_001.pkl 8 | """ 9 | import logging as log 10 | from optparse import OptionParser 11 | import numpy as np 12 | import unsupervised.rankings, unsupervised.util 13 | 14 | # -------------------------------------------------------------- 15 | 16 | def main(): 17 | parser = OptionParser(usage="usage: %prog [options] factor_file1 factor_file2 ...") 18 | parser.add_option("-t", "--top", action="store", type="int", dest="top", help="number of top document ids to show", default=10) 19 | (options, args) = parser.parse_args() 20 | if( len(args) < 1 ): 21 | parser.error( "Must specify at least one factor file" ) 22 | log.basicConfig(level=20, format='%(message)s') 23 | 24 | # Load each cached ranking set 25 | for in_path in args: 26 | log.info( "Loading model from %s ..." % in_path ) 27 | (W,H,doc_ids,terms) = unsupervised.util.load_nmf_factors( in_path ) 28 | k = W.shape[1] 29 | log.info( "Model has %d rankings covering %d documents" % ( k, len(doc_ids) ) ) 30 | for topic_index in range(k): 31 | top_indices = np.argsort( W[:,topic_index] )[::-1] 32 | top_indices = top_indices[0:min(len(top_indices),options.top)] 33 | top_doc_ids = [ doc_ids[index] for index in top_indices ] 34 | log.info("C%02d: %s" % (topic_index+1, ", ".join(top_doc_ids) ) ) 35 | 36 | # -------------------------------------------------------------- 37 | 38 | if __name__ == "__main__": 39 | main() 40 | -------------------------------------------------------------------------------- /display-top-terms.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | """ 3 | Simple tool to display term rankings generated by NMF/LDA, stored in one or more PKL 4 | files. 5 | 6 | Sample usage: 7 | python display-top-terms.py base-nmf/ranks_1000_001.pkl 8 | """ 9 | import logging as log 10 | from optparse import OptionParser 11 | import unsupervised.rankings, unsupervised.util 12 | 13 | # -------------------------------------------------------------- 14 | 15 | def main(): 16 | parser = OptionParser(usage="usage: %prog [options] ranking_file1 ranking_file2 ...") 17 | parser.add_option("-t", "--top", action="store", type="int", dest="top", help="number of top terms to show", default=10) 18 | parser.add_option("-l","--long", action="store_true", dest="long_display", help="long format display") 19 | (options, args) = parser.parse_args() 20 | if( len(args) < 1 ): 21 | parser.error( "Must specify at least one ranking set file" ) 22 | log.basicConfig(level=20, format='%(message)s') 23 | 24 | # Load each cached ranking set 25 | for in_path in args: 26 | log.info( "Loading term rankings from %s ..." % in_path ) 27 | (term_rankings,labels) = unsupervised.util.load_term_rankings( in_path ) 28 | m = unsupervised.rankings.term_rankings_size( term_rankings ) 29 | log.info( "Model has %d rankings covering %d terms" % ( len(term_rankings), m ) ) 30 | if options.long_display: 31 | print( unsupervised.rankings.format_term_rankings_long( term_rankings, labels, min(options.top,m) ) ) 32 | else: 33 | print( unsupervised.rankings.format_term_rankings( term_rankings, labels, min(options.top,m) ) ) 34 | 35 | # -------------------------------------------------------------- 36 | 37 | if __name__ == "__main__": 38 | main() 39 | -------------------------------------------------------------------------------- /unsupervised/nmf.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | from sklearn import decomposition 3 | import logging as log 4 | 5 | # -------------------------------------------------------------- 6 | 7 | class SklNMF: 8 | """ 9 | Wrapper class backed by the scikit-learn package NMF implementation. 10 | """ 11 | def __init__( self, max_iters = 100, init_strategy = "random" ): 12 | self.max_iters = 100 13 | self.init_strategy = init_strategy 14 | self.W = None 15 | self.H = None 16 | 17 | def apply( self, X, k = 2, init_W = None, init_H = None ): 18 | """ 19 | Apply NMF to the specified document-term matrix X. 20 | """ 21 | self.W = None 22 | self.H = None 23 | random_seed = np.random.randint( 1, 100000 ) 24 | if not (init_W is None or init_H is None): 25 | model = decomposition.NMF( init="custom", n_components=k, max_iter=self.max_iters, random_state = random_seed ) 26 | self.W = model.fit_transform( X, W=init_W, H=init_H ) 27 | else: 28 | model = decomposition.NMF( init=self.init_strategy, n_components=k, max_iter=self.max_iters, random_state = random_seed ) 29 | self.W = model.fit_transform( X ) 30 | self.H = model.components_ 31 | 32 | def rank_terms( self, topic_index, top = -1 ): 33 | """ 34 | Return the top ranked terms for the specified topic, generated during the last NMF run. 35 | """ 36 | if self.H is None: 37 | raise ValueError("No results for previous run available") 38 | # NB: reverse 39 | top_indices = np.argsort( self.H[topic_index,:] )[::-1] 40 | # truncate if necessary 41 | if top < 1 or top > len(top_indices): 42 | return top_indices 43 | return top_indices[0:top] 44 | 45 | def generate_partition( self ): 46 | if self.W is None: 47 | raise ValueError("No results for previous run available") 48 | return np.argmax( self.W, axis = 1 ).flatten().tolist() 49 | 50 | 51 | 52 | -------------------------------------------------------------------------------- /parse-file.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | """ 3 | Tool to parse a collection of documents, where each document is a single line in one or more text files. 4 | 5 | Sample usage: 6 | python parse-file.py data/sample.txt -o sample --tfidf --norm 7 | """ 8 | import os, os.path, sys, codecs, re, unicodedata 9 | import logging as log 10 | from optparse import OptionParser 11 | import text.util 12 | 13 | # -------------------------------------------------------------- 14 | 15 | def main(): 16 | parser = OptionParser(usage="usage: %prog [options] file1 file2 ...") 17 | parser.add_option("-o", action="store", type="string", dest="prefix", help="output prefix for corpus files", default=None) 18 | parser.add_option("--df", action="store", type="int", dest="min_df", help="minimum number of documents for a term to appear", default=20) 19 | parser.add_option("--tfidf", action="store_true", dest="apply_tfidf", help="apply TF-IDF term weight to the document-term matrix") 20 | parser.add_option("--norm", action="store_true", dest="apply_norm", help="apply unit length normalization to the document-term matrix") 21 | parser.add_option("--minlen", action="store", type="int", dest="min_doc_length", help="minimum document length (in characters)", default=50) 22 | parser.add_option("-s", action="store", type="string", dest="stoplist_file", help="custom stopword file path", default=None) 23 | parser.add_option('-d','--debug',type="int",help="Level of log output; 0 is less, 5 is all", default=3) 24 | (options, args) = parser.parse_args() 25 | if( len(args) < 1 ): 26 | parser.error( "Must specify at least one input file" ) 27 | log.basicConfig(level=max(50 - (options.debug * 10), 10), format='%(message)s') 28 | 29 | # Read the documents 30 | docs = [] 31 | short_documents = 0 32 | doc_ids = [] 33 | for in_path in args: 34 | file_count = 0 35 | log.info( "Reading documents from %s, one per line ..." % in_path ) 36 | fin = codecs.open(in_path, 'r', encoding="utf8", errors='ignore') 37 | for line in fin.readlines(): 38 | body = line.strip() 39 | if len(body) < options.min_doc_length: 40 | short_documents += 1 41 | continue 42 | doc_id = "%05d" % ( len(doc_ids) + 1 ) 43 | docs.append(body) 44 | doc_ids.append(doc_id) 45 | file_count += 1 46 | log.info( "Kept %d documents from %s" % (file_count, in_path) ) 47 | log.info( "Kept %d documents. Skipped %d documents with length < %d" % ( len(docs), short_documents, options.min_doc_length ) ) 48 | 49 | # Convert the documents in TF-IDF vectors and filter stopwords 50 | if options.stoplist_file is None: 51 | stopwords = text.util.load_stopwords("text/stopwords.txt") 52 | elif options.stoplist_file.lower() == "none": 53 | log.info("Using no stopwords") 54 | stopwords = set() 55 | else: 56 | log.info( "Using custom stopwords from %s" % options.stoplist_file ) 57 | stopwords = text.util.load_stopwords(options.stoplist_file) 58 | log.info( "Pre-processing data (%d stopwords, tfidf=%s, normalize=%s, min_df=%d) ..." % (len(stopwords), options.apply_tfidf, options.apply_norm, options.min_df) ) 59 | (X,terms) = text.util.preprocess( docs, stopwords, min_df = options.min_df, apply_tfidf = options.apply_tfidf, apply_norm = options.apply_norm ) 60 | log.info( "Built document-term matrix: %d documents, %d terms" % (X.shape[0], X.shape[1]) ) 61 | 62 | # Store the corpus 63 | prefix = options.prefix 64 | if prefix is None: 65 | prefix = "corpus" 66 | log.info( "Saving corpus '%s'" % prefix ) 67 | text.util.save_corpus( prefix, X, terms, doc_ids, None ) 68 | 69 | # -------------------------------------------------------------- 70 | 71 | if __name__ == "__main__": 72 | main() 73 | -------------------------------------------------------------------------------- /text/stopwords.txt: -------------------------------------------------------------------------------- 1 | a 2 | about 3 | above 4 | according 5 | across 6 | actually 7 | adj 8 | after 9 | afterwards 10 | again 11 | all 12 | almost 13 | along 14 | already 15 | also 16 | although 17 | always 18 | am 19 | among 20 | amongst 21 | an 22 | and 23 | another 24 | any 25 | anyhow 26 | anyone 27 | anything 28 | anywhere 29 | are 30 | aren 31 | arent 32 | around 33 | as 34 | at 35 | be 36 | became 37 | because 38 | become 39 | becomes 40 | been 41 | beforehand 42 | begin 43 | being 44 | below 45 | beside 46 | besides 47 | between 48 | both 49 | br 50 | but 51 | by 52 | can 53 | cannot 54 | cant 55 | caption 56 | co 57 | come 58 | could 59 | couldn 60 | couldnt 61 | did 62 | didn 63 | didnt 64 | do 65 | does 66 | doesn 67 | doesnt 68 | don 69 | dont 70 | down 71 | dr 72 | during 73 | each 74 | early 75 | eg 76 | either 77 | else 78 | elsewhere 79 | end 80 | ending 81 | enough 82 | etc 83 | even 84 | ever 85 | every 86 | everywhere 87 | except 88 | few 89 | for 90 | found 91 | fr 92 | from 93 | further 94 | had 95 | hadnt 96 | has 97 | hasn 98 | hasnt 99 | have 100 | haven 101 | havent 102 | he 103 | hence 104 | her 105 | here 106 | hereafter 107 | hereby 108 | herein 109 | hereupon 110 | hers 111 | him 112 | his 113 | how 114 | however 115 | ie 116 | if 117 | in 118 | inc 119 | indeed 120 | instead 121 | into 122 | is 123 | isn 124 | isnt 125 | it 126 | its 127 | itself 128 | just 129 | last 130 | late 131 | later 132 | less 133 | let 134 | like 135 | likely 136 | ll 137 | ltd 138 | made 139 | make 140 | makes 141 | many 142 | may 143 | maybe 144 | me 145 | meantime 146 | meanwhile 147 | might 148 | miss 149 | more 150 | most 151 | mostly 152 | mr 153 | mrs 154 | ms 155 | much 156 | must 157 | my 158 | myself 159 | namely 160 | near 161 | neither 162 | never 163 | nevertheless 164 | new 165 | next 166 | no 167 | nobody 168 | non 169 | none 170 | nonetheless 171 | noone 172 | nor 173 | not 174 | now 175 | of 176 | off 177 | often 178 | on 179 | once 180 | only 181 | onto 182 | or 183 | other 184 | others 185 | otherwise 186 | our 187 | ours 188 | ourselves 189 | out 190 | over 191 | own 192 | per 193 | perhaps 194 | prof 195 | rather 196 | re 197 | rev 198 | said 199 | same 200 | say 201 | seem 202 | seemed 203 | seeming 204 | seems 205 | several 206 | she 207 | should 208 | shouldn 209 | shouldnt 210 | since 211 | so 212 | some 213 | sr 214 | still 215 | stop 216 | such 217 | taking 218 | ten 219 | th 220 | than 221 | that 222 | the 223 | their 224 | them 225 | themselves 226 | then 227 | thence 228 | there 229 | thereafter 230 | thereby 231 | therefore 232 | therein 233 | thereupon 234 | these 235 | they 236 | this 237 | those 238 | though 239 | thousand 240 | through 241 | throughout 242 | thru 243 | thus 244 | to 245 | together 246 | too 247 | toward 248 | towards 249 | under 250 | unless 251 | unlike 252 | unlikely 253 | until 254 | up 255 | upon 256 | us 257 | use 258 | used 259 | using 260 | ve 261 | very 262 | via 263 | was 264 | wasn 265 | we 266 | well 267 | were 268 | weren 269 | werent 270 | what 271 | whatever 272 | when 273 | whence 274 | whenever 275 | where 276 | whereafter 277 | whereas 278 | whereby 279 | wherein 280 | whereupon 281 | wherever 282 | whether 283 | which 284 | while 285 | whither 286 | who 287 | whoever 288 | whole 289 | whom 290 | whomever 291 | whose 292 | why 293 | will 294 | with 295 | within 296 | without 297 | won 298 | would 299 | wouldn 300 | wouldnt 301 | yes 302 | yet 303 | you 304 | your 305 | yours 306 | yourself 307 | yourselves 308 | one 309 | two 310 | three 311 | four 312 | five 313 | six 314 | seven 315 | eight 316 | nine 317 | ten 318 | eleven 319 | twelve 320 | thirteen 321 | fourteen 322 | fifteen 323 | twenty 324 | thirty 325 | forty 326 | fifty 327 | sixty 328 | seventy 329 | eighty 330 | ninety 331 | hundred 332 | thousand 333 | million 334 | millions 335 | billion 336 | billions 337 | percent 338 | yr 339 | year 340 | years 341 | first 342 | second 343 | third 344 | fourth 345 | fifth 346 | tenth 347 | hundredth 348 | -------------------------------------------------------------------------------- /eval-partition-stability.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | """ 3 | Evaluate the stability (i.e. agreement) between a set of partitions generated on the same dataset, using Pairwise Normalized Mutual Information (PNMI). 4 | 5 | Sample usage: 6 | python eval-partition-stability.py models/base/*partition*.pkl 7 | """ 8 | import os, sys 9 | import logging as log 10 | from optparse import OptionParser 11 | import numpy as np 12 | from prettytable import PrettyTable 13 | from sklearn.metrics.cluster import normalized_mutual_info_score 14 | import unsupervised.nmf, unsupervised.util 15 | 16 | # -------------------------------------------------------------- 17 | 18 | def main(): 19 | parser = OptionParser(usage="usage: %prog [options] partition_file1|directory1 ...") 20 | parser.add_option("-o","--output", action="store", type="string", dest="out_path", help="path for CSV summary file (by default this is not written)", default=None) 21 | parser.add_option("--hist", action="store", type="string", dest="hist_out_path", help="path for histogram CSV file (by default this is not written)", default=None) 22 | # Parse command line arguments 23 | (options, args) = parser.parse_args() 24 | if( len(args) < 1 ): 25 | parser.error( "Must specify one or more partitions/directories" ) 26 | log.basicConfig(level=20, format='%(message)s') 27 | 28 | # Get list of all specified partition files 29 | file_paths = [] 30 | for path in args: 31 | if not os.path.exists( path ): 32 | log.error("No such file or directory: %s" % path ) 33 | sys.exit(1) 34 | if os.path.isdir(path): 35 | log.debug("Searching %s for partitions" % path ) 36 | for dir_path, dirs, files in os.walk(path): 37 | for fname in files: 38 | if fname.startswith("partition") and fname.endswith(".pkl"): 39 | file_paths.append( os.path.join( dir_path, fname ) ) 40 | else: 41 | file_paths.append( path ) 42 | file_paths.sort() 43 | 44 | if len(file_paths) == 0: 45 | log.error("No partition files found to validate") 46 | sys.exit(1) 47 | log.info("Processing partitions for %d base topic models ..." % len(file_paths) ) 48 | 49 | # Load cached partitions 50 | all_partitions = [] 51 | for file_path in file_paths: 52 | log.debug( "Loading partition from %s" % file_path ) 53 | partition,cluster_doc_ids = unsupervised.util.load_partition( file_path ) 54 | all_partitions.append( partition ) 55 | 56 | r = len(all_partitions) 57 | log.info( "Evaluating stability of %d partitions with NMI ..." % r ) 58 | # compute NMI of each pair of partitions 59 | all_scores = [] 60 | for i in range(r): 61 | for j in range(i+1,r): 62 | score = normalized_mutual_info_score( all_partitions[i], all_partitions[j] ) 63 | all_scores.append( score ) 64 | 65 | # Get overall score across all pairs 66 | all_scores = np.array( all_scores ) 67 | tab = PrettyTable( ["statistic","stability"] ) 68 | tab.align["statistic"] = "l" 69 | tab.add_row( [ "mean", "%.3f" % all_scores.mean() ] ) 70 | tab.add_row( [ "median", "%.3f" % np.median(all_scores) ] ) 71 | tab.add_row( [ "sdev", "%.3f" % all_scores.std() ] ) 72 | tab.add_row( [ "min", "%.3f" % all_scores.min() ] ) 73 | tab.add_row( [ "max", "%.3f" % all_scores.max() ] ) 74 | log.info( tab ) 75 | 76 | # Write summary to CSV? 77 | if not options.out_path is None: 78 | log.info("Writing summary of results to %s" % options.out_path) 79 | unsupervised.util.write_table( options.out_path, tab ) 80 | 81 | # Write histogram to CSV? 82 | if not options.hist_out_path is None: 83 | #bins = np.arange(0,1.1,0.1) 84 | bins = np.arange(0,1.01,0.05) 85 | inds = list(np.digitize(all_scores, bins, right=True)) 86 | log.info("Writing histogram of results to %s" % options.hist_out_path) 87 | with open(options.hist_out_path,"w") as fout: 88 | fout.write("NMI,Count,Fraction\n") 89 | for ind, b in enumerate(bins): 90 | freq = inds.count(ind) 91 | frac = float(freq)/len(all_scores) 92 | fout.write("%.2f,%d,%.3f\n" % (b, freq, frac ) ) 93 | 94 | # -------------------------------------------------------------- 95 | 96 | if __name__ == "__main__": 97 | main() 98 | -------------------------------------------------------------------------------- /unsupervised/util.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | from scipy import sparse as sp 3 | # note that we use the scikit-learn bundled version of joblib 4 | from sklearn.externals import joblib 5 | 6 | # -------------------------------------------------------------- 7 | 8 | def build_centroids( X, partition, k ): 9 | """ 10 | Build a set of K centroids based on the specified partition memberships. 11 | """ 12 | # NB: need to convert to a numpy array before we do this... 13 | memberships = np.array(partition) 14 | n_features = X.shape[1] 15 | centroids = np.empty((k, n_features), dtype=np.float64) 16 | for i in range(k): 17 | center_mask = memberships == i 18 | if sp.issparse(X): 19 | center_mask = np.where(center_mask)[0] 20 | centroids[i] = X[center_mask].mean(axis=0) 21 | return centroids 22 | 23 | def clustermap_to_partition( cluster_map, doc_ids ): 24 | """ 25 | Convert a dictionary representing a clustering into a partition. 26 | """ 27 | cluster_names = list(cluster_map.keys()) 28 | cluster_names.sort() 29 | # build document map 30 | partition = [] 31 | doc_map = {} 32 | for i in range( len(doc_ids) ): 33 | partition.append( -1 ) 34 | doc_map[ doc_ids[i] ] = i 35 | # now create partition 36 | for cluster_index in range( len(cluster_map) ): 37 | for doc_id in cluster_map[cluster_names[cluster_index]]: 38 | partition[doc_map[doc_id]] = cluster_index 39 | return partition 40 | 41 | # -------------------------------------------------------------- 42 | 43 | def save_term_rankings( out_path, term_rankings, labels = None ): 44 | """ 45 | Save a list of multiple term rankings using Joblib. 46 | """ 47 | # no labels? generate some standard ones 48 | if labels is None: 49 | labels = [] 50 | for i in range( len(term_rankings) ): 51 | labels.append( "C%02d" % (i+1) ) 52 | joblib.dump((term_rankings,labels), out_path ) 53 | 54 | def load_term_rankings( in_path ): 55 | """ 56 | Load a list of multiple term rankings using Joblib. 57 | """ 58 | #print "Loading term rankings from %s ..." % in_path 59 | (term_rankings,labels) = joblib.load( in_path ) 60 | return (term_rankings,labels) 61 | 62 | def save_nmf_factors( out_path, W, H, doc_ids, terms ): 63 | """ 64 | Save a NMF factorization result using Joblib. 65 | """ 66 | joblib.dump((W,H,doc_ids,terms), out_path ) 67 | 68 | def load_nmf_factors( in_path ): 69 | """ 70 | Load a NMF factorization result using Joblib. 71 | """ 72 | (W,H,doc_ids,terms) = joblib.load( in_path ) 73 | return (W,H,doc_ids,terms) 74 | 75 | def save_partition( out_path, partition, doc_ids ): 76 | """ 77 | Save a disjoint partition (clustering) result using Joblib. 78 | """ 79 | joblib.dump((partition,doc_ids), out_path ) 80 | 81 | 82 | def load_partition( in_path): 83 | """ 84 | Load a disjoint partition (clustering) result using Joblib. 85 | """ 86 | (partition,doc_ids) = joblib.load( in_path ) 87 | return (partition,doc_ids) 88 | 89 | def save_lda_doc_weights(out_path, W ): 90 | """ 91 | Save a lda document weight matrix 92 | """ 93 | joblib.dump(W, out_path ) 94 | 95 | def load_lda_doc_weights( in_path): 96 | """ 97 | Load a lda document weight matrix 98 | """ 99 | W = joblib.load( in_path ) 100 | return(W) 101 | 102 | 103 | # -------------------------------------------------------------- 104 | 105 | def write_table( out_path, tab, delimiter = ',' ): 106 | """ 107 | Utility function to write a Prettytable table to a plain text output file, with the specified delimiter. 108 | """ 109 | import csv 110 | fout = open(out_path, 'w') 111 | w = csv.writer(fout, delimiter=delimiter, quoting=csv.QUOTE_MINIMAL) 112 | w.writerow(tab.field_names) 113 | for row in tab._rows: 114 | w.writerow(row) 115 | fout.close() 116 | -------------------------------------------------------------------------------- /eval-term-difference.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | """ 3 | Evaluate the agreement between the union of terms used by 2 topic models, generated on the same dataset, using Average Descriptor Set Difference (ADSD). 4 | 5 | Sample usage: 6 | python eval-term-difference.py models/base/ranks*.pkl 7 | python eval-term-difference.py models/base/ 8 | """ 9 | import os, sys 10 | import logging as log 11 | from optparse import OptionParser 12 | import numpy as np 13 | from prettytable import PrettyTable 14 | import unsupervised.nmf, unsupervised.rankings, unsupervised.util 15 | 16 | # -------------------------------------------------------------- 17 | 18 | def main(): 19 | parser = OptionParser(usage="usage: %prog [options] test_rank_file1|directory1 ...") 20 | parser.add_option("-t", "--top", action="store", type="int", dest="top", help="number of top terms to use", default=10) 21 | parser.add_option("-o","--output", action="store", type="string", dest="out_path", help="path for CSV output file", default=None) 22 | # Parse command line arguments 23 | (options, args) = parser.parse_args() 24 | if( len(args) < 1 ): 25 | parser.error( "Must specify one or more term rankings or directories" ) 26 | log.basicConfig(level=20, format='%(message)s') 27 | top = options.top 28 | 29 | # Get list of all specified term ranking files 30 | file_paths = [] 31 | for path in args: 32 | if not os.path.exists( path ): 33 | log.error("No such file or directory: %s" % path ) 34 | sys.exit(1) 35 | if os.path.isdir(path): 36 | log.info("Searching %s for term ranking files" % path ) 37 | for dir_path, dirs, files in os.walk(path): 38 | for fname in files: 39 | if fname.startswith("ranks") and fname.endswith(".pkl"): 40 | file_paths.append( os.path.join( dir_path, fname ) ) 41 | else: 42 | file_paths.append( path ) 43 | file_paths.sort() 44 | if len(file_paths) == 0: 45 | log.error("No term ranking files found to validate") 46 | sys.exit(1) 47 | log.info( "Processing %d topic models ..." % len(file_paths) ) 48 | 49 | # Load cached ranking sets 50 | all_term_rankings = [] 51 | for rank_path in file_paths: 52 | log.debug( "Loading test term ranking set from %s ..." % rank_path ) 53 | (term_rankings,labels) = unsupervised.util.load_term_rankings( rank_path ) 54 | log.debug( "Set has %d rankings covering %d terms" % ( len(term_rankings), unsupervised.rankings.term_rankings_size( term_rankings ) ) ) 55 | all_term_rankings.append( term_rankings ) 56 | num_models = len(all_term_rankings) 57 | 58 | # For number of top terms 59 | metric = unsupervised.rankings.JaccardBinary() 60 | log.debug("Comparing unions of top %d terms ..." % top ) 61 | # get the set of all terms used in the top terms for specified model 62 | all_model_terms = [] 63 | for term_rankings in all_term_rankings: 64 | model_terms = set() 65 | for ranking in unsupervised.rankings.truncate_term_rankings( term_rankings, top ): 66 | for term in ranking: 67 | model_terms.add( term ) 68 | all_model_terms.append( model_terms ) 69 | all_scores = [] 70 | # perform pairwise comparisons 71 | for i in range(num_models): 72 | # NB: assume same value of K for both models 73 | base_k = len(all_term_rankings[i]) 74 | for j in range(i+1,num_models): 75 | diff = len( all_model_terms[i].symmetric_difference(all_model_terms[j]) ) 76 | ndiff = float(diff)/(base_k*top) 77 | all_scores.append( ndiff ) 78 | 79 | # Get overall score across all pairs 80 | all_scores = np.array( all_scores ) 81 | tab = PrettyTable( ["statistic","diff"] ) 82 | tab.align["statistic"] = "l" 83 | tab.add_row( [ "mean", "%.3f" % all_scores.mean() ] ) 84 | tab.add_row( [ "median", "%.3f" % np.median(all_scores) ] ) 85 | tab.add_row( [ "sdev", "%.3f" % all_scores.std() ] ) 86 | tab.add_row( [ "min", "%.3f" % all_scores.min() ] ) 87 | tab.add_row( [ "max", "%.3f" % all_scores.max() ] ) 88 | log.info( tab ) 89 | 90 | # Write to CSV? 91 | if not options.out_path is None: 92 | log.info("Writing summary of results to %s" % options.out_path ) 93 | unsupervised.util.write_table( options.out_path, tab ) 94 | 95 | # -------------------------------------------------------------- 96 | 97 | if __name__ == "__main__": 98 | main() 99 | -------------------------------------------------------------------------------- /eval-term-stability.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | """ 3 | Evaluate the stability (i.e. agreement) between a set of term rankings generated on the same dataset, using Average Term Stability (ATS). 4 | 5 | Sample usage: 6 | python eval-term-stability.py models/base/ranks*.pkl 7 | python eval-term-stability.py models/base/ 8 | """ 9 | import os, sys 10 | import logging as log 11 | from optparse import OptionParser 12 | import numpy as np 13 | from prettytable import PrettyTable 14 | import unsupervised.nmf, unsupervised.rankings, unsupervised.util 15 | 16 | # -------------------------------------------------------------- 17 | 18 | def main(): 19 | parser = OptionParser(usage="usage: %prog [options] rank_file1|directory1 ...") 20 | parser.add_option("-t", "--top", action="store", type="int", dest="top", help="number of top terms to use", default=10) 21 | parser.add_option("-o","--output", action="store", type="string", dest="out_path", help="path for CSV output file", default=None) 22 | # Parse command line arguments 23 | (options, args) = parser.parse_args() 24 | if( len(args) < 1 ): 25 | parser.error( "Must specify one or more term rankings or directories" ) 26 | log.basicConfig(level=20, format='%(message)s') 27 | 28 | # Get list of all specified term ranking files 29 | file_paths = [] 30 | for path in args: 31 | if not os.path.exists( path ): 32 | log.error("No such file or directory: %s" % path ) 33 | sys.exit(1) 34 | if os.path.isdir(path): 35 | log.info("Searching %s for term ranking files" % path ) 36 | for dir_path, dirs, files in os.walk(path): 37 | for fname in files: 38 | if fname.startswith("ranks") and fname.endswith(".pkl"): 39 | file_paths.append( os.path.join( dir_path, fname ) ) 40 | else: 41 | file_paths.append( path ) 42 | file_paths.sort() 43 | if len(file_paths) == 0: 44 | log.error("No term ranking files found to validate") 45 | sys.exit(1) 46 | log.info( "Processing %d topic models ..." % len(file_paths) ) 47 | 48 | # Load cached ranking sets 49 | all_term_rankings = [] 50 | for rank_path in file_paths: 51 | log.debug( "Loading term ranking set from %s ..." % rank_path ) 52 | (term_rankings,labels) = unsupervised.util.load_term_rankings( rank_path ) 53 | log.debug( "Set has %d rankings covering %d terms" % ( len(term_rankings), unsupervised.rankings.term_rankings_size( term_rankings ) ) ) 54 | # do we need to truncate the number of terms in the ranking? 55 | if options.top > 1: 56 | term_rankings = unsupervised.rankings.truncate_term_rankings( term_rankings, options.top ) 57 | log.debug( "Truncated to %d -> set now has %d rankings covering %d terms" % ( options.top, len(term_rankings), unsupervised.rankings.term_rankings_size( term_rankings ) ) ) 58 | all_term_rankings.append( term_rankings ) 59 | 60 | r = len(all_term_rankings) 61 | metric = unsupervised.rankings.JaccardBinary() 62 | matcher = unsupervised.rankings.RankingSetAgreement( metric ) 63 | 64 | # Perform pairwise comparisons evaluation for all models 65 | log.info( "Evaluating stability %d base term rankings with %s and top %d terms ..." % (r, str(metric), options.top) ) 66 | all_scores = [] 67 | for i in range(r): 68 | for j in range(i+1,r): 69 | try: 70 | score = matcher.similarity( all_term_rankings[i], all_term_rankings[j] ) 71 | all_scores.append( score ) 72 | except Exception as e: 73 | log.warning("Error occurred comparing pair (%d,%d): %s" % ( i, j, str(e) ) ) 74 | log.info("Compared %d pairs of term rankings" % len(all_scores) ) 75 | 76 | # Get overall score across all pairs 77 | all_scores = np.array( all_scores ) 78 | tab = PrettyTable( ["statistic","stability"] ) 79 | tab.align["statistic"] = "l" 80 | tab.add_row( [ "mean", "%.3f" % all_scores.mean() ] ) 81 | tab.add_row( [ "median", "%.3f" % np.median(all_scores) ] ) 82 | tab.add_row( [ "sdev", "%.3f" % all_scores.std() ] ) 83 | tab.add_row( [ "min", "%.3f" % all_scores.min() ] ) 84 | tab.add_row( [ "max", "%.3f" % all_scores.max() ] ) 85 | log.info( tab ) 86 | 87 | # Write to CSV? 88 | if not options.out_path is None: 89 | log.info("Writing summary of results to %s" % options.out_path) 90 | unsupervised.util.write_table( options.out_path, tab ) 91 | 92 | # -------------------------------------------------------------- 93 | 94 | if __name__ == "__main__": 95 | main() 96 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | topic-ensemble 2 | =============== 3 | 4 | This repository contains a Python reference implementation of methods for ensemble topic modeling with Non-negative Matrix Factorization (NMF). 5 | 6 | Details of these methods are described in the following paper [[Link]](https://doi.org/10.1016/j.eswa.2017.08.047): 7 | 8 | Belford, M., Mac Namee, B., & Greene, D. (2018). Stability of topic modeling via matrix factorization. 9 | Expert Systems with Applications, 91, 159-169. 10 | 11 | Draft pre-print: [https://arxiv.org/abs/1702.07186](https://arxiv.org/abs/1702.07186) 12 | 13 | Additional pre-processed datasets for use with this package [can be downloaded here](http://mlg.ucd.ie/files/datasets/stability-topic-datasets.zip) (179MB). 14 | 15 | ### Dependencies 16 | Tested with Python 3.5, and requiring the following packages, which are available via PIP: 17 | 18 | * Required: [numpy >= 1.8.0](http://www.numpy.org/) 19 | * Required: [scikit-learn >= 0.14](http://scikit-learn.org/stable/) 20 | * Required for utility tools: [prettytable >= 0.7.2](https://code.google.com/p/prettytable/) 21 | 22 | ### Basic Usage 23 | #### Step 1. 24 | Before applying topic modeling to a corpus, the first step is to pre-process the corpus and store it in a suitable format. The script 'parse-directory.py' can be used to parse a directory of plain text documents. Here, we parse all .txt files in the directory or sub-directories of 'data/sample-text'. 25 | 26 | python parse-directory.py data/sample-text/ -o sample --tfidf --norm 27 | 28 | The output will be sample.pkl, stored as a Joblib binary file. The identifiers of the documents in the dataset correspond to the original text input filenames. 29 | 30 | Alternatively, if all of your documents are stored in a text file, with one document per line, the script 'parse-file.py' can be used: 31 | 32 | python parse-file.py data/sample.txt -o sample --tfidf --norm 33 | 34 | #### Step 2. 35 | Next, we generate a set of "base" topic models, which represent the members of the ensemble. We provide two different ways to do this. 36 | 37 | Firstly, we can generate a specified number of base topic models using NMF and random initialization (the "Basic Ensemble" approach). For instance, we can generate 20 models, each containing *k=4* topics, where each NMF run will execute for a maximum of 100 iterations. The models will be written to the directory 'models/base' as separate Joblib files. 38 | 39 | python generate-nmf.py sample.pkl -k 4 -r 20 --maxiters 100 -o models/base 40 | 41 | Alternatively, we can use the "K-Fold" ensemble approach. For instance, to execute 5 repetitions of 10 folds, we run: 42 | 43 | python generate-kfold.py sample.pkl -k 4 -r 5 -f 10 --maxiters 100 -o models/base 44 | 45 | #### Step 3. 46 | The next step is to combine the base topic models using an ensemble approach, to produce a final ensemble model. Note that we specify all of the factor files from the base topic models to combine, along with the number of overall ensemble topics (here again we specify *k=4*). The model will be written as a number of files to the directory 'models/ensemble'. 47 | 48 | python combine-nmf.py sample.pkl models/base/*factors*.pkl -k 4 -o models/ensemble 49 | 50 | #### Browsing Results 51 | 52 | We can display the top 10 terms in the topic descriptors for the final ensemble results in tabular format: 53 | 54 | python display-top-terms.py models/ensemble/ranks_ensemble_k04.pkl 55 | 56 | Or using a line-by-line format: 57 | 58 | python display-top-terms.py -l models/ensemble/ranks_ensemble_k04.pkl 59 | 60 | Similarly, we can display the identifiers of the top-ranked documents for each topic: 61 | 62 | python display-top-documents.py models/ensemble/factors_ensemble_k04.pkl 63 | 64 | ### Evaluation Measures 65 | 66 | To evaluate the Normalized Mutual Information (NMI) accuracy of the document partitions associated with one or more topic models, relative to a ground truth dataset, run: 67 | 68 | python eval-partition-accuracy.py sample.pkl models/base/partition*.pkl 69 | 70 | To evaluate the stability of a collection of document partitions using Pairwise Normalized Mutual Information (PNMI), run: 71 | 72 | python eval-partition-stability.py models/base/partition*.pkl 73 | 74 | To evaluate the stability of a collection of term rankings from topic models using Average Term Stability (ATS), run: 75 | 76 | python eval-term-stability.py models/base/ranks*.pkl 77 | 78 | To evaluate the stability of a collection of term rankings from topic models using Average Descriptor Set Difference (ADSD), run: 79 | 80 | python eval-term-difference.py models/base/ranks*.pkl 81 | -------------------------------------------------------------------------------- /parse-directory.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | """ 3 | Tool to parse a collection of documents, where each file is stored in a separate plain text file. 4 | 5 | Sample usage: 6 | python parse-directory.py data/sample-text/ -o sample --tfidf --norm 7 | """ 8 | import os, os.path, sys, codecs, re, unicodedata 9 | import logging as log 10 | from optparse import OptionParser 11 | import text.util 12 | 13 | # -------------------------------------------------------------- 14 | 15 | def main(): 16 | parser = OptionParser(usage="usage: %prog [options] dir1 dir2 ...") 17 | parser.add_option("-o", action="store", type="string", dest="prefix", help="output prefix for corpus files", default=None) 18 | parser.add_option("--df", action="store", type="int", dest="min_df", help="minimum number of documents for a term to appear", default=20) 19 | parser.add_option("--tfidf", action="store_true", dest="apply_tfidf", help="apply TF-IDF term weight to the document-term matrix") 20 | parser.add_option("--norm", action="store_true", dest="apply_norm", help="apply unit length normalization to the document-term matrix") 21 | parser.add_option("--minlen", action="store", type="int", dest="min_doc_length", help="minimum document length (in characters)", default=50) 22 | parser.add_option("-s", action="store", type="string", dest="stoplist_file", help="custom stopword file path", default=None) 23 | parser.add_option('-d','--debug',type="int",help="Level of log output; 0 is less, 5 is all", default=3) 24 | (options, args) = parser.parse_args() 25 | if( len(args) < 1 ): 26 | parser.error( "Must specify at least one directory" ) 27 | log.basicConfig(level=max(50 - (options.debug * 10), 10), format='%(message)s') 28 | 29 | # Find all relevant files in directories specified by user 30 | filepaths = [] 31 | args.sort() 32 | for in_path in args: 33 | if os.path.isdir( in_path ): 34 | log.info( "Searching %s for documents ..." % in_path ) 35 | for fpath in text.util.find_documents( in_path ): 36 | filepaths.append( fpath ) 37 | else: 38 | if in_path.startswith(".") or in_path.startswith("_"): 39 | continue 40 | filepaths.append( in_path ) 41 | log.info( "Found %d documents to parse" % len(filepaths) ) 42 | 43 | # Read the documents 44 | log.info( "Reading documents ..." ) 45 | docs = [] 46 | short_documents = 0 47 | doc_ids = [] 48 | label_count = {} 49 | classes = {} 50 | for filepath in filepaths: 51 | # create the document ID 52 | label = os.path.basename( os.path.dirname( filepath ).replace(" ", "_") ) 53 | doc_id = os.path.splitext( os.path.basename( filepath ) )[0] 54 | if not doc_id.startswith(label): 55 | doc_id = "%s_%s" % ( label, doc_id ) 56 | # read body text 57 | log.debug( "Reading text from %s ..." % filepath ) 58 | body = text.util.read_text( filepath ) 59 | if len(body) < options.min_doc_length: 60 | short_documents += 1 61 | continue 62 | docs.append(body) 63 | doc_ids.append(doc_id) 64 | if label not in classes: 65 | classes[label] = set() 66 | label_count[label] = 0 67 | classes[label].add(doc_id) 68 | label_count[label] += 1 69 | log.info( "Kept %d documents. Skipped %d documents with length < %d" % ( len(docs), short_documents, options.min_doc_length ) ) 70 | if len(classes) < 2: 71 | log.warning( "No ground truth available" ) 72 | classes = None 73 | else: 74 | log.info( "Ground truth: %d classes - %s" % ( len(classes), label_count ) ) 75 | 76 | # Convert the documents in TF-IDF vectors and filter stopwords 77 | if options.stoplist_file is None: 78 | stopwords = text.util.load_stopwords("text/stopwords.txt") 79 | elif options.stoplist_file.lower() == "none": 80 | log.info("Using no stopwords") 81 | stopwords = set() 82 | else: 83 | log.info( "Using custom stopwords from %s" % options.stoplist_file ) 84 | stopwords = text.util.load_stopwords(options.stoplist_file) 85 | log.info( "Pre-processing data (%d stopwords, tfidf=%s, normalize=%s, min_df=%d) ..." % (len(stopwords), options.apply_tfidf, options.apply_norm, options.min_df) ) 86 | (X,terms) = text.util.preprocess( docs, stopwords, min_df = options.min_df, apply_tfidf = options.apply_tfidf, apply_norm = options.apply_norm ) 87 | log.info( "Built document-term matrix: %d documents, %d terms" % (X.shape[0], X.shape[1]) ) 88 | 89 | # Store the corpus 90 | prefix = options.prefix 91 | if prefix is None: 92 | prefix = "corpus" 93 | log.info( "Saving corpus '%s'" % prefix ) 94 | text.util.save_corpus( prefix, X, terms, doc_ids, classes ) 95 | 96 | # -------------------------------------------------------------- 97 | 98 | if __name__ == "__main__": 99 | main() 100 | -------------------------------------------------------------------------------- /eval-partition-accuracy.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | """ 3 | Apply various external validation measures to evaluate the accuracy of the partition 4 | resulting from a topic model (i.e. single membership assignments), relative to a set of ground truth classes. 5 | 6 | Sample usage: 7 | python eval-partition-accuracy.py sample.pkl models/base/*partition*.pkl 8 | """ 9 | import os, os.path, sys 10 | import logging as log 11 | from optparse import OptionParser 12 | from prettytable import PrettyTable 13 | import numpy as np 14 | from sklearn.metrics.cluster import normalized_mutual_info_score, adjusted_mutual_info_score, adjusted_rand_score 15 | import text.util, unsupervised.util 16 | 17 | # -------------------------------------------------------------- 18 | 19 | def validate( measure, classes, clustering ): 20 | if measure == "nmi": 21 | return normalized_mutual_info_score( classes, clustering ) 22 | elif measure == "ami": 23 | return adjusted_mutual_info_score( classes, clustering ) 24 | elif measure == "ari": 25 | return adjusted_rand_score( classes, clustering ) 26 | log.error("Unknown validation measure: %s" % measure ) 27 | return None 28 | 29 | # -------------------------------------------------------------- 30 | 31 | def main(): 32 | parser = OptionParser(usage="usage: %prog [options] corpus_file partition_file1|directory1 ...") 33 | parser.add_option("-s", "--summmary", action="store_true", dest="summary", help="display summary results only") 34 | parser.add_option("-o","--output", action="store", type="string", dest="out_path", help="path for CSV output file", default=None) 35 | parser.add_option("-m", "--measures", action="store_true", dest="measures", help="comma-separated list of validation measures to use (default is nmi)", default="nmi" ) 36 | # Parse command line arguments 37 | (options, args) = parser.parse_args() 38 | if( len(args) < 2 ): 39 | parser.error( "Must specify at least a corpus and one or more partitions/directories" ) 40 | log.basicConfig(level=20, format='%(message)s') 41 | measures = [ x.strip() for x in options.measures.lower().split(",") ] 42 | 43 | log.info ("Reading corpus from %s ..." % args[0] ) 44 | # Load the cached corpus 45 | (X,terms,doc_ids,classes) = text.util.load_corpus( args[0] ) 46 | if classes is None: 47 | log.error( "Error: No class information available for this corpus") 48 | sys.exit(1) 49 | 50 | # Convert a map to a list of class indices 51 | classes_partition = unsupervised.util.clustermap_to_partition( classes, doc_ids ) 52 | 53 | # Get list of all specified partition files 54 | file_paths = [] 55 | for path in args[1:]: 56 | if not os.path.exists( path ): 57 | log.error("No such file or directory: %s" % path ) 58 | sys.exit(1) 59 | if os.path.isdir(path): 60 | log.debug("Searching %s for partitions" % path ) 61 | for dir_path, dirs, files in os.walk(path): 62 | for fname in files: 63 | if fname.startswith("partition") and fname.endswith(".pkl"): 64 | file_paths.append( os.path.join( dir_path, fname ) ) 65 | else: 66 | file_paths.append( path ) 67 | file_paths.sort() 68 | 69 | if len(file_paths) == 0: 70 | log.error("No partition files found to validate") 71 | sys.exit(1) 72 | log.info("Processing partitions for %d base topic models ..." % len(file_paths) ) 73 | 74 | header = ["model"] 75 | for measure in measures: 76 | header.append(measure) 77 | tab = PrettyTable(header) 78 | tab.align["model"] = "l" 79 | 80 | scores = {} 81 | for measure in measures: 82 | scores[measure] = [] 83 | 84 | for file_path in file_paths: 85 | log.debug( "Loading partition from %s" % file_path ) 86 | partition,cluster_doc_ids = unsupervised.util.load_partition( file_path ) 87 | k = max(partition) + 1 88 | # does the number of documents match up? 89 | if len(doc_ids) != len(cluster_doc_ids): 90 | log.warning("Error: Cannot compare clusterings on different data") 91 | continue 92 | # perform validation 93 | row = [file_path] 94 | for measure in measures: 95 | score = validate(measure,classes_partition,partition) 96 | scores[measure].append(score) 97 | row.append( "%.3f" % score ) 98 | if not options.summary: 99 | tab.add_row(row) 100 | 101 | # display an overall summary? 102 | if options.summary or len(file_paths) > 1: 103 | # add mean 104 | row = ["mean"] 105 | for measure in measures: 106 | # convert to a NP array 107 | scores[measure] = np.array(scores[measure]) 108 | row.append( "%.3f" % scores[measure].mean() ) 109 | tab.add_row(row) 110 | row = ["median"] 111 | for measure in measures: 112 | row.append( "%.3f" % np.median(scores[measure]) ) 113 | tab.add_row(row) 114 | # add standard deviation 115 | row = ["sdev"] 116 | for measure in measures: 117 | row.append( "%.3f" % scores[measure].std() ) 118 | tab.add_row(row) 119 | # add range 120 | row = ["min"] 121 | for measure in measures: 122 | row.append( "%.3f" % scores[measure].min() ) 123 | tab.add_row(row) 124 | row = ["max"] 125 | for measure in measures: 126 | row.append( "%.3f" % scores[measure].max() ) 127 | tab.add_row(row) 128 | log.info( tab ) 129 | 130 | # Write to CSV? 131 | if not options.out_path is None: 132 | log.info("Writing summary of results to %s" % options.out_path) 133 | unsupervised.util.write_table( options.out_path, tab ) 134 | 135 | # -------------------------------------------------------------- 136 | 137 | if __name__ == "__main__": 138 | main() 139 | -------------------------------------------------------------------------------- /generate-kfold.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | """ 3 | Applies a K-Fold strategy with NNDSVD-initialized NMF to the specified dataset to generate an ensemble. 4 | 5 | Sample usage: 6 | python generate-kfold.py sample.pkl -k 4 -r 5 -f 10 --maxiters 100 -o models/base 7 | """ 8 | import os, sys, random 9 | import logging as log 10 | from optparse import OptionParser 11 | import numpy as np 12 | import scipy.sparse 13 | import text.util, unsupervised.nmf, unsupervised.rankings, unsupervised.util 14 | 15 | # -------------------------------------------------------------- 16 | 17 | def main(): 18 | parser = OptionParser(usage="usage: %prog [options] dataset_file") 19 | parser.add_option("--seed", action="store", type="int", dest="seed", help="initial random seed", default=1000) 20 | parser.add_option("-r","--runs", action="store", type="int", dest="runs", help="number of runs", default=1) 21 | parser.add_option("-f","--folds", action="store", type="int", dest="num_folds", help="number of folds", default=10) 22 | parser.add_option("-k", action="store", type="int", dest="k", help="number of topics", default=5) 23 | parser.add_option("--maxiters", action="store", type="int", dest="maxiter", help="maximum number of iterations", default=100) 24 | parser.add_option("-s", "--sample", action="store", type="float", dest="sample_ratio", help="sampling ratio of documents to include in each run (range is 0 to 1). default is all", default=1.0) 25 | parser.add_option("-o","--outdir", action="store", type="string", dest="dir_out", help="base output directory (default is current directory)", default=None) 26 | parser.add_option('-d','--debug',type="int",help="Level of log output; 0 is less, 5 is all", default=3) 27 | (options, args) = parser.parse_args() 28 | if len(args) < 1: 29 | parser.error( "Must specify at least one corpus file" ) 30 | log_level = max(50 - (options.debug * 10), 10) 31 | log.basicConfig(level=log_level, format='%(asctime)-18s %(levelname)-10s %(message)s', datefmt='%d/%m/%Y %H:%M',) 32 | 33 | if options.dir_out is None: 34 | dir_out_base = os.getcwd() 35 | else: 36 | dir_out_base = options.dir_out 37 | if not os.path.exists(dir_out_base): 38 | os.makedirs(dir_out_base) 39 | 40 | # Set random state 41 | random_seed = options.seed 42 | if random_seed < 0: 43 | random_seed = random.randint(1,100000) 44 | np.random.seed( random_seed ) 45 | random.seed( random_seed ) 46 | log.info("Using random seed %s" % random_seed ) 47 | 48 | # Load the cached corpus 49 | corpus_path = args[0] 50 | (X,terms,doc_ids,classes) = text.util.load_corpus( corpus_path ) 51 | log.debug( "Read %s document-term matrix, dictionary of %d terms, list of %d document IDs" % ( str(X.shape), len(terms), len(doc_ids) ) ) 52 | 53 | impl = unsupervised.nmf.SklNMF( max_iters = options.maxiter, init_strategy = "nndsvd" ) 54 | n_documents = X.shape[0] 55 | n_folds = options.num_folds 56 | fold_sizes = (n_documents // n_folds) * np.ones(n_folds, dtype=np.int) 57 | fold_sizes[:n_documents % n_folds] += 1 58 | 59 | log.debug( "Results will be written to %s" % dir_out_base ) 60 | for run in range(options.runs): 61 | log.info("Run %d/%d" % ( (run+1), options.runs ) ) 62 | idxs = np.arange(n_documents) 63 | np.random.shuffle( idxs ) 64 | 65 | current = 0 66 | for fold, fold_size in enumerate(fold_sizes): 67 | file_suffix = "%s_%02d_%02d" % ( options.seed, run+1, fold+1 ) 68 | start, stop = current, current + fold_size 69 | current = stop 70 | sample_idxs = list(idxs) 71 | for idx in idxs[start:stop]: 72 | sample_idxs.remove(idx) 73 | sample_doc_ids = [] 74 | for doc_index in sample_idxs: 75 | sample_doc_ids.append( doc_ids[doc_index] ) 76 | log.info("Fold %d/%d: Using fold with %d/%d documents" % ( fold+1, n_folds, len(sample_idxs), n_documents ) ) 77 | S = X[sample_idxs,:] 78 | log.debug("Creating sparse matrix ...") 79 | S = scipy.sparse.csr_matrix(S) 80 | 81 | # apply NMF 82 | log.info("Applying NMF (k=%d) to matrix of size %d X %d ..." % ( options.k, S.shape[0], S.shape[1] ) ) 83 | impl.apply( S, options.k ) 84 | # Get term rankings for each topic 85 | term_rankings = [] 86 | for topic_index in range(options.k): 87 | ranked_term_indices = impl.rank_terms( topic_index ) 88 | term_ranking = [terms[i] for i in ranked_term_indices] 89 | term_rankings.append(term_ranking) 90 | log.debug( "Generated ranking set with %d topics covering up to %d terms" % ( len(term_rankings), unsupervised.rankings.term_rankings_size( term_rankings ) ) ) 91 | # Write term rankings 92 | ranks_out_path = os.path.join( dir_out_base, "ranks_%s.pkl" % file_suffix ) 93 | log.debug( "Writing term ranking set to %s" % ranks_out_path ) 94 | unsupervised.util.save_term_rankings( ranks_out_path, term_rankings ) 95 | # Write document partition 96 | partition = impl.generate_partition() 97 | partition_out_path = os.path.join( dir_out_base, "partition_%s.pkl" % file_suffix ) 98 | log.debug( "Writing document partition to %s" % partition_out_path ) 99 | unsupervised.util.save_partition( partition_out_path, partition, sample_doc_ids ) 100 | # Write the complete factorization 101 | factor_out_path = os.path.join( dir_out_base, "factors_%s.pkl" % file_suffix ) 102 | # NB: need to make a copy of the factors 103 | log.debug( "Writing factorization for %d documents to %s" % ( len(sample_doc_ids), factor_out_path ) ) 104 | unsupervised.util.save_nmf_factors( factor_out_path, np.array( impl.W ), np.array( impl.H ), sample_doc_ids, terms ) 105 | 106 | # -------------------------------------------------------------- 107 | 108 | if __name__ == "__main__": 109 | main() 110 | -------------------------------------------------------------------------------- /generate-nmf.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | """ 3 | Applies randomly-initialized NMF to the specified dataset to generate an ensemble. 4 | 5 | Sample usage: 6 | python generate-nmf.py sample.pkl -k 4 -r 20 --maxiters 100 -o models/base 7 | """ 8 | import os, sys, random 9 | import logging as log 10 | from optparse import OptionParser 11 | import numpy as np 12 | import scipy.sparse 13 | import text.util, unsupervised.nmf, unsupervised.rankings, unsupervised.util 14 | 15 | # -------------------------------------------------------------- 16 | 17 | def main(): 18 | parser = OptionParser(usage="usage: %prog [options] dataset_file") 19 | parser.add_option("--seed", action="store", type="int", dest="seed", help="initial random seed", default=1000) 20 | parser.add_option("-k", action="store", type="int", dest="k", help="number of topics", default=5) 21 | parser.add_option("-r","--runs", action="store", type="int", dest="runs", help="number of runs", default=1) 22 | parser.add_option("--maxiters", action="store", type="int", dest="maxiter", help="maximum number of iterations", default=100) 23 | parser.add_option("-s", "--sample", action="store", type="float", dest="sample_ratio", help="sampling ratio of documents to include in each run (range is 0 to 1). default is all", default=1.0) 24 | parser.add_option("--nndsvd", action="store_true", dest="use_nndsvd", help="use nndsvd initialization instead of random") 25 | parser.add_option("-o","--outdir", action="store", type="string", dest="dir_out", help="base output directory (default is current directory)", default=None) 26 | parser.add_option('-d','--debug',type="int",help="Level of log output; 0 is less, 5 is all", default=3) 27 | (options, args) = parser.parse_args() 28 | if len(args) < 1: 29 | parser.error( "Must specify at least one corpus file" ) 30 | log_level = max(50 - (options.debug * 10), 10) 31 | log.basicConfig(level=log_level, format='%(message)s') 32 | 33 | if options.dir_out is None: 34 | dir_out_base = os.getcwd() 35 | else: 36 | dir_out_base = options.dir_out 37 | if not os.path.exists(dir_out_base): 38 | os.makedirs(dir_out_base) 39 | 40 | # Set random state 41 | random_seed = options.seed 42 | if random_seed < 0: 43 | random_seed = random.randint(1,100000) 44 | np.random.seed( random_seed ) 45 | random.seed( random_seed ) 46 | log.info("Using random seed %s" % random_seed ) 47 | 48 | # Load the cached corpus 49 | corpus_path = args[0] 50 | (X,terms,doc_ids,classes) = text.util.load_corpus( corpus_path ) 51 | log.debug( "Read %s document-term matrix, dictionary of %d terms, list of %d document IDs" % ( str(X.shape), len(terms), len(doc_ids) ) ) 52 | 53 | # Choose implementation 54 | if options.use_nndsvd: 55 | init_strategy = "nndsvd" 56 | else: 57 | init_strategy = "random" 58 | impl = unsupervised.nmf.SklNMF( max_iters = options.maxiter, init_strategy = init_strategy ) 59 | 60 | n_documents = X.shape[0] 61 | n_sample = int( options.sample_ratio * n_documents ) 62 | indices = np.arange(n_documents) 63 | 64 | log.info( "Applying NMF (k=%d, runs=%d, seed=%s, init_strategy=%s) ..." % ( options.k, options.runs, options.seed, init_strategy ) ) 65 | if options.sample_ratio < 1: 66 | log.info( "Sampling ratio = %.2f - %d/%d documents per run" % ( options.sample_ratio, n_sample, n_documents ) ) 67 | log.debug( "Results will be written to %s" % dir_out_base ) 68 | # Run NMF 69 | for r in range(options.runs): 70 | log.info( "NMF run %d/%d (k=%d, max_iters=%d)" % (r+1, options.runs, options.k, options.maxiter ) ) 71 | file_suffix = "%s_%03d" % ( options.seed, r+1 ) 72 | # randomly sub-sample the data 73 | if options.sample_ratio < 1: 74 | log.info("Subsamping the data ...") 75 | np.random.shuffle(indices) 76 | sample_indices = indices[0:n_sample] 77 | S = X[sample_indices,:] 78 | log.info("Creating sparse matrix ...") 79 | S = scipy.sparse.csr_matrix(S) 80 | sample_doc_ids = [] 81 | for doc_index in sample_indices: 82 | sample_doc_ids.append( doc_ids[doc_index] ) 83 | else: 84 | S = X 85 | sample_doc_ids = doc_ids 86 | # apply NMF 87 | log.info("Applying NMF to matrix of size %d X %d ..." % ( S.shape[0], S.shape[1] ) ) 88 | impl.apply( S, options.k ) 89 | log.debug("Generated factors: W %s, H %s" % ( impl.W.shape, impl.H.shape ) ) 90 | # Get term rankings for each topic 91 | term_rankings = [] 92 | for topic_index in range(options.k): 93 | ranked_term_indices = impl.rank_terms( topic_index ) 94 | term_ranking = [terms[i] for i in ranked_term_indices] 95 | term_rankings.append(term_ranking) 96 | log.debug( "Generated ranking set with %d topics covering up to %d terms" % ( len(term_rankings), unsupervised.rankings.term_rankings_size( term_rankings ) ) ) 97 | # Write term rankings 98 | ranks_out_path = os.path.join( dir_out_base, "ranks_%s.pkl" % file_suffix ) 99 | log.debug( "Writing term ranking set to %s" % ranks_out_path ) 100 | unsupervised.util.save_term_rankings( ranks_out_path, term_rankings ) 101 | # Write document partition 102 | partition = impl.generate_partition() 103 | partition_out_path = os.path.join( dir_out_base, "partition_%s.pkl" % file_suffix ) 104 | log.debug( "Writing document partition to %s" % partition_out_path ) 105 | unsupervised.util.save_partition( partition_out_path, partition, sample_doc_ids ) 106 | # Write the complete factorization 107 | factor_out_path = os.path.join( dir_out_base, "factors_%s.pkl" % file_suffix ) 108 | # NB: need to make a copy of the factors 109 | log.debug( "Writing factorization for %d documents to %s" % ( len(sample_doc_ids), factor_out_path ) ) 110 | unsupervised.util.save_nmf_factors( factor_out_path, np.array( impl.W ), np.array( impl.H ), sample_doc_ids, terms ) 111 | 112 | log.info("Generated %d ensemble members" % (r+1)) 113 | 114 | # -------------------------------------------------------------- 115 | 116 | if __name__ == "__main__": 117 | main() 118 | -------------------------------------------------------------------------------- /combine-nmf.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | """ 3 | Tool to combine a collection of base topic models, generated by NMF, to produce a single ensemble topic model. 4 | 5 | Sample usage: 6 | python combine-nmf.py sample.pkl models/base/*factors*.pkl -k 4 -o models/ensemble 7 | """ 8 | import os, sys, random, operator 9 | import logging as log 10 | from optparse import OptionParser 11 | import numpy as np 12 | import sklearn.preprocessing 13 | import unsupervised.nmf, unsupervised.rankings, unsupervised.util 14 | import text.util 15 | 16 | # -------------------------------------------------------------- 17 | 18 | def main(): 19 | parser = OptionParser(usage="usage: %prog [options] corpus_file base_factors1 base_factors2...") 20 | parser.add_option("--seed", action="store", type="int", dest="seed", help="initial random seed", default=1000) 21 | parser.add_option("-k", action="store", type="string", dest="k", help="number of topics", default=10) 22 | parser.add_option("--maxiters", action="store", type="int", dest="maxiter", help="maximum number of iterations", default=500) 23 | parser.add_option("-o","--outdir", action="store", type="string", dest="dir_out", help="output directory (default is current directory)", default=None) 24 | parser.add_option("-v", "--verbose", action="store_true", dest="verbose", help="display topic descriptors") 25 | parser.add_option('-d','--debug',type="int",help="Level of log output; 0 is less, 5 is all", default=3) 26 | (options, args) = parser.parse_args() 27 | if( len(args) < 3 ): 28 | parser.error( "Must specify corpus file and at least two base factor files" ) 29 | log_level = max(50 - (options.debug * 10), 10) 30 | log.basicConfig(level=log_level, format='%(message)s') 31 | 32 | # Parse user-specified range for number of topics K 33 | k = int(options.k) 34 | # Output directory for results 35 | if options.dir_out is None: 36 | dir_out = os.getcwd() 37 | else: 38 | dir_out = options.dir_out 39 | if not os.path.exists(dir_out): 40 | os.makedirs(dir_out) 41 | 42 | # Set random state 43 | random_seed = options.seed 44 | if random_seed < 0: 45 | random_seed = random.randint(1,100000) 46 | np.random.seed( random_seed ) 47 | random.seed( random_seed ) 48 | log.info("Using random seed %s" % random_seed ) 49 | 50 | # Load the cached corpus 51 | log.info( "Loading data from %s ..." % args[0] ) 52 | (X,all_terms,all_doc_ids,classes) = text.util.load_corpus( args[0] ) 53 | log.info( "Read corpus with %d documents, %d terms" % ( len(all_doc_ids), len(all_terms) ) ) 54 | 55 | # Process each specified base topic model 56 | log.info("Processing %d base topic models ..." % len(args[1:]) ) 57 | factors = [] 58 | for base_idx, base_model_path in enumerate(args[1:]): 59 | # load the cached base topics 60 | base_name = os.path.splitext( os.path.split( base_model_path )[-1] )[0] 61 | (base_W,base_H,base_doc_ids,base_terms) = unsupervised.util.load_nmf_factors( base_model_path ) 62 | base_k = base_W.shape[1] 63 | log.debug("Base model %d: Read %d base topics from %s" % (base_idx + 1, base_k, base_model_path) ) 64 | # label the topics 65 | base_topic_labels = [] 66 | for i in range(base_k): 67 | base_topic_labels.append( "%03d-%02d" % ( base_idx+1, i+1 ) ) 68 | # add it to the ensemble collection 69 | factors.append( base_H ) 70 | 71 | # Merge the H factors to create the topic-term matrix 72 | M = np.vstack( factors ) 73 | log.info( "Created topic-term matrix of size %dx%d" % M.shape ) 74 | log.debug( "Matrix statistics: range=[%.2f,%.2f] mean=%.2f" % ( np.min(M), np.max(M), np.mean(M) ) ) 75 | 76 | # NMF implementation 77 | impl = unsupervised.nmf.SklNMF( max_iters = options.maxiter, init_strategy = "nndsvd" ) 78 | log.info( "Applying ensemble combination to topic-term matrix for k=%d topics ..." % k ) 79 | impl.apply( M, k ) 80 | ensemble_H = np.array( impl.H ) 81 | ensemble_W = np.array( impl.W ) 82 | log.debug( "Generated %dx%d factor W and %dx%d factor H" % ( ensemble_W.shape[0], ensemble_W.shape[1], ensemble_H.shape[0], ensemble_H.shape[1] ) ) 83 | # Create term rankings for each topic 84 | term_rankings = [] 85 | for topic_index in range(k): 86 | ranked_term_indices = impl.rank_terms( topic_index ) 87 | term_ranking = [all_terms[i] for i in ranked_term_indices] 88 | term_rankings.append(term_ranking) 89 | 90 | # Print out the top terms? 91 | if options.verbose: 92 | log.info( unsupervised.rankings.format_term_rankings( term_rankings, top = 10 ) ) 93 | 94 | # Write term rankings 95 | ranks_out_path = os.path.join( dir_out, "ranks_ensemble_k%02d.pkl" % k ) 96 | log.info( "Writing ensemble term ranking set to %s" % ranks_out_path ) 97 | unsupervised.util.save_term_rankings( ranks_out_path, term_rankings ) 98 | 99 | # Write the complete factorization 100 | factor_out_path = os.path.join( dir_out, "factors_ensemble_k%02d.pkl" % k ) 101 | log.info( "Writing complete ensemble factorization to %s" % factor_out_path ) 102 | unsupervised.util.save_nmf_factors( factor_out_path, ensemble_W, ensemble_H, all_doc_ids, all_terms ) 103 | 104 | # Now finally fold in the documents to assign them to topics 105 | HT = sklearn.preprocessing.normalize( ensemble_H.T, "l2", axis=0 ) 106 | D = X.dot(HT) 107 | 108 | # Create a disjoint partition for the documents 109 | doc_partition = np.argmax( D, axis = 1 ).flatten().tolist() 110 | 111 | # Now write the results 112 | doc_factor_out_path = os.path.join( dir_out, "factors_final_k%02d.pkl" % k ) 113 | log.info( "Writing ensemble factorization to %s" % doc_factor_out_path ) 114 | unsupervised.util.save_nmf_factors( doc_factor_out_path, D, ensemble_H, all_doc_ids, all_terms ) 115 | 116 | # Write document partition 117 | doc_partition_out_path = os.path.join( dir_out, "partition_final_k%02d.pkl" % k ) 118 | log.info( "Writing ensemble document partition to %s" % doc_partition_out_path ) 119 | unsupervised.util.save_partition( doc_partition_out_path, doc_partition, all_doc_ids ) 120 | 121 | # -------------------------------------------------------------- 122 | 123 | if __name__ == "__main__": 124 | main() 125 | -------------------------------------------------------------------------------- /text/util.py: -------------------------------------------------------------------------------- 1 | import codecs, os, os.path, re 2 | from sklearn.externals import joblib 3 | from sklearn.feature_extraction.text import TfidfVectorizer 4 | 5 | # -------------------------------------------------------------- 6 | 7 | def preprocess( docs, stopwords, min_df = 3, min_term_length = 2, ngram_range = (1,1), apply_tfidf = True, apply_norm = True, lemmatize = False ): 8 | """ 9 | Preprocess a list containing text documents stored as strings. 10 | """ 11 | token_pattern = re.compile(r"\b\w\w+\b", re.U) 12 | 13 | if lemmatize: 14 | from nltk.stem import WordNetLemmatizer 15 | wnl = WordNetLemmatizer() 16 | 17 | def normalize( x ): 18 | x = x.lower() 19 | if lemmatize: 20 | return wnl.lemmatize(x) 21 | return x 22 | 23 | def custom_tokenizer( s ): 24 | return [normalize(x) for x in token_pattern.findall(s) if (len(x) >= min_term_length and x[0].isalpha() ) ] 25 | 26 | # Build the Vector Space Model, apply TF-IDF and normalize lines to unit length all in one call 27 | if apply_norm: 28 | norm_function = "l2" 29 | else: 30 | norm_function = None 31 | tfidf = TfidfVectorizer(stop_words=stopwords, lowercase=True, strip_accents="unicode", tokenizer=custom_tokenizer, use_idf=apply_tfidf, norm=norm_function, min_df = min_df, ngram_range = ngram_range) 32 | X = tfidf.fit_transform(docs) 33 | terms = [] 34 | # store the vocabulary map 35 | v = tfidf.vocabulary_ 36 | for i in range(len(v)): 37 | terms.append("") 38 | for term in v.keys(): 39 | terms[ v[term] ] = term 40 | return (X,terms) 41 | 42 | def preprocess_simple( docs, stopwords, min_df = 3, min_term_length = 2, ngram_range = (1,1), apply_tfidf = True, apply_norm = True ): 43 | """ 44 | Preprocess a list containing text documents stored as strings, where the documents have already been tokenized and are separated by whitespace 45 | """ 46 | token_pattern = re.compile(r"[\s\-]+", re.U) 47 | 48 | def custom_tokenizer( s ): 49 | return [x.lower() for x in token_pattern.split(s) if (len(x) >= min_term_length) ] 50 | 51 | # Build the Vector Space Model, apply TF-IDF and normalize lines to unit length all in one call 52 | if apply_norm: 53 | norm_function = "l2" 54 | else: 55 | norm_function = None 56 | tfidf = TfidfVectorizer(stop_words=stopwords, lowercase=True, strip_accents="unicode", tokenizer=custom_tokenizer, use_idf=apply_tfidf, norm=norm_function, min_df = min_df, ngram_range = ngram_range) 57 | X = tfidf.fit_transform(docs) 58 | terms = [] 59 | # store the vocabulary map 60 | v = tfidf.vocabulary_ 61 | for i in range(len(v)): 62 | terms.append("") 63 | for term in v.keys(): 64 | terms[ v[term] ] = term 65 | return (X,terms) 66 | 67 | def preprocess_tweets( docs, stopwords, min_df = 3, min_term_length = 2, ngram_range = (1,1), apply_tfidf = True, apply_norm = True): 68 | """ 69 | Preprocess a list containing text documents stored as strings, where the documents have already been tokenized and are separated by whitespace 70 | """ 71 | from nltk.tokenize import TweetTokenizer 72 | tweet_tokenizer = TweetTokenizer(preserve_case = False, strip_handles=True, reduce_len=True) 73 | 74 | def custom_tokenizer( s ): 75 | # need to manually replace quotes 76 | s = s.replace("'"," ").replace('"',' ') 77 | tokens = [] 78 | for x in tweet_tokenizer.tokenize(s): 79 | if len(x) >= min_term_length: 80 | if x[0] == "#" or x[0].isalpha(): 81 | tokens.append( x ) 82 | return tokens 83 | 84 | # Build the Vector Space Model, apply TF-IDF and normalize lines to unit length all in one call 85 | if apply_norm: 86 | norm_function = "l2" 87 | else: 88 | norm_function = None 89 | tfidf = TfidfVectorizer(stop_words=stopwords, lowercase=True, strip_accents="unicode", tokenizer=custom_tokenizer, use_idf=apply_tfidf, norm=norm_function, min_df = min_df, ngram_range = ngram_range) 90 | X = tfidf.fit_transform(docs) 91 | terms = [] 92 | # store the vocabulary map 93 | v = tfidf.vocabulary_ 94 | for i in range(len(v)): 95 | terms.append("") 96 | for term in v.keys(): 97 | terms[ v[term] ] = term 98 | return (X,terms) 99 | 100 | # -------------------------------------------------------------- 101 | 102 | def load_stopwords( inpath = "text/stopwords.txt"): 103 | """ 104 | Load stopwords from a file into a set. 105 | """ 106 | stopwords = set() 107 | with open(inpath) as f: 108 | lines = f.readlines() 109 | for l in lines: 110 | l = l.strip().lower() 111 | if len(l) > 0: 112 | stopwords.add(l) 113 | return stopwords 114 | 115 | def save_corpus( out_prefix, X, terms, doc_ids, classes = None ): 116 | """ 117 | Save a pre-processed scikit-learn corpus and associated metadata using Joblib. 118 | """ 119 | matrix_outpath = "%s.pkl" % out_prefix 120 | joblib.dump((X,terms,doc_ids,classes), matrix_outpath ) 121 | 122 | def load_corpus( in_path ): 123 | """ 124 | Load a pre-processed scikit-learn corpus and associated metadata using Joblib. 125 | """ 126 | (X,terms,doc_ids,classes) = joblib.load( in_path ) 127 | return (X, terms, doc_ids, classes) 128 | 129 | def find_documents( root_path ): 130 | """ 131 | Find all files in the specified directory and its subdirectories, and store them as strings in a list. 132 | """ 133 | filepaths = [] 134 | for dir_path, subFolders, files in os.walk(root_path): 135 | for filename in files: 136 | if filename.startswith(".") or filename.startswith("_"): 137 | continue 138 | filepath = os.path.join(dir_path,filename) 139 | filepaths.append( filepath ) 140 | filepaths.sort() 141 | return filepaths 142 | 143 | def read_text( in_path ): 144 | """ 145 | Read and normalize body text from the specified document file. 146 | """ 147 | http_re = re.compile('https?[:;]?/?/?\S*') 148 | # read the file 149 | f = codecs.open(in_path, 'r', encoding="utf8", errors='ignore') 150 | body = "" 151 | while True: 152 | line = f.readline() 153 | if not line: 154 | break 155 | # Remove URIs at this point (Note: this simple regex captures MOST URIs but may occasionally let others slip through) 156 | normalized_line = re.sub(http_re, '', line.strip()) 157 | if len(normalized_line) > 1: 158 | body += normalized_line 159 | body += "\n" 160 | f.close() 161 | return body 162 | 163 | -------------------------------------------------------------------------------- /unsupervised/rankings.py: -------------------------------------------------------------------------------- 1 | import math, string 2 | import numpy as np 3 | from sklearn.externals import joblib 4 | from prettytable import PrettyTable 5 | import unsupervised.hungarian 6 | 7 | # -------------------------------------------------------------- 8 | # Ranking Similarity 9 | # -------------------------------------------------------------- 10 | 11 | class JaccardBinary: 12 | """ 13 | Simple binary Jaccard-based ranking comparison, which does not take into account rank positions. 14 | """ 15 | def similarity( self, gold_ranking, test_ranking ): 16 | sx = set(gold_ranking) 17 | sy = set(test_ranking) 18 | numer = len( sx.intersection(sy) ) 19 | if numer == 0: 20 | return 0.0 21 | denom = len( sx.union(sy) ) 22 | if denom == 0: 23 | return 0.0 24 | return float(numer)/denom 25 | 26 | def __str__( self ): 27 | return "%s" % ( self.__class__.__name__ ) 28 | 29 | class AverageJaccard(JaccardBinary): 30 | """ 31 | A top-weighted version of Jaccard, which takes into account rank positions. 32 | This is based on Fagin's Average Overlap Intersection Metric. 33 | """ 34 | def similarity( self, gold_ranking, test_ranking ): 35 | k = min( len(gold_ranking), len(test_ranking) ) 36 | total = 0.0 37 | for i in range(1,k+1): 38 | total += JaccardBinary.similarity( self, gold_ranking[0:i], test_ranking[0:i] ) 39 | return total/k 40 | 41 | # -------------------------------------------------------------- 42 | # Ranking Set Agreement 43 | # -------------------------------------------------------------- 44 | 45 | class RankingSetAgreement: 46 | """ 47 | Calculates the agreement between pairs of ranking sets, using a specified measure of 48 | similarity between rankings. 49 | """ 50 | def __init__( self, metric = AverageJaccard() ): 51 | self.metric = metric 52 | 53 | def similarity( self, rankings1, rankings2 ): 54 | """ 55 | Calculate the overall agreement between two different ranking sets. This is given by the 56 | mean similarity values for all matched pairs. 57 | """ 58 | self.results = None 59 | self.S = self.build_matrix( rankings1, rankings2 ) 60 | score, self.results = self.hungarian_matching() 61 | return score 62 | 63 | def build_matrix( self, rankings1, rankings2 ): 64 | """ 65 | Construct the similarity matrix between the pairs of rankings in two 66 | different ranking sets. 67 | """ 68 | rows = len(rankings1) 69 | cols = len(rankings2) 70 | S = np.zeros( (rows,cols) ) 71 | for row in range(rows): 72 | for col in range(cols): 73 | S[row,col] = self.metric.similarity( rankings1[row], rankings2[col] ) 74 | return S 75 | 76 | def hungarian_matching( self ): 77 | """ 78 | Solve the Hungarian matching problem to find the best matches between columns and rows based on 79 | values in the specified similarity matrix. 80 | """ 81 | # apply hungarian matching 82 | h = unsupervised.hungarian.Hungarian() 83 | C = h.make_cost_matrix(self.S) 84 | h.calculate(C) 85 | results = h.get_results() 86 | # compute score based on similarities 87 | score = 0.0 88 | for (row,col) in results: 89 | score += self.S[row,col] 90 | score /= len(results) 91 | return (score, results) 92 | 93 | # -------------------------------------------------------------- 94 | # Utilities 95 | # -------------------------------------------------------------- 96 | 97 | def calc_relevance_scores( n, rel_measure ): 98 | """ 99 | Utility function to compute a sequence of relevance scores using the specified function. 100 | """ 101 | scores = [] 102 | for i in range(n): 103 | scores.append( rel_measure.relevance( i + 1 ) ) 104 | return scores 105 | 106 | def term_rankings_size( term_rankings ): 107 | """ 108 | Return the number of terms covered by a list of multiple term rankings. 109 | """ 110 | m = 0 111 | for ranking in term_rankings: 112 | if m == 0: 113 | m = len(ranking) 114 | else: 115 | m = min( len(ranking), m ) 116 | return m 117 | 118 | def truncate_term_rankings( orig_rankings, top ): 119 | """ 120 | Truncate a list of multiple term rankings to the specified length. 121 | """ 122 | if top < 1: 123 | return orig_rankings 124 | trunc_rankings = [] 125 | for ranking in orig_rankings: 126 | trunc_rankings.append( ranking[0:min(len(ranking),top)] ) 127 | return trunc_rankings 128 | 129 | def format_term_rankings( term_rankings, labels = None, top = 10 ): 130 | """ 131 | Format a list of multiple term rankings using PrettyTable. 132 | """ 133 | from prettytable import PrettyTable 134 | # add header 135 | header = ["Rank"] 136 | if labels is None: 137 | for i in range( len(term_rankings) ): 138 | header.append("C%02d" % (i+1) ) 139 | else: 140 | for label in labels: 141 | header.append(label) 142 | tab = PrettyTable(header) 143 | for field in header: 144 | tab.align[field] = "l" 145 | # add body 146 | for pos in range(top): 147 | row = [ str(pos+1) ] 148 | for ranking in term_rankings: 149 | # have we run out of terms? 150 | if len(ranking) <= pos: 151 | row.append( "" ) 152 | else: 153 | row.append( ranking[pos] ) 154 | tab.add_row( row ) 155 | return tab 156 | 157 | def format_term_rankings_long( term_rankings, labels = None, top = 10 ): 158 | """ 159 | Format a list of multiple term rankings using lists. 160 | """ 161 | if labels is None: 162 | labels = [] 163 | for i in range( len(term_rankings) ): 164 | labels.append("C%02d" % (i+1) ) 165 | max_label_len = 0 166 | for label in labels: 167 | max_label_len = max(max_label_len,len(label)) 168 | max_label_len += 1 169 | 170 | s = "" 171 | for i, label in enumerate(labels): 172 | s += label.ljust(max_label_len) 173 | s += ": " 174 | sterms = "" 175 | for term in term_rankings[i][0:top]: 176 | if len(sterms) > 0: 177 | sterms += ", " 178 | sterms += term 179 | s += sterms + "\n" 180 | return s 181 | 182 | # -------------------------------------------------------------- 183 | 184 | def save_term_rankings( out_path, term_rankings, labels = None ): 185 | """ 186 | Save a list of multiple term rankings using Joblib. 187 | """ 188 | # no labels? generate some standard ones 189 | if labels is None: 190 | labels = [] 191 | for i in range( len(term_rankings) ): 192 | labels.append( "C%02d" % (i+1) ) 193 | joblib.dump((term_rankings,labels), out_path ) 194 | 195 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /unsupervised/hungarian.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | """ 3 | Implementation of the Hungarian (Munkres) Algorithm using Python and NumPy 4 | References: http://www.ams.jhu.edu/~castello/362/Handouts/hungarian.pdf 5 | http://weber.ucsd.edu/~vcrawfor/hungar.pdf 6 | http://en.wikipedia.org/wiki/Hungarian_algorithm 7 | http://www.public.iastate.edu/~ddoty/HungarianAlgorithm.html 8 | http://www.clapper.org/software/python/munkres/ 9 | """ 10 | 11 | # Module Information. 12 | __version__ = "1.1.1" 13 | __author__ = "Thom Dedecko" 14 | __url__ = "http://github.com/tdedecko/hungarian-algorithm" 15 | __copyright__ = "(c) 2010 Thom Dedecko" 16 | __license__ = "MIT License" 17 | 18 | 19 | class HungarianError(Exception): 20 | pass 21 | 22 | # Import numpy. Error if fails 23 | try: 24 | import numpy as np 25 | except ImportError: 26 | raise HungarianError("NumPy is not installed.") 27 | 28 | 29 | class Hungarian: 30 | """ 31 | Implementation of the Hungarian (Munkres) Algorithm using np. 32 | 33 | Usage: 34 | hungarian = Hungarian(cost_matrix) 35 | hungarian.calculate() 36 | or 37 | hungarian = Hungarian() 38 | hungarian.calculate(cost_matrix) 39 | 40 | Handle Profit matrix: 41 | hungarian = Hungarian(profit_matrix, is_profit_matrix=True) 42 | or 43 | cost_matrix = Hungarian.make_cost_matrix(profit_matrix) 44 | 45 | The matrix will be automatically padded if it is not square. 46 | For that numpy's resize function is used, which automatically adds 0's to any row/column that is added 47 | 48 | Get results and total potential after calculation: 49 | hungarian.get_results() 50 | hungarian.get_total_potential() 51 | """ 52 | 53 | def __init__(self, input_matrix=None, is_profit_matrix=False): 54 | """ 55 | input_matrix is a List of Lists. 56 | input_matrix is assumed to be a cost matrix unless is_profit_matrix is True. 57 | """ 58 | if input_matrix is not None: 59 | # Save input 60 | my_matrix = np.array(input_matrix) 61 | self._input_matrix = np.array(input_matrix) 62 | self._maxColumn = my_matrix.shape[1] 63 | self._maxRow = my_matrix.shape[0] 64 | 65 | # Adds 0s if any columns/rows are added. Otherwise stays unaltered 66 | matrix_size = max(self._maxColumn, self._maxRow) 67 | my_matrix.resize(matrix_size, matrix_size) 68 | 69 | # Convert matrix to profit matrix if necessary 70 | if is_profit_matrix: 71 | my_matrix = self.make_cost_matrix(my_matrix) 72 | 73 | self._cost_matrix = my_matrix 74 | self._size = len(my_matrix) 75 | self._shape = my_matrix.shape 76 | 77 | # Results from algorithm. 78 | self._results = [] 79 | self._totalPotential = 0 80 | else: 81 | self._cost_matrix = None 82 | 83 | def get_results(self): 84 | """Get results after calculation.""" 85 | return self._results 86 | 87 | def get_total_potential(self): 88 | """Returns expected value after calculation.""" 89 | return self._totalPotential 90 | 91 | def calculate(self, input_matrix=None, is_profit_matrix=False): 92 | """ 93 | Implementation of the Hungarian (Munkres) Algorithm. 94 | 95 | input_matrix is a List of Lists. 96 | input_matrix is assumed to be a cost matrix unless is_profit_matrix is True. 97 | """ 98 | # Handle invalid and new matrix inputs. 99 | if input_matrix is None and self._cost_matrix is None: 100 | raise HungarianError("Invalid input") 101 | elif input_matrix is not None: 102 | self.__init__(input_matrix, is_profit_matrix) 103 | 104 | result_matrix = self._cost_matrix.copy() 105 | 106 | # Step 1: Subtract row mins from each row. 107 | for index, row in enumerate(result_matrix): 108 | result_matrix[index] -= row.min() 109 | 110 | # Step 2: Subtract column mins from each column. 111 | for index, column in enumerate(result_matrix.T): 112 | result_matrix[:, index] -= column.min() 113 | 114 | # Step 3: Use minimum number of lines to cover all zeros in the matrix. 115 | # If the total covered rows+columns is not equal to the matrix size then adjust matrix and repeat. 116 | total_covered = 0 117 | while total_covered < self._size: 118 | # Find minimum number of lines to cover all zeros in the matrix and find total covered rows and columns. 119 | cover_zeros = CoverZeros(result_matrix) 120 | covered_rows = cover_zeros.get_covered_rows() 121 | covered_columns = cover_zeros.get_covered_columns() 122 | total_covered = len(covered_rows) + len(covered_columns) 123 | 124 | # if the total covered rows+columns is not equal to the matrix size then adjust it by min uncovered num (m). 125 | if total_covered < self._size: 126 | result_matrix = self._adjust_matrix_by_min_uncovered_num(result_matrix, covered_rows, covered_columns) 127 | 128 | # Step 4: Starting with the top row, work your way downwards as you make assignments. 129 | # Find single zeros in rows or columns. 130 | # Add them to final result and remove them and their associated row/column from the matrix. 131 | expected_results = min(self._maxColumn, self._maxRow) 132 | zero_locations = (result_matrix == 0) 133 | while len(self._results) != expected_results: 134 | 135 | # If number of zeros in the matrix is zero before finding all the results then an error has occurred. 136 | if not zero_locations.any(): 137 | raise HungarianError("Unable to find results. Algorithm has failed.") 138 | 139 | # Find results and mark rows and columns for deletion 140 | matched_rows, matched_columns = self.__find_matches(zero_locations) 141 | 142 | # Make arbitrary selection 143 | total_matched = len(matched_rows) + len(matched_columns) 144 | if total_matched == 0: 145 | matched_rows, matched_columns = self.select_arbitrary_match(zero_locations) 146 | 147 | # Delete rows and columns 148 | for row in matched_rows: 149 | zero_locations[row] = False 150 | for column in matched_columns: 151 | zero_locations[:, column] = False 152 | 153 | # Save Results 154 | self.__set_results(zip(matched_rows, matched_columns)) 155 | 156 | # Calculate total potential 157 | value = 0 158 | for row, column in self._results: 159 | value += self._input_matrix[row, column] 160 | self._totalPotential = value 161 | 162 | @staticmethod 163 | def make_cost_matrix(profit_matrix): 164 | """ 165 | Converts a profit matrix into a cost matrix. 166 | Expects NumPy objects as input. 167 | """ 168 | # subtract profit matrix from a matrix made of the max value of the profit matrix 169 | matrix_shape = profit_matrix.shape 170 | offset_matrix = np.ones(matrix_shape) * profit_matrix.max() 171 | cost_matrix = offset_matrix - profit_matrix 172 | return cost_matrix 173 | 174 | def _adjust_matrix_by_min_uncovered_num(self, result_matrix, covered_rows, covered_columns): 175 | """Subtract m from every uncovered number and add m to every element covered with two lines.""" 176 | # Calculate minimum uncovered number (m) 177 | elements = [] 178 | for row_index, row in enumerate(result_matrix): 179 | if row_index not in covered_rows: 180 | for index, element in enumerate(row): 181 | if index not in covered_columns: 182 | elements.append(element) 183 | min_uncovered_num = min(elements) 184 | 185 | # Add m to every covered element 186 | adjusted_matrix = result_matrix 187 | for row in covered_rows: 188 | adjusted_matrix[row] += min_uncovered_num 189 | for column in covered_columns: 190 | adjusted_matrix[:, column] += min_uncovered_num 191 | 192 | # Subtract m from every element 193 | m_matrix = np.ones(self._shape) * min_uncovered_num 194 | adjusted_matrix -= m_matrix 195 | 196 | return adjusted_matrix 197 | 198 | def __find_matches(self, zero_locations): 199 | """Returns rows and columns with matches in them.""" 200 | marked_rows = np.array([], dtype=int) 201 | marked_columns = np.array([], dtype=int) 202 | 203 | # Mark rows and columns with matches 204 | # Iterate over rows 205 | for index, row in enumerate(zero_locations): 206 | row_index = np.array([index]) 207 | if np.sum(row) == 1: 208 | column_index, = np.where(row) 209 | marked_rows, marked_columns = self.__mark_rows_and_columns(marked_rows, marked_columns, row_index, 210 | column_index) 211 | 212 | # Iterate over columns 213 | for index, column in enumerate(zero_locations.T): 214 | column_index = np.array([index]) 215 | if np.sum(column) == 1: 216 | row_index, = np.where(column) 217 | marked_rows, marked_columns = self.__mark_rows_and_columns(marked_rows, marked_columns, row_index, 218 | column_index) 219 | 220 | return marked_rows, marked_columns 221 | 222 | @staticmethod 223 | def __mark_rows_and_columns(marked_rows, marked_columns, row_index, column_index): 224 | """Check if column or row is marked. If not marked then mark it.""" 225 | new_marked_rows = marked_rows 226 | new_marked_columns = marked_columns 227 | if not (marked_rows == row_index).any() and not (marked_columns == column_index).any(): 228 | new_marked_rows = np.insert(marked_rows, len(marked_rows), row_index) 229 | new_marked_columns = np.insert(marked_columns, len(marked_columns), column_index) 230 | return new_marked_rows, new_marked_columns 231 | 232 | @staticmethod 233 | def select_arbitrary_match(zero_locations): 234 | """Selects row column combination with minimum number of zeros in it.""" 235 | # Count number of zeros in row and column combinations 236 | rows, columns = np.where(zero_locations) 237 | zero_count = [] 238 | for index, row in enumerate(rows): 239 | total_zeros = np.sum(zero_locations[row]) + np.sum(zero_locations[:, columns[index]]) 240 | zero_count.append(total_zeros) 241 | 242 | # Get the row column combination with the minimum number of zeros. 243 | indices = zero_count.index(min(zero_count)) 244 | row = np.array([rows[indices]]) 245 | column = np.array([columns[indices]]) 246 | 247 | return row, column 248 | 249 | def __set_results(self, result_lists): 250 | """Set results during calculation.""" 251 | # Check if results values are out of bound from input matrix (because of matrix being padded). 252 | # Add results to results list. 253 | for result in result_lists: 254 | row, column = result 255 | if row < self._maxRow and column < self._maxColumn: 256 | new_result = (int(row), int(column)) 257 | self._results.append(new_result) 258 | 259 | 260 | class CoverZeros: 261 | """ 262 | Use minimum number of lines to cover all zeros in the matrix. 263 | Algorithm based on: http://weber.ucsd.edu/~vcrawfor/hungar.pdf 264 | """ 265 | 266 | def __init__(self, matrix): 267 | """ 268 | Input a matrix and save it as a boolean matrix to designate zero locations. 269 | Run calculation procedure to generate results. 270 | """ 271 | # Find zeros in matrix 272 | self._zero_locations = (matrix == 0) 273 | self._shape = matrix.shape 274 | 275 | # Choices starts without any choices made. 276 | self._choices = np.zeros(self._shape, dtype=bool) 277 | 278 | self._marked_rows = [] 279 | self._marked_columns = [] 280 | 281 | # marks rows and columns 282 | self.__calculate() 283 | 284 | # Draw lines through all unmarked rows and all marked columns. 285 | self._covered_rows = list(set(range(self._shape[0])) - set(self._marked_rows)) 286 | self._covered_columns = self._marked_columns 287 | 288 | def get_covered_rows(self): 289 | """Return list of covered rows.""" 290 | return self._covered_rows 291 | 292 | def get_covered_columns(self): 293 | """Return list of covered columns.""" 294 | return self._covered_columns 295 | 296 | def __calculate(self): 297 | """ 298 | Calculates minimum number of lines necessary to cover all zeros in a matrix. 299 | Algorithm based on: http://weber.ucsd.edu/~vcrawfor/hungar.pdf 300 | """ 301 | while True: 302 | # Erase all marks. 303 | self._marked_rows = [] 304 | self._marked_columns = [] 305 | 306 | # Mark all rows in which no choice has been made. 307 | for index, row in enumerate(self._choices): 308 | if not row.any(): 309 | self._marked_rows.append(index) 310 | 311 | # If no marked rows then finish. 312 | if not self._marked_rows: 313 | return True 314 | 315 | # Mark all columns not already marked which have zeros in marked rows. 316 | num_marked_columns = self.__mark_new_columns_with_zeros_in_marked_rows() 317 | 318 | # If no new marked columns then finish. 319 | if num_marked_columns == 0: 320 | return True 321 | 322 | # While there is some choice in every marked column. 323 | while self.__choice_in_all_marked_columns(): 324 | # Some Choice in every marked column. 325 | 326 | # Mark all rows not already marked which have choices in marked columns. 327 | num_marked_rows = self.__mark_new_rows_with_choices_in_marked_columns() 328 | 329 | # If no new marks then Finish. 330 | if num_marked_rows == 0: 331 | return True 332 | 333 | # Mark all columns not already marked which have zeros in marked rows. 334 | num_marked_columns = self.__mark_new_columns_with_zeros_in_marked_rows() 335 | 336 | # If no new marked columns then finish. 337 | if num_marked_columns == 0: 338 | return True 339 | 340 | # No choice in one or more marked columns. 341 | # Find a marked column that does not have a choice. 342 | choice_column_index = self.__find_marked_column_without_choice() 343 | 344 | while choice_column_index is not None: 345 | # Find a zero in the column indexed that does not have a row with a choice. 346 | choice_row_index = self.__find_row_without_choice(choice_column_index) 347 | 348 | # Check if an available row was found. 349 | new_choice_column_index = None 350 | if choice_row_index is None: 351 | # Find a good row to accomodate swap. Find its column pair. 352 | choice_row_index, new_choice_column_index = \ 353 | self.__find_best_choice_row_and_new_column(choice_column_index) 354 | 355 | # Delete old choice. 356 | self._choices[choice_row_index, new_choice_column_index] = False 357 | 358 | # Set zero to choice. 359 | self._choices[choice_row_index, choice_column_index] = True 360 | 361 | # Loop again if choice is added to a row with a choice already in it. 362 | choice_column_index = new_choice_column_index 363 | 364 | def __mark_new_columns_with_zeros_in_marked_rows(self): 365 | """Mark all columns not already marked which have zeros in marked rows.""" 366 | num_marked_columns = 0 367 | for index, column in enumerate(self._zero_locations.T): 368 | if index not in self._marked_columns: 369 | if column.any(): 370 | row_indices, = np.where(column) 371 | zeros_in_marked_rows = (set(self._marked_rows) & set(row_indices)) != set([]) 372 | if zeros_in_marked_rows: 373 | self._marked_columns.append(index) 374 | num_marked_columns += 1 375 | return num_marked_columns 376 | 377 | def __mark_new_rows_with_choices_in_marked_columns(self): 378 | """Mark all rows not already marked which have choices in marked columns.""" 379 | num_marked_rows = 0 380 | for index, row in enumerate(self._choices): 381 | if index not in self._marked_rows: 382 | if row.any(): 383 | column_index, = np.where(row) 384 | if column_index in self._marked_columns: 385 | self._marked_rows.append(index) 386 | num_marked_rows += 1 387 | return num_marked_rows 388 | 389 | def __choice_in_all_marked_columns(self): 390 | """Return Boolean True if there is a choice in all marked columns. Returns boolean False otherwise.""" 391 | for column_index in self._marked_columns: 392 | if not self._choices[:, column_index].any(): 393 | return False 394 | return True 395 | 396 | def __find_marked_column_without_choice(self): 397 | """Find a marked column that does not have a choice.""" 398 | for column_index in self._marked_columns: 399 | if not self._choices[:, column_index].any(): 400 | return column_index 401 | 402 | raise HungarianError( 403 | "Could not find a column without a choice. Failed to cover matrix zeros. Algorithm has failed.") 404 | 405 | def __find_row_without_choice(self, choice_column_index): 406 | """Find a row without a choice in it for the column indexed. If a row does not exist then return None.""" 407 | row_indices, = np.where(self._zero_locations[:, choice_column_index]) 408 | for row_index in row_indices: 409 | if not self._choices[row_index].any(): 410 | return row_index 411 | 412 | # All rows have choices. Return None. 413 | return None 414 | 415 | def __find_best_choice_row_and_new_column(self, choice_column_index): 416 | """ 417 | Find a row index to use for the choice so that the column that needs to be changed is optimal. 418 | Return a random row and column if unable to find an optimal selection. 419 | """ 420 | row_indices, = np.where(self._zero_locations[:, choice_column_index]) 421 | for row_index in row_indices: 422 | column_indices, = np.where(self._choices[row_index]) 423 | column_index = column_indices[0] 424 | if self.__find_row_without_choice(column_index) is not None: 425 | return row_index, column_index 426 | 427 | # Cannot find optimal row and column. Return a random row and column. 428 | from random import shuffle 429 | 430 | shuffle(row_indices) 431 | column_index, = np.where(self._choices[row_indices[0]]) 432 | return row_indices[0], column_index[0] 433 | 434 | 435 | if __name__ == '__main__': 436 | profit_matrix = [ 437 | [62, 75, 80, 93, 95, 97], 438 | [75, 80, 82, 85, 71, 97], 439 | [80, 75, 81, 98, 90, 97], 440 | [78, 82, 84, 80, 50, 98], 441 | [90, 85, 85, 80, 85, 99], 442 | [65, 75, 80, 75, 68, 96]] 443 | 444 | hungarian = Hungarian(profit_matrix, is_profit_matrix=True) 445 | hungarian.calculate() 446 | print("Expected value:\t\t543") 447 | print("Calculated value:\t", hungarian.get_total_potential()) # = 543 448 | print("Expected results:\n\t[(0, 4), (2, 3), (5, 5), (4, 0), (1, 1), (3, 2)]") 449 | print("Results:\n\t", hungarian.get_results()) 450 | print("-" * 80) 451 | 452 | cost_matrix = [ 453 | [4, 2, 8], 454 | [4, 3, 7], 455 | [3, 1, 6]] 456 | hungarian = Hungarian(cost_matrix) 457 | print('calculating...') 458 | hungarian.calculate() 459 | print("Expected value:\t\t12") 460 | print("Calculated value:\t", hungarian.get_total_potential()) # = 12 461 | print("Expected results:\n\t[(0, 1), (1, 0), (2, 2)]") 462 | print("Results:\n\t", hungarian.get_results()) 463 | print("-" * 80) 464 | 465 | profit_matrix = [ 466 | [62, 75, 80, 93, 0, 97], 467 | [75, 0, 82, 85, 71, 97], 468 | [80, 75, 81, 0, 90, 97], 469 | [78, 82, 0, 80, 50, 98], 470 | [0, 85, 85, 80, 85, 99], 471 | [65, 75, 80, 75, 68, 0]] 472 | hungarian = Hungarian() 473 | hungarian.calculate(profit_matrix, is_profit_matrix=True) 474 | print("Expected value:\t\t523") 475 | print("Calculated value:\t", hungarian.get_total_potential()) # = 523 476 | print("Expected results:\n\t[(0, 3), (2, 4), (3, 0), (5, 2), (1, 5), (4, 1)]") 477 | print("Results:\n\t", hungarian.get_results()) 478 | print("-" * 80) 479 | --------------------------------------------------------------------------------