-
Notifications
You must be signed in to change notification settings - Fork 0
/
reviews.py
175 lines (116 loc) · 4.06 KB
/
reviews.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
import csv
import re
import numpy as np
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import GridSearchCV
from sklearn.neighbors import KNeighborsClassifier
from sklearn.ensemble import AdaBoostClassifier
import matplotlib.pyplot as plt
#reads in data into xtrain and ytrain variables
with open("trainreviews.txt", "r") as ins:
xtrain = []
ytrain = []
for line in ins:
head,sep,tail = line.partition("\t")
#head = re.sub('[^A-Za-z0-9]+', '', head)
head = re.sub(r"[-()\"#/@;:<>{}`+=~|.!?,]", " ", head) #replace special characters with space
head = ''.join([i for i in head if not i.isdigit()]) #remove digits
head = head.lower() #make all characters lowercase
tail = float(tail) #make the value a number
xtrain.append(head) #add sentence to xtrain
ytrain.append(tail) #add class value to ytrain
#reads in test data into xvalidation matrix
with open("testreviewsunlabeled.txt", "r") as ins:
xreal = []
yreal = []
for line in ins:
head,sep,tail = line.partition("\t")
head = re.sub(r"[-()\"#/@;:<>{}`+=~|.!?,]", " ", head) #replace special characters with space
head = ''.join([i for i in head if not i.isdigit()]) #remove digits
head = head.lower() #make all characters lowercase
#tail = float(tail)
xreal.append(head)
yreal.append(tail)
#done reading in reviews
#word embeddings
textmatrix = []
with open("glove.6B.50d.txt", "r") as f:
textmatrix = [line.split() for line in f]
#create dict of word embeddings where keys are words and values are word vectors
dict = {}
for line in textmatrix:
list2 = [float(i) for i in line[1:]]
dict[line[0]] = list2
embeddings = []
lineno = 0
#for every document add calculate sum of word embeddings
for line in xtrain:
sum = np.zeros(50)
for word in line.split():
try:
sum = sum + np.array( dict[word] )
except:
pass
embeddings.append(sum)
lineno = lineno+1
#embeddiings is the final data matrix
#vectorizer for bag of words
vectorizer = CountVectorizer()
X = vectorizer.fit_transform(xtrain) #makes a big of words matrix for training data
Xreal = vectorizer.transform(xreal) #bag of words for validation set
clforig = LogisticRegression(C = 10) #final model chosen after experiments
#clforig = KNeighborsClassifier()
#clforig = AdaBoostClassifier()
clforig.fit(X,ytrain)
preds = clforig.predict(Xreal)
"""this is code that writes the predicted-labels file
with open('predicted-labels.txt', 'w') as f:
for item in preds:
item = int(item)
f.write("%s\n" % item)
"""
###
#The following code was used to run cross validation for 3 models and plot errors
###
parameters = {'C':[0.01, 0.1, 1, 10, 100, 1000]}
#parameters = {'n_neighbors':[1, 10, 50, 100, 200]}
#parameters = {'n_estimators':[50,100,150,200]}
clf = GridSearchCV(clforig, parameters, cv=5)
clf.fit(embeddings,ytrain) #run cross validation
#
#debugging print statements
print("score is:")
print( clf.best_score_ )
print("best param?:")
print(clf.best_params_)
print(clf.cv_results_)
print("\ntesterror:")
testscores = clf.cv_results_['mean_test_score']
testscores = 1-testscores
print(testscores)
print("trainingerror")
trainscores = clf.cv_results_['mean_train_score']
trainscores = 1- trainscores
print(trainscores)
print("parameter values:")
paramvalues = []
paramdicts = clf.cv_results_['params']
for paramdict in paramdicts:
paramvalues.append(paramdict['C'])
paramvalues = np.log10(paramvalues) #for logreg only
print(paramvalues)
#
#
#plotting code
plt.plot(paramvalues, testscores, label = "validation set" )
plt.plot(paramvalues, trainscores , label = "training set")
plt.legend()
#plt.title("Adaboost training/test accuracy vs n_estimators (Word Embedding)")
#plt.title("KNN training/valid. error vs n_neighbors (Word Embedding)")
plt.title("Logistic Regression training/valid. error vs C (Bag of Words)")
#plt.xlabel("n_estimators")
#plt.xlabel("n_neighbors")
plt.xlabel("log10(C)")
plt.ylabel("error")
plt.show()