-
Notifications
You must be signed in to change notification settings - Fork 12
/
trainw2v.py
226 lines (195 loc) · 7.37 KB
/
trainw2v.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
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
import re
import gensim
import os
import itertools
import numpy as np
import argparse
import string
from nltk.corpus import stopwords
import glob
from bs4 import BeautifulSoup
from mycounter import Counter
import math
import pickle
from sklearn.metrics import pairwise
from nltk.stem import WordNetLemmatizer
from difflib import SequenceMatcher
import random
wordnet_lemmatizer = WordNetLemmatizer()
engstop = stopwords.words('english')
set_stopword=engstop
parser = argparse.ArgumentParser("Word2Vec")
def lemmaorstem(w):
return wordnet_lemmatizer.lemmatize(w)
def proclineb(q):
q=q.replace('Which of the following ','').replace('Which of these ','').replace('Which statement BEST describes ','').replace('Which statement best describes ','')
q=q.replace(' evidence','').replace(' description','').replace(' example','').replace(' explains','').replace(' best ','').replace(' explanation','').replace(' likely','')
q=q.replace(' describe','').replace(' correctly','').replace(' identifies','').replace(' determines','').replace(' would','').replace(' estimate','')
q=q.replace('Were do ','').replace('If a ','').replace('In which ','').replace('Which best ','').replace('What are ', '').replace('According ', '')
q=q.replace('What best ','').replace('What is ','').replace('What would ', '').replace('When a ','').replace('Which statement ', '').replace(' statement', '')
q=q.replace('Why is ','').replace('Which ','').replace('Researchers ','').replace('A scientist ','').replace('A student ','')
q = q.replace('\t',' ').replace('\n',' ').replace('\r', ' ').replace(' ',' ').replace(' ',' ').replace(' ',' ')
q = re.sub('[^a-zA-Z0-9\- \']+', " ", q)
q=[lemmaorstem(m) for m in q.lower().split(' ') if m not in set_stopword and m!='']
return q#' '.join(q)
def procline(q,stem=True):
q=q.replace('Which of the following ','').replace('Which of these ','').replace('Which statement best describes ','')
q=q.replace('Were do ','').replace('If a ','').replace('In which ','').replace('Which best ','').replace('What are ', '')
q=q.replace('What best ','').replace('What is ','').replace('What would ', '').replace('When a ','').replace('Which statement ', '')
q=q.replace('Why is ','').replace('Which ','')
q = q.replace('\t',' ').replace('\n',' ').replace('\r', ' ').replace(' ',' ').replace(' ',' ').replace(' ',' ')
q = re.sub('[^a-zA-Z0-9\- \']+', " ", q)
if stem==False:
q=[m for m in q.lower().split(' ') if m not in set_stopword and m!='' and m!=' ']
else:
q=[lemmaorstem(m) for m in q.lower().split(' ') if m not in set_stopword and m!='' and m!=' ']
return q
def get_vector_from_model(model, key):
if key in model:
return model[key]
else:
#return np.random.uniform(-0.25,0.25,model.syn0.shape[1])
return np.zeros(model.syn0.shape[1])
def get_entities_from_list(vocab,list):
lista=[]
for i in range(len(list)-1):
if i<len(list):
#print i,list,len(list)
word1 = list[i]+'_'+list[i+1]
#print word1
if word1 in vocab:
lista.append(word1)
word2 = list[i+1]+'_'+list[i]
#print word2
if word2 in vocab:
lista.append(word2)
else:
w,scor=fuzzymatch(word1,vocab)
#print w,word1,scor
if w!='' and w.find('_')!=-1:
lista.append(w)
else:
w,scor=fuzzymatch(word2,vocab)
#print w,word2,scor
if w!='' and w.find('_')!=-1:
lista.append(w)
#print lista
final=[]
for m in range(len(list)):
if list[m] in vocab:
lista.append(list[m])
else:
w,scor=fuzzymatch(list[m],vocab)
if w!='':
lista.append(w)
#print lista
return lista
def trainw2v2():
sents=[]
if 1==2:
sents2=[]
for line in open('train/CK12clean.txt'):
#text = line.replace('\t',' ').replace('\n',' ').replace('\r', ' ').replace(' ',' ').replace(' ',' ').replace(' ',' ')
#text = re.sub('[^a-zA-Z0-9 \']+', " ", text.lower()).replace(' ',' ')
#sent= [m for m in text.split(' ') if m not in engstop and m!='' and m!=' ']
sent=procline(line)
sents.append(sent)
sents2.append(' '.join(sent))
f=open('CK12lemma.txt','wb+')
f.write('\n'.join(sents2))
f.close()
lines={}
lines2=[]
for line in open('train/bigquiz.txt'):
#text = line.replace('\t',' ').replace('\n',' ').replace('\r', ' ').replace(' ',' ').replace(' ',' ').replace(' ',' ')
#text = re.sub('[^a-zA-Z0-9 \']+', " ", text.lower()).replace(' ',' ')
#sent= [m for m in text.split(' ') if m not in engstop and m!='' and m!=' ']
line=line.split('\t')
line=' '.join(line[1:])
lines[line]=None
for line in lines:
sent=procline(line)
lines2.append(' '.join(sent))
sents.append(sent)
if 1==2:
lines={}
lines2=[]
for line in open('train/bigquiz2.txt'):
#text = line.replace('\t',' ').replace('\n',' ').replace('\r', ' ').replace(' ',' ').replace(' ',' ').replace(' ',' ')
#text = re.sub('[^a-zA-Z0-9 \']+', " ", text.lower()).replace(' ',' ')
#sent= [m for m in text.split(' ') if m not in engstop and m!='' and m!=' ']
line=line.split('\t')
line=' '.join(line[1:])
lines[line]=None
for line in lines:
sent=procline(line)
lines2.append(' '.join(sent))
sents.append(sent)
f=open('bigquizlemma2.txt','wb+')
f.write('\n'.join(lines2))
f.close()
lines={}
lines2=[]
for line in open('train/bigquiz3.txt'):
#text = line.replace('\t',' ').replace('\n',' ').replace('\r', ' ').replace(' ',' ').replace(' ',' ').replace(' ',' ')
#text = re.sub('[^a-zA-Z0-9 \']+', " ", text.lower()).replace(' ',' ')
#sent= [m for m in text.split(' ') if m not in engstop and m!='' and m!=' ']
line=line.split('\t')
line=' '.join(line[1:])
lines[line]=None
for line in lines:
sent=procline(line)
lines2.append(' '.join(sent))
sents.append(sent)
f=open('bigquizlemma3.txt','wb+')
f.write('\n'.join(lines2))
f.close()
if 1==1:
bidict,tridict = pickle.load(open('quizletvocab3.pick','rb'))
lines={}
for line in open('train/bigquizlemma.txt'):
lines[line.rstrip()]=None
for line in open('train/bigquizlemma2.txt'):
lines[line.rstrip()]=None
for line in open('train/bigquizlemma3.txt'):
lines[line.rstrip()]=None
for line in open('train/CK12lemma.txt'):
lines[line.rstrip()]=None
for line in lines:
line=line.split(' ')
line.extend(get_entities_from_list(bidict,line))
line.extend(get_entities_from_list(tridict,line))
sents.append(line)
#print line
lines=None
path_model = 'model/word2vec_myck12_quizlet3_stem_23gram.model'
model = gensim.models.Word2Vec(sents, min_count = 5, workers = 4, size = 300, window = 9, iter = 10)
##model = gensim.models.Word2Vec(sents, sg=0,min_count = 5, workers = 4, size = 300, window = 5, iter = 10)
model.save(path_model)
#f=open('bigquizlemma.txt','wb+')
#f.write('\n'.join(lines2))
#f.close()
def fuzzymatch(w,vocab):
if w in vocab:
return w,1.0
spl=w.split('_')
candidates=[]
for m in spl:
if m in vocab:
candidates.extend(vocab[m])
if len(candidates)==0 and w[0:3] in vocab:
candidates=vocab[w[0:3]]
maxi=''
scor=0
if isinstance(candidates, list)==False:
return maxi,scor
for m in candidates:
if m[0:3]==w[0:3]:
ratio=SequenceMatcher(None, a=m,b=w).ratio()
if ratio>0.85:
#print w,m,ratio
if ratio>scor:
scor=ratio
maxi=m
return maxi,scor
trainw2v2()