-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathex2.py
303 lines (258 loc) · 8.33 KB
/
ex2.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
import numpy as np
from scipy import stats
import random
import os
import sys
def turnToFloat(abalonesArr):
"""
Cast all the values in the array to float.
Parameters
----------
abalonesArr : array of strings.
Returns
-------
newArr : array of floats.
"""
newArr = []
for line in abalonesArr:
newLine = []
for value in line:
newLine.append(float(value))
newArr.append(np.asarray(newLine))
return np.asarray(newArr)
def setIMFValues(abalonesArr):
"""
Replace the I/M/F by a numeric value.
Parameters
----------
abalonesArr : array of abalones information.
Returns
-------
abalonesArr : array after all I/M/F are replaced.
"""
for abalones in abalonesArr:
if abalones[0] == "I":
abalones[0] = 0
if abalones[0] == "F":
abalones[0] = 1
if abalones[0] == "M":
abalones[0] = 2
return abalonesArr
def normalizeValues(abalonesArr):
"""
Normalize each column in the array by Z-Score normalization.
Parameters
----------
abalonesArr : array of abalones information.
Returns
-------
abalonesArr : array with normalized values.
"""
# transpose the matrix to get each parameter in a separate array.
transposedArr = np.asarray([*zip(*abalonesArr)])
# iterate the parameters one by one.
for line in transposedArr:
stats.zscore(line)
# re-transpose matrix.
return np.asarray([*zip(*transposedArr)])
def perceptron(X_train, Y_train):
"""
Build a weights vector using the perceptron algorithm.
Parameters
----------
X_train : array of information (abalones).
Y_train : array of matching labels (ages).
Returns
-------
weights : weights vector.
"""
# Hyper-parameters
epochs = 50
eta = 0.01
weights = np.zeros((3, 8))
# Train the algorithm epochs times.
for e in range(epochs):
s = list(zip(X_train, Y_train))
random.shuffle(s)
X_train, Y_train = zip(*s)
for x, y in zip(X_train, Y_train):
wx = np.dot(weights, x)
# y_hat is prediction
y_hat = np.argmax(wx)
y = int(y[0])
# Update weights only if the prediction was wrong.
if y != y_hat:
weights[y, :] = weights[y, :] + eta * x
weights[y_hat, :] = weights[y_hat, :] - eta * x
eta = eta / epochs
return weights
def SVM(X_train, Y_train):
"""
Build a weights vector using the SVM algorithm.
Parameters
----------
X_train : array of information (abalones).
Y_train : array of matching labels (ages).
Returns
-------
weights : weights vector.
"""
# Hyper-parameters
epochs = 50
eta = 0.01
lamda = 0.01
weights = np.zeros((3, 8))
# Train the algorithm epochs times.
for e in range(epochs):
s = list(zip(X_train, Y_train))
random.shuffle(s)
X_train, Y_train = zip(*s)
for x, y in zip(X_train, Y_train):
# y_hat is prediction
y_hat = np.argmax(np.dot(weights, x))
y = int(y[0])
# Update weights only if the prediction was wrong.
if y != y_hat:
weights[y, :] = (1 - eta * lamda) * weights[y, :] + eta * x
weights[y_hat, :] = (1 - eta * lamda) * weights[y_hat, :] - eta * x
for i in range (3):
if (i != y) and (i != y_hat):
weights[i, :] = (1 - eta * lamda) * weights[i, :]
eta = eta / epochs
return weights
def tau(weights, x, y, y_hat):
"""
Calculate the tau value for PA.
Parameters
----------
weights : weights vector.
x : specific abalone's information.
y : specific abalone's label.
y_hat : abalone's prediction.
Returns
-------
tau value.
"""
normal_X = 0
for i in range(len(x)):
normal_X += np.power(x[i], 2)
normal_X = np.sqrt(normal_X)
a = np.dot(weights[y, :], x)
b = np.dot(weights[y_hat, :], x)
loss = max(0, 1 - a + b)
# For case of division by 0.
if (2 * np.power(normal_X, 2)) == 0:
return 1
return loss / (2 * np.power(normal_X, 2))
def PA(X_train, Y_train):
"""
Build a weights vector using the PA algorithm.
Parameters
----------
X_train : array of information (abalones).
Y_train : array of matching labels (ages).
Returns
-------
weights : weights vector.
"""
# Hyper-parameters
epochs = 70
weights = np.zeros((3, 8))
# Train the algorithm epochs times
for e in range(epochs):
s = list(zip(X_train, Y_train))
random.shuffle(s)
X_train, Y_train = zip(*s)
for x, y in zip(X_train, Y_train):
# y_hat is prediction
y_hat = np.argmax(np.dot(weights, x))
y = int(y[0])
# Update weights only if the prediction was wrong.
if y != y_hat:
t = tau(weights, x, y, y_hat)
weights[y, :] = weights[y, :] + t * x
weights[y_hat, :] = weights[y_hat, :] - t * x
return weights
def createResultsList(weights, X_test):
"""
Multiplies each information vector in the test array by the weights vector, and returns a list of results.
Parameters
----------
weights : weights vector.
X_test : array of information (abalones).
Returns
-------
results : list of results.
"""
results = []
X_test = list(X_test)
for t in range (0, len(X_test)):
results.append(np.argmax(np.dot(weights, X_test[t])))
return results
def printResults(perceptron_results, svm_results, pa_results):
"""
Prints all the predictions for each abalones in the following format:
"perceptron: __, svm: __, pa: __"
Parameters
----------
perceptron_results : predictions list of perceptron.
svm_results : predictions list of svm.
pa_results : predictions list of pa.
"""
for r1, r2, r3 in zip(perceptron_results, svm_results, pa_results):
print("perceptron: %d, svm: %d, pa: %d" % (r1, r2, r3))
# get paths from command line arguments.
train_x_path = sys.argv[1]
train_y_path = sys.argv[2]
test_x_path = sys.argv[3]
# open files.
train_x = open(os.path.join(os.path.dirname(__file__), train_x_path), 'r')
train_y = open(os.path.join(os.path.dirname(__file__), train_y_path), 'r')
test_x = open(os.path.join(os.path.dirname(__file__), test_x_path), 'r')
# initialize lists.
abalonesTrainList = []
labelsTrainList = []
abalonesTestList = []
# start reading lines.
xline = train_x.readline()
yline = train_y.readline()
# iterate all the lines in both train files.
while xline and yline:
# add abalone to abalones list and label to labels list accordingly.
xarr = str.split(xline, ",")
abalonesTrainList.append(xarr)
labelsTrainList.append(yline[0]);
# move on to next line.
xline = train_x.readline()
yline = train_y.readline()
xtestline = test_x.readline()
# iterate all the lines in both train files.
while xtestline:
# add abalone to abalones list and label to labels list accordingly.
xarr = str.split(xtestline, ",")
abalonesTestList.append(xarr)
# move on to next line.
xtestline = test_x.readline()
# prepare train inputs array.
abalonesTrainArr = np.asarray(abalonesTrainList)
abalonesTrainArr = setIMFValues(abalonesTrainArr)
abalonesTrainArr = turnToFloat(abalonesTrainArr)
abalonesTrainArr = normalizeValues(abalonesTrainArr)
# prepare train labels array.
labelsTrainArr = np.asarray(labelsTrainList)
labelsTrainArr = turnToFloat(labelsTrainArr)
# prepare test inputs array.
abalonesTestArr = np.asarray(abalonesTestList)
abalonesTestArr = setIMFValues(abalonesTestArr)
abalonesTestArr = turnToFloat(abalonesTestArr)
abalonesTestArr = normalizeValues(abalonesTestArr)
# get weights vector for each of the algorithms.
w_perceptron = perceptron(abalonesTrainArr, labelsTrainArr)
w_svm = SVM(abalonesTrainArr, labelsTrainArr)
w_pa = PA(abalonesTrainArr, labelsTrainArr)
# create lists of results for each algorithm.
perceptron_results = createResultsList(w_perceptron, abalonesTestArr)
svm_results = createResultsList(w_svm, abalonesTestArr)
pa_results = createResultsList(w_pa, abalonesTestArr)
# print the results in the requested format.
printResults(perceptron_results, svm_results, pa_results)