-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgenwrap.py
190 lines (129 loc) · 5.01 KB
/
genwrap.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
#!usr/bin/python
# -*- coding: utf-8 -*-
'''
filename: genwrap.py
description: a python wrapper for gensim APIs
version : 0.2 (basic funciton with support for generator)
author: Wonchang Chung
date: 08/12/2016
'''
import os
import sys
import math
import time
import gensim
from gensim import corpora, models, utils
import nltk
from nltk.corpus import stopwords
import string
import argparse
import numpy as np
from six import iteritems
from utils import read_large_file
def get_arguments():
print "----------------------------------------"
print "parsing arguments..."
parser = argparse.ArgumentParser()
# choose mode
parser.add_argument('--model', type=str, default='lda',
help='choose mode : lda/lsi')
# choose vectorization
parser.add_argument('--vec', type=str, default='bow',
help='choose vectorization : bow/tfidf')
args = parser.parse_args()
print "arguments parsing done."
# printout all arguments
print "----------------------------------------"
print "LIST OF ARGUMENTS"
for arg in vars(args):
print arg, ":", getattr(args, arg)
return args
def make_dictionary(raw_file):
stoplist = stopwords.words('english')
try:
dictionary = corpora.Dictionary(map(lambda x : x.split('/')[0], utils.lemmatize(line)) for line in read_large_file(open(raw_file)))
# dictionary = corpora.Dictionary(utils.lemmatize(line) for line in read_large_file(open(raw_file)))
# dictionary = corpora.Dictionary(line.lower().split() for line in read_large_file(open(raw_file)))
# dictionary = corpora.Dictionary(line.lower().split() for line in open(raw_file))
# remove stopwords and once-words
stop_ids = [dictionary.token2id[stopword] for stopword in stoplist if stopword in dictionary.token2id]
once_ids = [tokenid for tokenid, docfreq in iteritems(dictionary.dfs) if docfreq == 1]
dictionary.filter_tokens(stop_ids + once_ids)
dictionary.compactify()
return dictionary
except (IOError, OSError):
print("Error opening / processing file")
def make_corpus(raw_file, dictionary):
try:
corpus = [dictionary.doc2bow(text.lower().split()) for text in read_large_file(open(raw_file))]
# corpus = [dictionary.doc2bow(text.lower().split()) for text in open(raw_file)]
# when using tf-idf
tfidf = models.TfidfModel(corpus)
corpus = tfidf[corpus]
return corpus, tfidf
except (IOError, OSError):
print("Error opening / processing file")
def look_up(model, dictionary, tfidf, doc):
# topic lookup function
doc_value = model[tfidf[dictionary.doc2bow(doc.lower().split())]]
return doc_value
def word_to_vec(sentences, size):
# TODO : implement word2vec wrapper
# sentences = list of list of words
return models.word2vec.Word2Vec(sentences, size=size, window=5, min_count=5, workers=4)
def doc_to_vec(documents, size):
# TODO : implement doc2vec wrapper
tagged_documents = models.doc2vec.TaggedLineDocument(documents)
model = models.doc2vec.Doc2Vec(tagged_documents, size=size, window=10, min_count=5, workers=11,alpha=0.025, min_alpha=0.025)
model.build_vocab
# TODO : train in loop with changing parameters
model.train
return model
def main():
args = get_arguments()
INPUT_FILE = 'data/sample_corpus.txt'
print "----------------------------------------"
print "making dictionary.."
dictionary = make_dictionary(INPUT_FILE)
print "dictionary done."
print "----------------------------------------"
print "making corpus.."
corpus, tfidf = make_corpus(INPUT_FILE, dictionary)
print "corpus done."
# TODO : add any other possible options
if args.model == 'lda':
print "----------------------------------------"
print "doing LDA.."
# lda = gensim.models.ldamodel.LdaModel(corpus=corpus, id2word=dictionary, num_topics=100, update_every=1, chunksize=10000, passes=1)
# load/save
lda.save('model/model.lda')
dictionary.save('model/dict.lda')
tfidf.save('model/tfidf.lda')
# lda = models.LdaModel.load('model/model.lda')
# dictionary = corpora.Dictionary.load('model/dict.lda')
# tfidf = models.TfidfModel.load('model/tfidf.lda')
topics = lda.print_topics(10)
for topic in topics:
print dictionary.id2token[topic[0]], topic[1]
value = look_up(lda, dictionary, tfidf, "I like scissors and hammer and control and earthquake")
for topic in value:
print dictionary.id2token[topic[0]], topic[1]
print "LDA done."
elif args.model == 'lsi':
print "----------------------------------------"
print "doing LSI.."
lsi = gensim.models.lsimodel.LsiModel(corpus=corpus, id2word=dictionary, num_topics=400)
# load/save
lsi.save('model/model.lsi')
dictionary.save('model/dict.lda')
tfidf.save('model/tfidf.lda')
# lsi = models.LsiModel.load('model/model.lsi')
# dictionary = corpora.Dictionary.load('model/dict.lda')
# tfidf = models.TfidfModel.load('model/tfidf.lda')
topics = lsi.print_topics(10)
for topic in topics:
print dictionary.id2token[topic[0]], topic[1]
print "LSI done."
else:
raise ValueError('choose proper mode: lda/lsi')
if __name__ == '__main__' : main()