-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSVM.py
More file actions
362 lines (317 loc) · 15.4 KB
/
SVM.py
File metadata and controls
362 lines (317 loc) · 15.4 KB
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
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
import codecs
import numpy as np
from sklearn.metrics import precision_recall_fscore_support
from sklearn.metrics import accuracy_score
from sklearn.metrics import precision_score
from sklearn.metrics import recall_score
from sklearn.metrics import f1_score
from sklearn import svm
from sklearn.model_selection import KFold
from sklearn.multiclass import OneVsRestClassifier
from sklearn.svm import LinearSVC
from sklearn.model_selection import train_test_split
from sklearn import preprocessing
from sklearn.linear_model import Ridge
from sklearn.model_selection import cross_val_score
from sklearn.model_selection import GridSearchCV
import pickle
from sklearn.metrics import classification_report
from sklearn.svm import SVC
import itertools
from sklearn.utils import shuffle
#read preprocessed data from local
with open('./Pickle_Data/citation_with_context_vec.pk', 'rb') as f:
vec_texts_with_context = pickle.load(f)
# print(texts_with_context)
with open('./Pickle_Data/pre_citation_with_context_vec.pk', 'rb') as f:
vec_pre_texts_with_context = pickle.load(f)
#
with open('./Pickle_Data/citation_vec.pk', 'rb') as f:
vec_texts = pickle.load(f)
# print(texts)
with open('./Pickle_Data/polarities.pk', 'rb') as f:
polarities = pickle.load(f)
# print(polarities)
with open('./Pickle_Data/purposes.pk', 'rb') as f:
purposes = pickle.load(f)
# print(purposes)
citation_X = vec_texts
citation_with_context_X = vec_texts_with_context
pre_citation_with_context_X = vec_pre_texts_with_context
polarity_Y = polarities
purpose_Y = purposes
#change to array
citation_X = np.asarray(citation_X)
citation_with_context_X = np.asarray(citation_with_context_X)
pre_citation_with_context_X = np.asarray(pre_citation_with_context_X)
polarity_Y = np.asarray(polarity_Y)
purpose_Y = np.asarray(purpose_Y)
#print(citation_X)
#print("------------Example of citations and its length:---------------")
#print(len(citation_X))
#print(citation_X[0])
#print("------------Example of citations with contexts and its length:------------")
#print(len(citation_with_context_X))
#change NaN element to 0
nan_element = []
#remove nan in data
for i in range(len(citation_X)):
sample=citation_X[i]
for j in range(len(sample)):
if np.isnan(sample[j]):
sample[j]=0
nan_element.append(i)
#break
# print(nan_element)
# for i in nan_element:
# citation_X = np.delete(citation_X,i,axis = 0)
# polarity_Y = np.delete(polarity_Y,i,axis = 0)
# purpose_Y = np.delete(purpose_Y,i,axis = 0)
for i in range(len(citation_with_context_X)):
sample=citation_with_context_X[i]
for j in range(len(sample)):
if np.isnan(sample[j]):
sample[j]=0
for i in range(len(pre_citation_with_context_X)):
sample = pre_citation_with_context_X[i]
for j in range(len(sample)):
if np.isnan(sample[j]):
sample[j] = 0
#shuffle the data
citation_with_context_X, polarity_Y, purpose_Y= shuffle(citation_with_context_X, polarity_Y,purpose_Y, random_state=0)
#Create svm model for label: polarity
# Split the dataset
X_train, X_test, y_train, y_test = train_test_split(citation_with_context_X, polarity_Y, test_size=0.1, random_state=10)
# Define different values for the hyperparameter optimization
kernel_list = ['rbf', 'linear']
c_list = [ 80, 85, 90, 95, 100]
g_list = [ 0.3, 0.4, 0.5, 0.75, 1, 10]
# Build cartesian product
configs = list(itertools.product(c_list, g_list,kernel_list))
current_best_f1 = 0.0
best_kernel = ""
best_c = None
best_g = None
for c, g, kernel in configs:
kf = KFold(n_splits=10, shuffle=False)
clf = svm.SVC(kernel=kernel, C=c, gamma=g)
fscores = []
current_f1 = 0
for k, (train, dev) in enumerate(kf.split(X_train, y_train)):
clf.fit(X_train[train], y_train[train])
result = clf.predict(X_train[dev])
fscores.append(f1_score(y_train[dev], result, average="macro"))
#print("[INFO] fold %s, score: %s " % (k, precision_recall_fscore_support(y_train[dev], result, average="macro" )))
print("[INFO] current kernel: %s, current c: %s, current g: %s " % (kernel, c, g))
current_f1 = np.mean(fscores)
print("[INFO] Current average fscore: %s" %(current_f1))
if(current_f1 > current_best_f1):
current_best_f1 = current_f1
best_c = c
best_g = g
best_kernel = kernel
print(best_kernel)
print(best_g)
print(best_c)
print(current_best_f1)
#Test on test data set
clf = svm.SVC(kernel=best_kernel, C=best_c, gamma=best_g)
clf.fit(X_train, y_train)
result = clf.predict(X_test)
print(precision_recall_fscore_support(y_test, result, average="macro" ))
# Use cross validation to evaluate the model on all data (Train and test)
kf = KFold(n_splits=10, shuffle=False)
clf = svm.SVC(kernel=best_kernel, C=best_c, gamma=best_g)
accuracy_scores = []
precision_scores = []
recall_scores =[]
fscores = []
for k, (train, test) in enumerate(kf.split(citation_with_context_X, polarity_Y)):
clf.fit(citation_with_context_X[train], polarity_Y[train])
result = clf.predict(citation_with_context_X[test])
accuracy_scores.append(accuracy_score(polarity_Y[test], result))
precision_scores.append(precision_score(polarity_Y[test], result, average="macro"))
recall_scores.append(recall_score(polarity_Y[test], result, average="macro"))
fscores.append(f1_score(polarity_Y[test], result, average="macro"))
print("[INFO] fold %s, score: %s " % (k, precision_recall_fscore_support(polarity_Y[test], result, average="macro" )))
print("Accuracy mean: %s, std. deviation: %s" %(np.mean(accuracy_scores)*100.0,np.std(accuracy_scores)*100.0))
print("precision_scores mean: %s, std. deviation: %s" %(np.mean(precision_scores)*100.0,np.std(precision_scores)*100.0))
print("recall_scores mean: %s, std. deviation: %s" %(np.mean(recall_scores)*100.0,np.std(recall_scores)*100.0))
print("fscores mean: %s, std. deviation: %s" %(np.mean(fscores)*100.0,np.std(fscores)*100.0))
#Create svm model for label: purpose
# Split the dataset
X_train, X_test, y_train, y_test = train_test_split(citation_with_context_X, purpose_Y, test_size=0.1, random_state=10)
# Define different values for the hyperparameter optimization
kernel_list = ['rbf', 'linear']
c_list = [ 80, 85, 90, 95,100]
g_list = [ 0.3, 0.4, 0.5, 0.75, 1, 10]
# Build cartesian product
configs = list(itertools.product(c_list, g_list,kernel_list))
current_best_f1 = 0.0
best_kernel = ""
best_c = None
best_g = None
for c, g, kernel in configs:
kf = KFold(n_splits=10, shuffle=False)
clf = svm.SVC(kernel=kernel, C=c, gamma=g)
fscores = []
current_f1 = 0
for k, (train, dev) in enumerate(kf.split(X_train, y_train)):
clf.fit(X_train[train], y_train[train])
result = clf.predict(X_train[dev])
fscores.append(f1_score(y_train[dev], result, average="macro"))
#print("[INFO] fold %s, score: %s " % (k, precision_recall_fscore_support(y_train[dev], result, average="macro" )))
print("[INFO] current kernel: %s, current c: %s, current g: %s " % (kernel, c, g))
current_f1 = np.mean(fscores)
print("[INFO] Current average fscore: %s" %(current_f1))
if(current_f1 > current_best_f1):
current_best_f1 = current_f1
best_c = c
best_g = g
best_kernel = kernel
print(best_kernel)
print(best_g)
print(best_c)
print(current_best_f1)
#Test on test data set
clf = svm.SVC(kernel=best_kernel, C=best_c, gamma=best_g)
clf.fit(X_train, y_train)
result = clf.predict(X_test)
print(precision_recall_fscore_support(y_test, result, average="macro" ))
# Use cross validation to evaluate the model on all data (Train and test)
kf = KFold(n_splits=10, shuffle=False)
clf = svm.SVC(kernel=best_kernel, C=best_c, gamma=best_g)
accuracy_scores = []
precision_scores = []
recall_scores =[]
fscores = []
for k, (train, test) in enumerate(kf.split(citation_with_context_X, purpose_Y)):
clf.fit(citation_with_context_X[train], purpose_Y[train])
result = clf.predict(citation_with_context_X[test])
accuracy_scores.append(accuracy_score(purpose_Y[test], result))
precision_scores.append(precision_score(purpose_Y[test], result, average="macro"))
recall_scores.append(recall_score(purpose_Y[test], result, average="macro"))
fscores.append(f1_score(purpose_Y[test], result, average="macro"))
print("[INFO] fold %s, score: %s " % (k, precision_recall_fscore_support(purpose_Y[test], result, average="macro" )))
print("Accuracy mean: %s, std. deviation: %s" %(np.mean(accuracy_scores)*100.0,np.std(accuracy_scores)*100.0))
print("precision_scores mean: %s, std. deviation: %s" %(np.mean(precision_scores)*100.0,np.std(precision_scores)*100.0))
print("recall_scores mean: %s, std. deviation: %s" %(np.mean(recall_scores)*100.0,np.std(recall_scores)*100.0))
print("fscores mean: %s, std. deviation: %s" %(np.mean(fscores)*100.0,np.std(fscores)*100.0))
#test
#Backup: old models
# # train classifier svm
# print("------SVM model: svm.LinearSVC() with Kfold. input: vector of each citation, label: polarities-------")
# kf = KFold(n_splits=10, shuffle=False)
# #clf = OneVsRestClassifier(svm.SVC(kernel='linear'))
# #clf = svm.LinearSVC()
# clf = svm.SVC(C=100.0, decision_function_shape='ovo', kernel='linear')
# accuracy_scores = []
# precision_scores = []
# recall_scores =[]
# fscores = []
# for k, (train, test) in enumerate(kf.split(citation_with_context_X, polarity_Y)):
# clf.fit(citation_with_context_X[train], polarity_Y[train])
# result = clf.predict(citation_with_context_X[test])
# accuracy_scores.append(accuracy_score(polarity_Y[test], result))
# precision_scores.append(precision_score(polarity_Y[test], result, average="macro"))
# recall_scores.append(recall_score(polarity_Y[test], result, average="macro"))
# fscores.append(f1_score(polarity_Y[test], result, average="macro"))
# print("[INFO] fold %s, score: %s " % (k, precision_recall_fscore_support(polarity_Y[test], result, average="macro" )))
#
# print("Accuracy mean: %s, std. deviation: %s" %(np.mean(accuracy_scores)*100.0,np.std(accuracy_scores)*100.0))
# print("precision_scores mean: %s, std. deviation: %s" %(np.mean(precision_scores)*100.0,np.std(precision_scores)*100.0))
# print("recall_scores mean: %s, std. deviation: %s" %(np.mean(recall_scores)*100.0,np.std(recall_scores)*100.0))
# print("fscores mean: %s, std. deviation: %s" %(np.mean(fscores)*100.0,np.std(fscores)*100.0))
# # train classifier svm
# print("------SVM model: svm.LinearSVC() with Kfold. input: vector of each citation, label: purpose-------")
# kf = KFold(n_splits=10, shuffle=False)
# #clf = OneVsRestClassifier(svm.SVC(kernel='linear'))
# #clf = svm.LinearSVC()
# clf = svm.SVC(C=100.0, decision_function_shape='ovo', kernel='linear')
# accuracy_scores = []
# precision_scores = []
# recall_scores =[]
# fscores = []
# for k, (train, test) in enumerate(kf.split(citation_with_context_X, purpose_Y)):
# clf.fit(citation_with_context_X[train], purpose_Y[train])
# result = clf.predict(citation_with_context_X[test])
# accuracy_scores.append(accuracy_score(purpose_Y[test], result))
# precision_scores.append(precision_score(purpose_Y[test], result, average="macro"))
# recall_scores.append(recall_score(purpose_Y[test], result, average="macro"))
# fscores.append(f1_score(purpose_Y[test], result, average="macro"))
# print("[INFO] fold %s, score: %s " % (k, precision_recall_fscore_support(purpose_Y[test], result, average="macro" )))
# print("Accuracy mean: %s, std. deviation: %s" %(np.mean(accuracy_scores)*100.0,np.std(accuracy_scores)*100.0))
# print("precision_scores mean: %s, std. deviation: %s" %(np.mean(precision_scores)*100.0,np.std(precision_scores)*100.0))
# print("recall_scores mean: %s, std. deviation: %s" %(np.mean(recall_scores)*100.0,np.std(recall_scores)*100.0))
# print("fscores mean: %s, std. deviation: %s" %(np.mean(fscores)*100.0,np.std(fscores)*100.0))
#
# clf = svm.SVC(kernel='linear', C=100)
# scores = cross_val_score(clf, citation_with_context_X, polarity_Y, cv=10, scoring="recall_macro")
# print(scores)
# print(scores.mean())
# print(scores.std())
# grid_param = [{'kernel': ['rbf'], 'gamma': [1e-3, 1e-4], 'C': [1, 10, 100, 1000]},
# {'kernel': ['linear'], 'C': [1, 10, 100, 1000]}]
# gd_sr = GridSearchCV(estimator=svm.SVC(), param_grid=grid_param)
# gd_sr.fit(citation_with_context_X, polarity_Y)
# print('Best score for data1:', gd_sr.best_score_)
# print('Best C:',gd_sr.best_estimator_.C)
# print('Best Kernel:',gd_sr.best_estimator_.kernel)
# print('Best Gamma:',gd_sr.best_estimator_.gamma)
# ParaC = np.array([1,0.1,0.01,0.001,0.0001,10, 100, 1000])
# # create and fit a ridge regression model, testing each alpha
# model = svm.LinearSVC()
# grid = GridSearchCV(estimator=model, param_grid=dict(C=ParaC))
# grid.fit(citation_with_context_X[train], polarity_Y[train])
# print(grid)
# # summarize the results of the grid search
# print(grid.best_score_)
# print(grid.best_estimator_.C)
# x_train1, x_test1, y_train1, y_test1 = train_test_split(citation_X, polarity_Y, random_state=0, train_size=0.9)
# x_train2, x_test2, y_train2, y_test2 = train_test_split(citation_with_context_X, polarity_Y, random_state=0, train_size=0.9)
# x_train3, x_test3, y_train3, y_test3 = train_test_split(pre_citation_with_context_X, polarity_Y, random_state=0, train_size=0.9)
# print("------SVM model: svm.LinearSVC(). input: vector of each citation, label: polarities-------")
# clf.fit(x_train1,y_train1)
# result = clf.predict(x_test1)
# print(precision_recall_fscore_support(y_test1, result, average="macro"))
# #
# # one vs the rest
# print("------SVM model: OneVsRestClassifier. input: vector of each citation, label: polarities-------")
# result = OneVsRestClassifier(svm.SVC(kernel='linear')).fit(x_train1,y_train1).predict(x_test1)
# print(precision_recall_fscore_support(y_test1, result, average="macro"))
# #print(result2)
#
# print("------SVM model: svm.LinearSVC(). input: vector of each citation with its contexts, label: polarities-------")
# clf.fit(x_train2,y_train2)
# result2 = clf.predict(x_test2)
# print(precision_recall_fscore_support(y_test2, result2, average="macro"))
#
# # one vs the rest
# print("------SVM model: OneVsRestClassifier. input: vector of each citation with its contexts, label: polarities-------")
# result2 = OneVsRestClassifier(svm.SVC(kernel='linear')).fit(x_train2,y_train2).predict(x_test2)
# print(precision_recall_fscore_support(y_test2, result2, average="macro"))
# #print(result2)
#
# print("------SVM model: svm.LinearSVC(). input: vector of each citation with its contexts and with preprocessing, label: polarities-------")
# clf.fit(x_train3,y_train3)
# result3 = clf.predict(x_test3)
# print(precision_recall_fscore_support(y_test3, result3, average="macro"))
#
# # one vs the rest
# print("------SVM model: OneVsRestClassifier. input: vector of each citation with its contexts, label: polarities-------")
# result3 = OneVsRestClassifier(svm.SVC(kernel='linear')).fit(x_train3,y_train3).predict(x_test3)
# print(precision_recall_fscore_support(y_test3, result3, average="macro"))
# #label binarizer
# lb = preprocessing.LabelBinarizer()
# lb.fit([1,2,3])
# lb.classes_
# polarity_Y = lb.fit_transform(polarity_Y)
# #print(polarity_Y)
#
# # one vs the rest
# print("------SVM model: OneVsRestClassifier. input: vector of each citations, binarizer label: polarities-------")
# x_train1, x_test1, y_train1, y_test1 = train_test_split(citation_X, polarity_Y, random_state=0, train_size=0.8)
# model = OneVsRestClassifier(svm.SVC(kernel='linear'))
# model.fit(x_train1,y_train1)
# result = model.predict(x_test1)
# print(precision_recall_fscore_support(y_test1, result, average="macro"))