-
Notifications
You must be signed in to change notification settings - Fork 0
/
svm.py
192 lines (168 loc) · 6 KB
/
svm.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
from __future__ import division
import numpy as np
from sklearn.svm import SVC
from sklearn.grid_search import GridSearchCV as gs
from sklearn.preprocessing import normalize
import tfidfSparse as tf
from scipy.sparse import csr_matrix, coo_matrix
import lsi
import n_gram as bigram
import itertools
''' This module contains functions for SVR regression as well as
related utility methods (i.e. compiling the targets vector,
normalizing features, and training/testing using support vector
regression. '''
def compile_targets(filename, threshold = 0.75, binary_threshold = True):
# Construct target vector
ratings = []
with open(filename, 'r') as f:
line = f.readline()
percents = []
while line != '':
if 'review/helpfulness: ' in line:
line = line[len('review/helpfulness: '):]
numbers = line.split('/')
percent = float(numbers[0]) / float(numbers[1])
percents.append(percent)
if binary_threshold:
if percent > threshold:
ratings.append(1)
else:
ratings.append(0)
line = f.readline()
if binary_threshold:
print ratings.count(0)
print ratings.count(1)
return np.array(ratings)
"""percents = np.array(percents)
uq = np.percentile(percents, 75)
m = np.percentile(percents, 50)
lq = np.percentile(percents, 25)
print uq, m, lq
for i in xrange(percents.shape[0]):
if percents[i] < lq:
percents[i] = 0
elif percents[i] >= lq and percents[i] < m:
percents[i] = 1
elif percents[i] >= m and percents[i] < uq:
percents[i] = 2
elif percents[i] >= uq:
percents[i] = 3
print len(np.where(percents == 0)[0])
print len(np.where(percents == 1)[0])
print len(np.where(percents == 2)[0])
print len(np.where(percents == 3)[0])
return percents"""
def normalize_features(X):
normalize(X, axis=0)
def train(X, y):
svm = SVC(C = 1000, kernel='rbf')
#svm = SVC(kernel='linear', class_weight='auto', tol=1e-2)
svm.fit(X, y)
return svm
def test(svm, X):
return svm.predict(X)
# converts a list of dictionaries to a
# scipy sparse CSR matrix, given a key id map
# If keys are already integers, please
# set the length of the ids
def dictListToCSR(listDict, keyIdMap = None, idLen = None):
# Create the appropriate format for the COO format.
assert(keyIdMap != None or idLen != None)
featureLength = len(listDict)
data = []
i = []
j = []
if idLen == None: idLen = len(keyIdMap)
if keyIdMap == None:
keyId = lambda x: x
else:
keyId = lambda x: keyIdMap[x]
# A[i[k], j[k]] = data[k]
for x in range(featureLength):
for key in listDict[x]:
i.append(x)
j.append(keyId(key))
data.append(listDict[x][key])
# Create the COO-matrix
coo = coo_matrix((data, (i, j)), shape = (featureLength, idLen))
return csr_matrix(coo, dtype = np.float64)
# maps all keys in an iterable of dictionaries to integer id's so
# the list of dictionaries can be converted to sparse CSR format
def getKeyIds(listDict):
allKeys = set()
for dictionary in listDict:
for key in dictionary:
allKeys.add(key)
allKeys = list(allKeys)
keyIdMap = {}
for i in range(len(allKeys)):
keyIdMap[allKeys[i]] = i
return keyIdMap
if __name__ == "__main__":
""" General Testing Paramaters """
thres = .75
num = 10
y = compile_targets('../dataset/small_small_train.txt', threshold = thres)
actual = compile_targets('../dataset/small_small_test.txt', threshold = thres)
# """ tf-idf """
# X, idsLength = tf.tfidf('random_train2.txt')
# X = dictListToCSR(X, idLen = idsLength)
# # Xp = tf.tfidf('random_test.txt')
# svm = train(X, y)
# predictions = test(svm, X)
# predCount = np.bincount(predictions)
# actualCount = np.bincount(actual)
# comparedCount = np.bincount(predictions + actual)
# if len(predCount) == 1: predCount = np.append(predCount, 0)
# if len(comparedCount) == 2: comparedCount = np.append(comparedCount, 0)
# precision = comparedCount[2] / predCount[1]
# recall = comparedCount[2] / actualCount[1]
# accuracy = (comparedCount[0] + comparedCount[2]) / len(predictions)
# print "Tf-idf Testing: "
# print "Accuracy: " + "{:.2%}".format(accuracy)
# print "Precision: " + "{:.2%}".format(precision)
# print "Recall: " + "{:.2%}".format(recall)
''' Bigram Testing: perplexities only'''
model = bigram.ClassifyEssays(lamb = .03, eps = 1e-6)
model.buildNgram("../dataset/small_small_train.txt", threshold = thres, num = num)
perplexities, bigrams = model.classify("../dataset/small_small_train.txt")
testPerplexities, testBigrams = model.classify("../dataset/small_small_test.txt")
X = perplexities
Xp = testPerplexities
svm = train(X, y)
predictions = test(svm, Xp)
predCount = np.bincount(predictions)
actualCount = np.bincount(actual)
comparedCount = np.bincount(predictions + actual)
print predCount
print actualCount
if len(predCount) == 1: predCount = np.append(predCount, 0)
if len(comparedCount) == 2: comparedCount = np.append(comparedCount, 0)
precision = comparedCount[2] / predCount[1]
recall = comparedCount[2] / actualCount[1]
accuracy = (comparedCount[0] + comparedCount[2]) / len(predictions)
print "Bigram Testing: perplexities only: "
print "Accuracy: " + "{:.2%}".format(accuracy)
print "Precision: " + "{:.2%}".format(precision)
print "Recall: " + "{:.2%}".format(recall)
''' Bigram Testing: full bigram vectors'''
keyIdMap = getKeyIds(itertools.chain(bigrams, testBigrams))
X = dictListToCSR(bigrams, keyIdMap = keyIdMap)
Xp = dictListToCSR(testBigrams, keyIdMap = keyIdMap)
svm = train(X, y)
predictions = test(svm, Xp)
predCount = np.bincount(predictions)
actualCount = np.bincount(actual)
print predCount
print actualCount
comparedCount = np.bincount(predictions + actual)
if len(predCount) == 1: predCount = np.append(predCount, 0)
if len(comparedCount) == 2: comparedCount = np.append(comparedCount, 0)
precision = comparedCount[2] / predCount[1]
recall = comparedCount[2] / actualCount[1]
accuracy = (comparedCount[0] + comparedCount[2]) / len(predictions)
print "Bigram Testing: full bigram vectors: "
print "Accuracy: " + "{:.2%}".format(accuracy)
print "Precision: " + "{:.2%}".format(precision)
print "Recall: " + "{:.2%}".format(recall)