-
Notifications
You must be signed in to change notification settings - Fork 1
/
TextFeatures.py
350 lines (318 loc) · 10.2 KB
/
TextFeatures.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
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
import time
start=time.time()
import pickle
import pandas as pd
import math
from nltk.tokenize import word_tokenize
# Loading of Text Transcripts of Dataset
df=pd.read_csv("C:/MyData/PythonPractice/Speech_CMU-MOSI/original_transcripts.csv",encoding='ISO-8859-1')
#print(df.columns.tolist())
#filename=df[['FileName']] # extracting only the filenames
#fileID=df[['FileID']] # extracting only the fileids
#utterance=df[['Utterance']] # extracting only utterances
#utterancelist=[]
#for row in utterance.iterrows():
# index, data = row
# utterancelist.append(data.tolist()[0]) # data.tolist() gives value [[1],[0],...] so we just need the label
#
##print(utterancelist)
#print(len(utterancelist)) #2199
#
#filename = 'utterances.pickle'
#outfile = open(filename,'wb')
#pickle.dump(utterancelist,outfile)
#outfile.close()
#seq=df[['SeqNo']] # extracting only the sequence numbers
#label=df[['Label']] # extracting only the sentiment labels
#
##print(type(label)) #dataframe
#
#print(len(filename)) #Total no of utterances in dataset
#N=len(filename)
#
#seqlist=list(set(df.SeqNo)) # sequence of series type
#print(seqlist) #Unique set of sequence numbers
#
#
##sentiment_labels=[] # converts rows of data frame to list
##
##for row in label.iterrows():
## index, data = row
## sentiment_labels.append(data.tolist()[0]) # data.tolist() gives value [[1],[0],...] so we just need the label
##
##print(sentiment_labels)
###print(len(temp)) #2199
#
#u=df.Utterance
#utterances=[]
#for x in u:
# utterances.append(x)
#print(utterances) #Unique set of file names
#print(len(utterances))
#
## BAG OF WORDS
#global_unique_tokens=[]
#
##for i in range(0,2):
#for i in range(len(utterances)):
# doc=utterances[i]
# allwords = word_tokenize(doc)
# allwords=[word.lower() for word in allwords if word.isalpha()]
## print(allwords)
# unique_tokens = []
# for x in allwords:
# if x not in unique_tokens:
# unique_tokens.append(x)
# global_unique_tokens.append(x)
## print(unique_tokens)
##print(global_unique_tokens)
#
#BOW=[]
#for x in global_unique_tokens:
# if x not in BOW:
# BOW.append(x)
#print(" Bag of Words: ")
#print(BOW)
#print(len(BOW))
## CALCULATION OF IDF VALUES
#
## IDF= log(N/n) N : NUMBER OF DOCUMENTS/ Sentences n : NUMBER OF DOCUMENTS A TERM HAS APPEARED IN
#
## n : NUMBER OF DOCUMENTS A TERM HAS APPEARED IN
##
##count=[]
##for k in range(len(BOW)):
## x=0
## for i in range(len(utterances)):
##
## doc=utterances[i]
## allwords = word_tokenize(doc)
## allwords=[word.lower() for word in allwords if word.isalpha()]
### print(allwords)
##
## if BOW[k] in allwords:
## x=x+1
## count.append(x)
##print(count)
##print(len(count))
##ndict=dict(zip(BOW,count))
##print(ndict)
##
##IDF=[]
##for i in range(len(BOW)):
## x=math.log10(N/(count[i]))
## x=round(x,3)
## IDF.append(x)
##print("\n Pair wise --(Words,IDF Values):" )
##print(IDF)
##print(len(IDF))
##IDFdict=dict(zip(BOW,IDF))
##print(IDFdict)
#
#
##filename = 'simple_IDF.pickle'
##outfile = open(filename,'wb')
##pickle.dump(IDFdict,outfile)
##outfile.close()
#
#filename='C:/Users/srish/Dropbox/DTU/Research/4 May 19/simple_IDF.pickle'
#infile = open(filename,'rb')
#IDFdict = pickle.load(infile, encoding='latin1')
#infile.close()
#print(IDFdict)
#global_TF_Matrix=[]
#global_TF_IDF_Matrix=[]
#
#
#for i in range(len(utterances)):
##for i in range(0,2):
## print(utterances[i])
# doc=utterances[i]
## print(doc)
# allwords = word_tokenize(doc)
# allwords=[word.lower() for word in allwords if word.isalpha()]
## print(allwords)
#
# unique_tokens = []
# for x in allwords:
# if x not in unique_tokens:
# unique_tokens.append(x)
#
# wordfreq = [] # NUMBER OF TIMES A TERM APPEAR IN EACH SENTENCE
# # len(uniquetokens) # NUMBER OF TERMS IN EACH REVIEW
#
# for w in allwords:
# wordfreq.append(allwords.count(w))
## print("\n Pair wise --(Words,Frequences):" )
## print(list(zip(allwords, wordfreq)))
## print("\n Number of times a term appear :")
## print(wordfreq)
#
# # TF for each term
# TF=[]
# for j in range(len(allwords)):
# x=((wordfreq[j])/(len(unique_tokens)))
# x=round(x,3)
# TF.append(x)
## print("\n TF values : ")
## print(TF)
#
## print("\n Pair wise --(Words,TF Values):" )
# TFdict=dict(zip(allwords, TF))
## print(TFdict)
#
# TF_Matrix=[]
# TFrow=[]
# for k in range(len(BOW)):
# if BOW[k] in allwords:
# TFrow.append(TFdict[BOW[k]])
# else:
# TFrow.append(0)
## print(TFrow)
# TF_Matrix.append(TFrow)
#
# TF_IDF_Matrix=[]
# TF_IDF_row=[]
# for k in range(len(BOW)):
# if BOW[k] in allwords:
# t=TFdict[BOW[k]]*IDFdict[BOW[k]]
# TF_IDF_row.append(round(t,3))
# else:
# TF_IDF_row.append(0)
## print(TF_IDF_row)
# TF_IDF_Matrix.append(TF_IDF_row)
#
## print("\n TF MATRIX :" +str(TF_Matrix))
## print(len(TF_Matrix))
## print("\n TF-IDF MATRIX: " +str(TF_IDF_Matrix))
## print(len(TF_IDF_Matrix))
#
# global_TF_Matrix.append(TFrow)
# global_TF_IDF_Matrix.append(TF_IDF_row)
#
##print("\n Global TF MATRIX :" +str(global_TF_Matrix))
#print(len(global_TF_Matrix))
##print("\n Global TF-IDF MATRIX :" +str(global_TF_IDF_Matrix))
#print(len(global_TF_IDF_Matrix))
#
#textfeatures=global_TF_IDF_Matrix
#import pickle
#filename = 'textfeatures_TF-IDF_normalize.pickle'
#outfile = open(filename,'wb')
#pickle.dump(global_TF_IDF_Matrix,outfile)
#outfile.close()
###### COLUMN WISE ( FEATURE WISE) NORMALIZATION
#filename='C:/Users/srish/Dropbox/DTU/Research/4 May 19/textfeatures_TF-IDF_simple.pickle'
#infile = open(filename,'rb')
#textfeatures = pickle.load(infile, encoding='latin1')
#infile.close()
#print(textfeatures)
#
#rowsize=len(textfeatures)
##print(rowsize) #2199
#colsize=len(textfeatures[0])
##print(colsize) #3079
#
##Transpose the TextFeatures Matrix for columnwise normalization
#newtextfeatures = [[textfeatures[j][i] for j in range(len(textfeatures))] for i in range(len(textfeatures[0]))]
#
#newrowsize=len(newtextfeatures)
##print(newrowsize) #3079
#newcolsize=len(newtextfeatures[0])
##print(newcolsize) #2199
#
##import csv
#
#datacol1=newtextfeatures[0] # 1st BOW feature list
#norm = [(round((i- min(datacol1))/(max(datacol1)-min(datacol1)),3)) for i in datacol1]
#print(norm)
#
#normalized_data=[]
#
#for j in range(colsize):
# datacol1=newtextfeatures[j] # 1st BOW feature list
# norm = [(round((i- min(datacol1))/(max(datacol1)-min(datacol1)),3)) for i in datacol1]
## print(norm)
# normalized_data.append(norm)
#
##Transpose it back
#finalnormalizedfeatures = [[normalized_data[j][i] for j in range(len(normalized_data))] for i in range(len(normalized_data[0]))]
#
#filename = 'textfeatures_normalized.pickle' #Save Text features in pickle file
#outfile = open(filename,'wb')
#pickle.dump(finalnormalizedfeatures,outfile)
#outfile.close()
filename='C:/Users/..../textfeatures_normalized.pickle' # Path of Textfeatures pickle file
infile = open(filename,'rb')
textfeatures = pickle.load(infile, encoding='latin1')
infile.close()
#print(textfeatures)
filename='C:/Users/.../sentimentlabels_simple.pickle' #Path of Sentiment Label pickle file
infile = open(filename,'rb')
sentiment_labels = pickle.load(infile, encoding='latin1')
infile.close()
#print(sentiment_labels)
#
################# SVM CLASSIFIER ###################
### Import train_test_split function
from sklearn.model_selection import train_test_split
accuracy=[]
precision=[]
recall=[]
fscore1=[]
fscore2=[]
t=10 # Number of folds for:- Cross Validation
for i in range(0,t):
print(i+1)
# Split dataset into training set and test set # 70% training and 30% test
X_train, X_test, y_train, y_test = train_test_split(textfeatures, sentiment_labels, test_size=0.3)
#Import svm model
from sklearn import svm
#Create a svm Classifier
clf = svm.SVC(kernel='linear') # Linear Kernel
#Train the model using the training sets
clf.fit(X_train, y_train)
# #decision function
decision=clf.decision_function(X_test) # size= size of textfeatures
filename = 'TextConfidenceScore.pickle' # Text Confidence Score
outfile = open(filename,'wb')
pickle.dump(decision,outfile)
outfile.close()
filename = 'Text_TrueLabels.pickle'
outfile = open(filename,'wb')
pickle.dump(y_test,outfile)
outfile.close()
#Predict the response for test dataset
y_pred = clf.predict(X_test)
filename = 'Text_PredictedLabels.pickle'
outfile = open(filename,'wb')
pickle.dump(y_pred,outfile)
outfile.close()
#Import scikit-learn metrics module for accuracy calculation
from sklearn import metrics
# Model Accuracy: how often is the classifier correct?
acc=metrics.accuracy_score(y_test, y_pred)
print("Accuracy:",acc)
# Model Precision: what percentage of positive tuples are labeled as such?
prec=metrics.precision_score(y_test, y_pred, average='macro')
print("Precision:",prec)
# Model Recall: what percentage of positive tuples are labelled as such?
re=metrics.recall_score(y_test, y_pred, average='macro')
print("Recall:", re)
# Model F1- Score:
f1=metrics.f1_score(y_test, y_pred, average='macro')
print("F1-Score:",f1)
accuracy.append(acc)
precision.append(prec)
recall.append(re)
fscore1.append(f1)
avg_accuracy=sum(accuracy)/t
print(" Avg Accuracy:",avg_accuracy*100)
avg_precision=round(sum(precision)/t,3)
print(" Avg Precision:",avg_precision)
avg_recall=round(sum(recall)/t,3)
print(" Avg Recall:",avg_recall)
avg_fscore1=round(sum(fscore1)/t,3)
print(" Avg F1-score :",avg_fscore1)
end=time.time()
print(str(end-start)+" secs")