/
doc2vec.py
232 lines (196 loc) · 6.55 KB
/
doc2vec.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
227
228
229
230
231
232
from gensim.models import Doc2Vec
from gensim.utils import to_unicode
from collections import namedtuple
from cnn import CNN
import string
import numpy as np
from sklearn.linear_model import LogisticRegression as LR
from sklearn.svm import SVC
from keras.utils import np_utils
from random import shuffle
from sklearn.metrics import precision_recall_fscore_support, accuracy_score
from gensim.test.test_doc2vec import ConcatenatedDoc2Vec
SentimentDocument = namedtuple("SentimentDocument", "words tags sentiment split")
train = [
"./Data/train/BookTrain.csv",
"./Data/train/DVDTrain.csv",
"./Data/train/ElectronicsTrain.csv",
"./Data/train/KitchenTrain.csv"
]
test = ["./Data/test/BookTest.csv","./Data/test/DVDTest.csv","./Data/test/ElectronicsTest.csv","./Data/test/KitchenTest.csv"]
unlabel = ["./Data/BookUnlabel.csv", "./Data/DVDUnlabel.csv", "./Data/ElectronicsUnlabel.csv", "./Data/KitchenUnlabel.csv"]
test_path = unlabel[1]
def sentiment_to_int(i):
if i == "pos":
return 1
return 0
def reshapeX(X):
n = len(X)
t = len(X[0])
return X.reshape(n, 1, t, 1)
def reshapeY(Y):
return np_utils.to_categorical(Y)
def get_data(file_path, split="train"):
f = open(file_path)
f.readline()
k = 0
docs = []
for i in f.readlines():
s = i.split(",")
words = ""
for i in s[1:]:
words += " " + i.strip().lower()
words = words.translate(None, string.punctuation)
tags =[split + "_" + str(k)]
sentiment = sentiment_to_int(s[0])
words = to_unicode(words).split()
docs.append(SentimentDocument(words, tags, sentiment, split))
k+=1
f.close()
return docs
def split(docs, model):
X = []
Y = []
for i in docs:
Y.append(i.sentiment)
X.append(model.docvecs[i.tags[0]])
return X, Y
def split_test(docs, model):
X = []
Y = []
for i in docs:
Y.append(i.sentiment)
X.append(model.infer_vector(i.words))
return X, Y
def get_accuracy(pred, testY):
c = 0
pred = [round(x) for x in pred]
for i in range(0, len(pred)):
if pred[i] == testY[i]:
c+=1
print c
c = c*1.0
c/= len(testY)
print len(testY)
return c
simple_models = [
# PV-DM w/concatenation - window=5 (both sides) approximates paper's 10-word total window size
Doc2Vec(dm=1, dm_concat=1, vector_size=100, window=5, negative=5, hs=0, min_count=2, epochs=55),
# PV-DBOW
Doc2Vec(dm=0, vector_size=100, negative=5, hs=0, min_count=2, epochs=100),
# PV-DM w/average
Doc2Vec(dm=1, dm_mean=1, vector_size=100, window=10, negative=10, hs=0, min_count=2, epochs=55)
]
train_docs = []
for i in range(len(train)):
train_docs.extend(get_data(train[i]))
test_docs = get_data(test_path, split="test")
simple_models[1].build_vocab(train_docs)
models_by_name =[]
#models_by_name.append(simple_models[0])
models_by_name.append(simple_models[1])
#models_by_name.append(simple_models[2])
#models_by_name.append(ConcatenatedDoc2Vec([simple_models[1], simple_models[2]]))
doc_list = train_docs
shuffle(doc_list)
for i in range(len(models_by_name)):
if i<3:
models_by_name[i].train(doc_list, epochs=models_by_name[i].epochs, total_examples=models_by_name[i].corpus_count)
else:
models_by_name[i].train(doc_list)
for train_i in range(len(train)):
for test_i in range(4):
train_path = train[train_i]
train_docs = get_data(train_path)
simple_models = [
# PV-DM w/concatenation - window=5 (both sides) approximates paper's 10-word total window size
Doc2Vec(dm=1, dm_concat=1, vector_size=100, window=5, negative=5, hs=0, min_count=2, epochs=55),
# PV-DBOW
Doc2Vec(dm=0, vector_size=100, negative=5, hs=0, min_count=2, epochs=100),
# PV-DM w/average
Doc2Vec(dm=1, dm_mean=1, vector_size=100, window=10, negative=10, hs=0, min_count=2, epochs=55)
]
simple_models[1].build_vocab(train_docs)
models_by_name =[]
#models_by_name.append(simple_models[0])
models_by_name.append(simple_models[1])
#models_by_name.append(simple_models[2])
#models_by_name.append(ConcatenatedDoc2Vec([simple_models[1], simple_models[2]]))
doc_list = train_docs
shuffle(doc_list)
for i in range(len(models_by_name)):
if i<3:
models_by_name[i].train(doc_list, epochs=models_by_name[i].epochs, total_examples=models_by_name[i].corpus_count)
else:
models_by_name[i].train(doc_list)
for test_j in range(2):
test_path = test[test_i]
title = "Test Data"
if test_j==1:
test_path = unlabel[test_i]
title = "Cross Validation Set(Larger Data Set)"
print title
test_docs = get_data(test_path, split="test")
for model in models_by_name:
testX, testY = split_test(test_docs, model)
trainX, trainY = split(train_docs, model)
trainX = np.asarray(trainX)
testX = np.asarray(testX)
trainY = np.asarray(trainY)
testY = np.asarray(testY)
trainX = reshapeX(trainX)
testX = reshapeX(testX)
trainY = reshapeY(trainY)
cnn = CNN(100).get_model()
cnn.fit(trainX, trainY, epochs=20, batch_size=250, verbose=0)
pred = cnn.predict(testX)
val = []
for i in pred:
if i[0] > 0.50:
val.append(0)
else:
val.append(1)
linear_model = SVC()
linear_model.fit(trainX, trainY)
val = linear_model.predict(testX)
test_accuracy = precision_recall_fscore_support(testY, val, average="weighted")
print "Accuracy = {0:.4f}".format( accuracy_score(testY, val))
print "Precision = {0:.4f}".format(test_accuracy[0])
print "Recall = {0:.4f}".format(test_accuracy[1])
print "F1-Score = {0:.4f}".format(test_accuracy[2])
"""
#training with SVC
for model in models_by_name:
trainX, trainY = split(train_docs, model)
testX, testY = split_test(test_docs, model)
linear_model = SVC()
linear_model.fit(trainX, trainY)
pred = linear_model.predict(testX)
print accuracy_score(testY, pred)
print precision_recall_fscore_support(testY, pred, average="weighted")
for model in models_by_name:
trainX, trainY = split(train_docs, model)
testX, testY = split_test(test_docs, model)
trainX = np.asarray(trainX)
testX = np.asarray(testX)
trainY = np.asarray(trainY)
testY = np.asarray(testY)
trainX = reshapeX(trainX)
testX = reshapeX(testX)
trainY = reshapeY(trainY)
cnn = CNN(100).get_model()
cnn.fit(trainX, trainY, epochs=20, batch_size=250, verbose=0)
pred = cnn.predict(testX)
val = []
for i in pred:
if i[0] > 0.50:
val.append(0)
else:
val.append(1)
test_accuracy = precision_recall_fscore_support(testY, val, average="weighted")
print train, test_path
print "Accuracy = {0:.4f}".format( accuracy_score(testY, val))
print "Precision = {0:.4f}".format(test_accuracy[0])
print "Recall = {0:.4f}".format(test_accuracy[1])
print "F1-Score = {0:.4f}".format(test_accuracy[2])
"""