-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAssignment6_SanjayKPattanayak_Final.py
More file actions
134 lines (103 loc) · 3.44 KB
/
Assignment6_SanjayKPattanayak_Final.py
File metadata and controls
134 lines (103 loc) · 3.44 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
# coding: utf-8
# In[70]:
from IPython.core.interactiveshell import InteractiveShell
InteractiveShell.ast_node_interactivity = "all"
import csv
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.model_selection import cross_validate
from sklearn.naive_bayes import MultinomialNB
from sklearn.model_selection import train_test_split
from sklearn.metrics import precision_recall_fscore_support
from sklearn.metrics import classification_report
from sklearn.model_selection import GridSearchCV
from sklearn.pipeline import Pipeline
from sklearn import svm
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
# In[ ]:
print("Solution for Question 1:\n")
with open("amazon_review_300.csv", "r") as f:
reader=csv.reader(f, delimiter=',')
rows=[(row[1][2],row[1][0]) for row in enumerate(reader)]
text,target=zip(*rows)
text=list(text)
target=list(target)
tfidf_vect = TfidfVectorizer(stop_words="english")
dtm= tfidf_vect.fit_transform(text)
metrics = ['precision_macro', 'recall_macro', "f1_macro"]
clf = MultinomialNB()
cv = cross_validate(clf, dtm, target, scoring=metrics, cv=6)
print("Test data set average precision:")
print(cv['test_precision_macro'])
print("\nTest data set average recall:")
print(cv['test_recall_macro'])
print("\nTest data set average fscore:")
print(cv['test_f1_macro'])
print("\nTrain data set average fscore:")
print(cv['train_f1_macro'])
# In[ ]:
print("Solution for Question 2:\n")
text_clf = Pipeline([('tfidf', TfidfVectorizer()),
('clf', MultinomialNB())
])
parameters = {'tfidf__min_df':[1,2,3,5],
'tfidf__stop_words':[None,"english"],
'clf__alpha': [0.5,1.0,1.5,2.0],
}
metric = "f1_macro"
gs_clf = GridSearchCV(text_clf, param_grid=parameters, scoring=metric, cv=6)
gs_clf = gs_clf.fit(text, target)
for param_name in gs_clf.best_params_:
print(param_name,": ",gs_clf.best_params_[param_name])
print("best f1 score:", gs_clf.best_score_)
# In[ ]:
print("Solution for Question 3:\n")
with open("amazon_review_large.csv", "r") as f:
reader=csv.reader(f, delimiter=',')
rows=[(row[1][1],row[1][0]) for row in enumerate(reader)]
df=[]
i=400
while i<=20000:
text,target=zip(*rows[0:i])
text=list(text)
target=list(target)
tfidf_vect = TfidfVectorizer(stop_words="english")
dtm= tfidf_vect.fit_transform(text)
metrics = ['precision_macro', 'recall_macro', "f1_macro"]
clf = svm.LinearSVC()
cv = cross_validate(clf, dtm, target, scoring=metrics, cv=5)
x=(np.mean(np.array(cv['test_f1_macro'])))
y=(i,x)
df.append(y)
i+=400
#df
df1=[]
i=400
while i<=20000:
text,target=zip(*rows[0:i])
text=list(text)
target=list(target)
tfidf_vect = TfidfVectorizer(stop_words="english")
dtm= tfidf_vect.fit_transform(text)
metrics = ['precision_macro', 'recall_macro', "f1_macro"]
clf = MultinomialNB()
cv = cross_validate(clf, dtm, target, scoring=metrics, cv=10)
x=(np.mean(np.array(cv['test_f1_macro'])))
y=(i,x)
df1.append(y)
i+=400
#df1
dfdf = pd.DataFrame(df, columns=['SampleSize','AvgF1'])
print("SVM Classifier")
print(dfdf)
dfdf1 = pd.DataFrame(df1, columns=['SampleSize','AvgF1'])
print("Naive Bayes Classifier\n")
print(dfdf1)
# In[ ]:
print("SVM Classifier Plot\n")
plt.plot(dfdf.SampleSize,dfdf.AvgF1);
# In[ ]:
print("Naive-Bayes Classifier Plot\n")
plt.plot(dfdf1.SampleSize,dfdf1.AvgF1);