-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathComparisonSystem.py
More file actions
214 lines (131 loc) · 6.01 KB
/
ComparisonSystem.py
File metadata and controls
214 lines (131 loc) · 6.01 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
# -*- coding: utf-8 -*-
"""
Created on Tue Apr 2 10:56:37 2019
@author: Mathew
"""
# Importing the libraries
import PySimpleGUI as sg
from sklearn import metrics
import pandas as pd
from nltk.corpus import stopwords
from sklearn.naive_bayes import MultinomialNB
from sklearn.model_selection import train_test_split
from nltk.stem import WordNetLemmatizer
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.ensemble import RandomForestClassifier
import re
from sklearn import svm
import time
# Importing the dataset
#sg.PopupOK('Please select csv')
#amazon = pd.read_csv('C:\\Users\\lenovo\\Desktop\\code\\10kreviews.csv')
csv_loc = sg.PopupGetFile('Please enter a dataset')
amazon = pd.read_csv(csv_loc)
#Removing null entries
amazon.isnull().sum()
amazon = amazon.fillna(' ')
amazon.shape
# Text Length
amazon['text length'] = amazon['reviewText'].apply(len)
# Creating a class with only 5 and 1 stars
amazon = amazon[(amazon['overall'] == 1) | (amazon['overall'] == 5)]
# Generating X and Y coordinates
X = amazon['reviewText']
y = amazon['overall']
# Resetting key values
X = X.reset_index(drop=True)
y = y.reset_index(drop=True)
# Data Preprocessing
documents = []
stemmer = WordNetLemmatizer()
for sen in range(0, len(X)):
# Remove all the special characters
document = re.sub(r'\W', ' ', str(X[sen]))
# remove all single characters
document = re.sub(r'\s+[a-zA-Z]\s+', ' ', document)
# Remove single characters from the start
document = re.sub(r'\^[a-zA-Z]\s+', ' ', document)
# Substituting multiple spaces with single space
document = re.sub(r'\s+', ' ', document, flags=re.I)
# Removing prefixed 'b'
document = re.sub(r'^b\s+', '', document)
# Converting to Lowercase
document = document.lower()
# Lemmatization
document = document.split()
document = [stemmer.lemmatize(word) for word in document]
document = ' '.join(document)
documents.append(document)
#TFIDF Vectorization
tfidfconverter = TfidfVectorizer(max_features=1500, min_df=5, max_df=0.7, stop_words=stopwords.words('english'))
X = tfidfconverter.fit_transform(documents).toarray()
# Split Dataset into training and testing
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=101)
# The callback functions
def button1():
Smilli = int(round(time.time() * 1000))
# Training and Testing
nb = MultinomialNB()
nb.fit(X_train, y_train)
# Predicting sentiment
preds = nb.predict(X_test)
# Print the Results
Emilli = int(round(time.time() * 1000))
ntime = Emilli-Smilli
accuracy = round(metrics.accuracy_score(y_test, preds)*100,2)
precision = round(metrics.precision_score(y_test, preds, average='weighted')*100,2)
recall = round(metrics.recall_score(y_test, preds, average='weighted')*100,2)
f1score = round(metrics.f1_score(y_test, preds, average='weighted')*100,2)
sg.PopupOK('Naive Bayes Results : \n accuracy:', str(accuracy) + '%' ,'\n precision:', str(precision) + '%' ,'\n recall:', str(recall) + '%' ,'\n F-measure:', str(f1score) + '%' ,'\n Computation Time:',str(ntime) + ' ms')
def button2():
Smilli = int(round(time.time() * 1000))
# Training the model
classifier = RandomForestClassifier(n_estimators=1000, random_state=0)
classifier.fit(X_train, y_train)
# Predicting sentiment
y_pred = classifier.predict(X_test)
Emilli = int(round(time.time() * 1000))
ntime = Emilli-Smilli
accuracy = round(metrics.accuracy_score(y_test, y_pred)*100,2)
precision = round(metrics.precision_score(y_test, y_pred, average='weighted')*100,2)
recall = round(metrics.recall_score(y_test, y_pred, average='weighted')*100,2)
f1score = round(metrics.f1_score(y_test, y_pred, average='weighted')*100,2)
# Print the Results
sg.PopupOK('Random Forest Results : \n accuracy:', str(accuracy) + '%' ,'\n precision:', str(precision) + '%' ,'\n recall:', str(recall) + '%' ,'\n F-measure:', str(f1score) + '%' ,'\n Computation Time:',str(ntime) + ' ms')
def button3():
Smilli = int(round(time.time() * 1000))
# Training the model
classifier = svm.SVC(kernel='linear', random_state=12345)
classifier.fit(X_train, y_train)
# Predicting sentiment
y_pred = classifier.predict(X_test)
Emilli = int(round(time.time() * 1000))
ntime = Emilli-Smilli
accuracy = round(metrics.accuracy_score(y_test, y_pred)*100,2)
precision = round(metrics.precision_score(y_test, y_pred, average='weighted')*100,2)
recall = round(metrics.recall_score(y_test, y_pred, average='weighted')*100,2)
f1score = round(metrics.f1_score(y_test, y_pred, average='weighted')*100,2)
# Print the Results
sg.PopupOK('SVM Results : \n accuracy:', str(accuracy) + '%' ,'\n precision:', str(precision) + '%' ,'\n recall:', str(recall) + '%' ,'\n F-measure:', str(f1score) + '%' ,'\n Computation Time:',str(ntime) + ' ms')
# Layout the design of the GUI
layout = [[sg.Text('Please select an algorithm: ', auto_size_text=True)],
[sg.Button('Naive Bayes'), sg.Button('Random Forest'), sg.Button('SVM'), sg.Quit()]]
# Show the Window to the user
window = sg.Window('Comparison System').Layout(layout)
def gui():
# Read the Window
event, value = window.Read()
# Take appropriate action based on button
if event == 'Naive Bayes':
button1()
gui()
elif event == 'Random Forest':
button2()
gui()
elif event == 'SVM':
button3()
gui()
elif event =='Quit' or event is None:
window.Close()
gui()
# All done!