Carlos-Francisco Méndez-Cruz

LSA soft clustering

1 +"""Pirated example from Gensim library (a NLP specialized tool):
2 +https://radimrehurek.com/gensim/tut2.html
3 +https://radimrehurek.com/gensim/wiki.html#latent-semantic-analysis
4 +
5 +Ignacio Arroyo
6 +"""
7 +
8 +import gensim
9 +import logging
10 +from six import iteritems
11 +from gensim import corpora
12 +import argparse
13 +
14 +from pdb import set_trace as st # Debug the program step by step calling st()
15 + # anywhere.
16 +class corpus_streamer(object):
17 + """ This Object streams the input raw text file row by row.
18 + """
19 + def __init__(self, file_name, dictionary=None, strings=None):
20 + self.file_name=file_name
21 + self.dictionary=dictionary
22 + self.strings=strings
23 +
24 + def __iter__(self):
25 + for line in open(self.file_name):
26 + # assume there's one document per line, tokens separated by whitespace
27 + if self.dictionary and not self.strings:
28 + yield self.dictionary.doc2bow(line.lower().split())
29 + elif not self.dictionary and self.strings:
30 + yield line.strip().lower()
31 +# Logging all our program
32 +logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s',
33 + level=logging.INFO)
34 +
35 +parser = argparse.ArgumentParser()
36 +parser.add_argument("--n_topics", help="Number of eigenvectors picked up.",
37 + default=2, type=int)
38 +parser.add_argument("--input", help="Input file to perform LSA.",
39 + required=True)
40 +
41 +args = parser.parse_args()
42 +
43 +n_topics=args.n_topics
44 +n_docs=0
45 +input_file=args.input
46 +#input_file='lsa_example.csv'
47 +#input_file='wiki_sample/wiki_75_AA.txt.cln'
48 +#input_file='wiki_sample/wiki_77_AA.txt'
49 +
50 +# A little stopwords list
51 +stoplist = set('for a of the and to in _ [ ]'.split())
52 +# Do not load the text corpus into memory, but stream it!
53 +fille=corpus_streamer(input_file, strings=True)
54 +dictionary=corpora.Dictionary(line.lower().split() for line in fille)#open(input_file))
55 +# remove stop words and words that appear only once
56 +stop_ids=[dictionary.token2id[stopword] for stopword in stoplist
57 + if stopword in dictionary.token2id]
58 +once_ids=[tokenid for tokenid, docfreq in iteritems(dictionary.dfs)
59 + if docfreq == 1]
60 +dictionary.filter_tokens(stop_ids + once_ids)
61 +# remove gaps in id sequence after words that were removed
62 +dictionary.compactify()
63 +# Store the dictionary
64 +dictionary.save('lsa_mini.dict')
65 +# Reading sentences from file into a list of strings.
66 +# Use instead streaming objects:
67 +# Load stored word-id map (dictionary)
68 +stream_it = corpus_streamer(input_file, dictionary=dictionary)
69 +#for vector in stream_it: # load one vector into memory at a time
70 +# print vector
71 +# Convert to sparse matrix
72 +sparse_corpus = [text for text in stream_it]
73 +# Store to disk, for later use collect statistics about all tokens
74 +corpora.MmCorpus.serialize('lsa_mini.mm',
75 + sparse_corpus)
76 +## LSA zone
77 +# load the dictionary saved before
78 +id2word = dictionary.load('lsa_mini.dict')
79 +# Now load the sparse matrix corpus from file into a (memory friendly) streaming
80 +# object.
81 +corpus=corpora.MmCorpus('lsa_mini.mm')
82 +
83 +## IF TfidfModel
84 +tfidf = gensim.models.TfidfModel(corpus) # step 1 -- initialize a model
85 +corpus = tfidf[corpus]
86 +## FI TfidfModel
87 +# Compute the LSA vectors
88 +lsa=gensim.models.lsimodel.LsiModel(corpus, id2word=dictionary,
89 + num_topics=n_topics)
90 +# Print the n topics in our corpus:
91 +#lsa.print_topics(n_topics)
92 +f=open("topics_file.txt","wb")
93 +f.write("-------------------------------------------------\n")
94 +for t in lsa.show_topics(num_words=200):
95 + f.write("%s\n" % str(t))
96 +
97 +f.write("-------------------------------------------------\n")
98 +f.close()
99 +# create a double wrapper over the original corpus: bow->tfidf->fold-in-lsi
100 +corpus_lsa = lsa[corpus]
101 +# Stream sentences from file into a list of strings called "sentences"
102 +sentences=corpus_streamer(input_file, strings=True)
103 +n=0
104 +for pertenence, sentence in zip(corpus_lsa, sentences):
105 + if n_docs <= 0:
106 + #print "%s\t\t%s" % (pertenence, sentence.split("\t")[0])
107 + p=[dict(pertenence)[x] if x in dict(pertenence) else 0.0
108 + for x in xrange(n_topics)]
109 + print "%s %s" % ("".join(sentence.split("\t")[0].split()),
110 + "".join(str(p)[1:].strip("]").split(",")) )
111 + else:
112 + if n<n_docs:
113 + pertenence=[dict(pertenence)[x] if x in dict(pertenence) else 0.0
114 + for x in xrange(n_topics)]
115 + print "%s\t\t%s" % (pertenence, sentence)
116 + n+=1
117 + else:
118 + break
...\ No newline at end of file ...\ No newline at end of file
1 +c1: Human machine interface for ABC computer applications
2 +c2: A survey of user opinion of computer system response time
3 +c3: The EPS user interface management system
4 +c4: System and human system engineering testing of EPS
5 +c5: Relation of user perceived response time to error measurement
6 +m1: The generation of random, binary, ordered trees
7 +m2: The intersection graph of paths in trees
8 +m3: Graph minors IV: Widths of trees and well-quasi-ordering
9 +m4: Graph minors: A survey