/
main.py
244 lines (194 loc) · 7.92 KB
/
main.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
import tkinter as tk
from tkinter import ttk
import tkinter.messagebox as tkmb
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import perceptron
import Adaline
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
################ LOAD DATA ###################
data = pd.read_csv('IrisData.txt')
def prepareData(F1, F2, C1, C2):
tempData = pd.DataFrame()
tempData[F1] = data[F1]
tempData[F2] = data[F2]
tempData['Class'] = data['Class']
removedClass = None
for x in tempData['Class'].unique():
if x != C1 and x != C2:
removedClass = x
break
tempData = tempData[tempData.Class != removedClass] # remove the third class from data
# split classes
class1 = tempData[tempData.Class != C2] #.sample(frac=1)
class2 = tempData[tempData.Class != C1] #.sample(frac=1)
# map classes into 1 and -1
class1.loc[:, ['Class']] = 1
class2.loc[:, ['Class']] = -1
# split train and test
x_train = class1.iloc[:30, :2]
x_train = x_train.append(class2.iloc[:30, :2])
y_train = class1.iloc[:30, 2]
y_train = y_train.append(class2.iloc[:30, 2])
x_test = class1.iloc[30:, :2]
x_test = x_test.append(class2.iloc[30:, :2])
y_test = class1.iloc[30:, 2]
y_test = y_test.append(class2.iloc[30:, 2])
return x_train, y_train, x_test, y_test
# Variables Operations
AllFeatures = list(data.columns[:len(data.columns) - 1])
AllClasses = list(data['Class'].unique())
################ GUI Creation ################
# parent window
parent = tk.Tk()
parent.geometry("300x450")
parent.title("Perceptron")
parent.resizable(0, 0)
# Select First Feature
row = 0
label = ttk.Label(parent, text="Select first feature:")
label.grid(column=0, row=row, padx=10, pady=10)
selection = tk.StringVar()
firstFeatureCB = ttk.Combobox(parent, textvariable=selection, width=15)
firstFeatureCB['values'] = tuple(AllFeatures)
firstFeatureCB['state'] = 'readonly'
firstFeatureCB.grid(column=1, row=row, padx=10, pady=10)
def MaintainFeaturesList(e):
tempFeaturesList = [*AllFeatures]
tempFeaturesList.remove(firstFeatureCB.get())
secondFeatureCB.set("")
secondFeatureCB['values'] = tuple(tempFeaturesList)
# when the first comboBox is selected, maintain features list for the second one
firstFeatureCB.bind('<<ComboboxSelected>>', MaintainFeaturesList)
# Select Second Feature
row = 1
label = ttk.Label(parent, text="Select Second feature:")
label.grid(column=0, row=row, padx=10, pady=10)
selection2 = tk.StringVar()
secondFeatureCB = ttk.Combobox(parent, textvariable=selection2, width=15)
secondFeatureCB['state'] = 'readonly'
secondFeatureCB.grid(column=1, row=row, padx=10, pady=10)
# visualize features
def visualize():
if firstFeatureCB.get() != "" and secondFeatureCB.get() != "":
# prepare data to be visualized
firstFeatureIndex = AllFeatures.index(firstFeatureCB.get())
secondFeatureIndex = AllFeatures.index(secondFeatureCB.get())
X1 = data.iloc[:50, firstFeatureIndex]
Y1 = data.iloc[:50, secondFeatureIndex]
X2 = data.iloc[50:100, firstFeatureIndex]
Y2 = data.iloc[50:100, secondFeatureIndex]
X3 = data.iloc[100:150, firstFeatureIndex]
Y3 = data.iloc[100:150, secondFeatureIndex]
plt.figure("Data visualization")
plt.scatter(X1, Y1)
plt.scatter(X2, Y2)
plt.scatter(X3, Y3)
plt.xlabel(firstFeatureCB.get())
plt.ylabel(secondFeatureCB.get())
plt.show()
else:
tkmb.showinfo("Missing Data", "Select 2 features")
row = 2
visualizeButton = ttk.Button(parent, text="Visualize", command=visualize)
visualizeButton.grid(column=0, row=row, padx=10, pady=10)
# Select First Class
row = 3
label = ttk.Label(parent, text="Select first class:")
label.grid(column=0, row=row, padx=10, pady=10)
selection3 = tk.StringVar()
firstClassCB = ttk.Combobox(parent, textvariable=selection3, width=15)
firstClassCB['values'] = tuple(AllClasses)
firstClassCB['state'] = 'readonly'
firstClassCB.grid(column=1, row=row, padx=10, pady=10)
def MaintainClassesList(e):
tempClassesList = [*AllClasses]
tempClassesList.remove(firstClassCB.get())
secondClassCB.set("")
secondClassCB['values'] = tuple(tempClassesList)
# when the first comboBox is selected, maintain classes list for the second one
firstClassCB.bind('<<ComboboxSelected>>', MaintainClassesList)
# Select Second class
row = 4
label = ttk.Label(parent, text="Select Second feature:")
label.grid(column=0, row=row, padx=10, pady=10)
selection4 = tk.StringVar()
secondClassCB = ttk.Combobox(parent, textvariable=selection4, width=15)
secondClassCB['state'] = 'readonly'
secondClassCB.grid(column=1, row=row, padx=10, pady=10)
# Enter learning rate
row = 5
label = ttk.Label(parent, text="Enter learning rate:")
label.grid(column=0, row=row, padx=10, pady=10)
learningRate_txt = ttk.Entry(parent, width=5)
learningRate_txt.grid(column=1, row=row, padx=10, pady=10)
# Enter no. of epochs
row = 6
label = ttk.Label(parent, text="Enter no. of epochs:")
label.grid(column=0, row=row, padx=10, pady=10)
epochsNum_txt = ttk.Entry(parent, width=5)
epochsNum_txt.grid(column=1, row=row, padx=10, pady=10)
# Enter MSE threshold
row = 7
label = ttk.Label(parent, text="Enter MSE threshold:")
label.grid(column=0, row=row, padx=10, pady=10)
MSE_Threshold_txt = ttk.Entry(parent, width=5)
MSE_Threshold_txt.grid(column=1, row=row, padx=10, pady=10)
# Bias checkbox
row = 8
isBiased = tk.IntVar()
checkBox = ttk.Checkbutton(parent, text="Use Bias", variable=isBiased)
checkBox.grid(column=0, row=row, padx=10, pady=10)
######################### Model #########################
def modelOperations(algorithm):
# if firstFeatureCB.get() != "" and \
# secondFeatureCB.get() != "" and \
# firstClassCB.get() != "" and \
# secondClassCB.get() != "" and \
# learningRate_txt.get() != "" and \
# epochsNum_txt.get() != "":
try:
# Prepare Data to be sent to the model
x_train, y_train, x_test, y_test = prepareData(firstFeatureCB.get(), secondFeatureCB.get(), firstClassCB.get(), secondClassCB.get())
# Data scaling
standard = StandardScaler()
standard.fit(x_train)
x_train = standard.transform(x_train)
standard.fit(x_test)
x_test = standard.transform(x_test)
# train then show drawing of plotted line
if algorithm == 'perceptron':
return np.array(x_train), np.array(y_train), isBiased.get(), float(learningRate_txt.get()), int(epochsNum_txt.get()), x_test, y_test
return np.array(x_train), np.array(y_train), isBiased.get(), float(learningRate_txt.get()), int(epochsNum_txt.get()), float(MSE_Threshold_txt.get()), x_test, y_test
# else:
except:
tkmb.showinfo("Missing Data", "Enter all data")
def perceptronModel():
try:
x_train, y_train, isBiased, learningRate, epochNum, x_test, y_test = modelOperations('perceptron')
W = perceptron.train(x_train, y_train, isBiased, learningRate, epochNum)
labels = [firstClassCB.get(), secondClassCB.get()]
perceptron.test(x_test, y_test, W, labels)
# show confusion matrix and accuracy
except:
pass
def adalineModel():
try:
x_train, y_train, isBiased, learningRate, epochNum, MSE_Threshold, x_test, y_test= modelOperations('adaline')
W = Adaline.train(x_train, y_train, isBiased, learningRate, epochNum, MSE_Threshold)
labels = [firstClassCB.get(), secondClassCB.get()]
Adaline.test(x_test, y_test, W, labels)
except:
pass
#perceptron.evaluate()
###################### END Model ########################
row = 9
perceptronButton = ttk.Button(parent, text="perceptron", command=perceptronModel)
perceptronButton.grid(column=0, row=row, padx=10, pady=10)
row = 9
adalineButton = ttk.Button(parent, text="adaline", command=adalineModel)
adalineButton.grid(column=1, row=row, padx=10, pady=10)
# render
parent.mainloop()