-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPerceptron.py
424 lines (305 loc) · 12 KB
/
Perceptron.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
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
#!/usr/bin/env python
# coding: utf-8
# In[1]:
from typing import Union, List
from math import sqrt
# In[2]:
from collections.abc import Iterable
import random
from random import randint
# In[3]:
import matplotlib.pyplot as plt
# In[4]:
class Scalar:
pass
class Vector:
pass
# In[5]:
class Scalar:
def __init__(self: Scalar, val: float):
self.val = float(val)
def __mul__(self: Scalar, other: Union[Scalar, Vector]) -> Union[Scalar, Vector]:
is_Scalar = isinstance(other, Scalar)
is_Vector = isinstance(other, Vector)
if is_Scalar:
return Scalar(self.val * other.val)
elif is_Vector:
return Vector(*[n * self.val for n in other])
else:
raise TypeError("the second operand should be of type Vector or Scalar")
def __add__(self: Scalar, other: Scalar) -> Scalar:
if not isinstance(other, Scalar):
raise TypeError("the second operand should be of type Scalar")
return Scalar(self.val + other.val)
def __sub__(self: Scalar, other: Scalar) -> Scalar:
if not isinstance(other, Scalar):
raise TypeError("the second operand should be of type Scalar")
return Scalar(self.val - other.val)
def __truediv__(self: Scalar, other: Scalar) -> Scalar:
if not isinstance(other, Scalar):
raise TypeError("the second operand should be of type Scalar")
return Scalar(self.val / other.val)
def __rtruediv__(self: Scalar, other: Vector) -> Vector:
if not isinstance(other, Vector):
raise TypeError("the second operand should be of type Vector")
return Vector(*[n / self.val for n in other])
def __repr__(self: Scalar) -> str:
return "Scalar(%r)" % self.val
def sign(self: Scalar) -> int:
if self.val == 0:
return 0
elif self.val > 0:
return 1
return -1
def __float__(self: Scalar) -> float:
return self.val
# In[6]:
class Vector:
def __init__(self: Vector, *entries: List[float]):
self.entries = entries
def zero(size: int) -> Vector:
return Vector(*[0 for i in range(size)])
def __add__(self: Vector, other: Vector) -> Vector:
if not isinstance(other, Vector):
raise TypeError("The second operand should be of type Vector")
assert len(self) == len(other), "Vectors should be of equal length"
return Vector(*[v1 + v2 for v1, v2 in zip(self.entries, other.entries)])
def __sub__(self: Vector, other: Vector) -> Vector:
if not isinstance(other, Vector):
raise TypeError("The second operand should be of type Vector")
assert len(self) == len(other), "Vectors should be of equal length"
return Vector(*[v1 - v2 for v1, v2 in zip(self.entries, other.entries)])
def __mul__(self: Vector, other: Vector) -> Scalar:
if not isinstance(other, Vector):
raise TypeError("the second operand should be of type Vector")
assert len(self.entries) == len(other.entries), "vectors should be of equal length"
return Scalar(sum([v1 * v2 for v1, v2 in zip(self.entries, other.entries)]))
def magnitude(self: Vector) -> Scalar:
return Scalar(sqrt(self * self))
def __getitem__(self, item):
return self.entries[item]
def unit(self: Vector) -> Vector:
return self / self.magnitude()
def __len__(self: Vector) -> int:
return len(self.entries)
def __repr__(self: Vector) -> str:
return "Vector%s" % repr(self.entries)
def __iter__(self: Vector):
return iter(self.entries)
# In[8]:
def perceptron_train(data: List[tuple], maxiter: int, weights: Vector=None, bias: Scalar=None) -> tuple:
if not isinstance(data, list):
raise TypeError("param data should be of type list")
if weights is None:
weights = Vector.zero(len(data[0][0]))
if bias is None:
bias = Scalar(0)
iteration: int = 1
while iteration <= maxiter:
for x, y in data:
act: Scalar = Scalar(x * weights) + bias
if float(y * act) <= 0:
weights = weights + ( y * x )
bias = bias + y
iteration += 1
return (weights, bias)
# In[9]:
def perceptron_test(weights: Vector,
bias: Scalar,
x: Vector):
if not isinstance(weights, Vector) or not isinstance(x, Vector):
raise TypeError("X and weights should be vectors")
if not isinstance(bias, Scalar):
raise TypeError("Bias should be a single scalar")
if len(weights) != len(x):
raise ValueError("vectors should be of equal length")
a: Scalar = Scalar(x * weights) + bias
return a.sign()
# In[10]:
def to_train_data(_x, _y):
return [(x, y) for x, y in zip(_x, _y)]
# In[11]:
def train_test_split(*args, test_size: float=0.1):
if len(args) < 1:
raise ValueError("Nothing to split")
if not all(
map(lambda x: isinstance(x, Iterable),
args)):
raise TypeError(
"Can only process iterables"
)
common_length: int = len(args[0])
if not all(
map(lambda x: len(x) == common_length,
args)):
raise ValueError(
"All vectors should have equal length"
)
size: int = int(common_length * test_size)
random_indices: List[int] = random.sample(range(common_length), size)
output: list = []
for vector in args:
train: list = []
test: list = []
for index in range(common_length):
if index in random_indices:
test.append(vector[index])
else:
train.append(vector[index])
output.append(Vector(*train))
output.append(Vector(*test))
return output
# In[12]:
def evaluate(w: Vector, b: Scalar, data: list, labels: list):
prediction = [perceptron_test(w, b, x_i) for x_i in data]
correct = [i for i in filter(
lambda x: labels[x].sign() == prediction[x],
range(len(labels))
)]
return len(correct) / len(labels)
# In[14]:
v = Vector(randint(-100, 100), randint(-100, 100))
xs = [Vector(randint(-100, 100), randint(-100, 100)) for i in range(500)]
ys = [v * x * Scalar(randint(-1, 9)) for x in xs]
x_train, x_test, y_train, y_test = train_test_split(xs, ys)
data = to_train_data(x_train, y_train)
w, b = perceptron_train(data, maxiter=500)
print("Ratio of correct predictions: {}".format(
evaluate(w, b, x_test, y_test)
))
# In[15]:
xs = [Vector(randint(-100, 100), randint(-100, 100)) for i in range(500)]
ys = [Scalar(1) if x.entries[0]*x.entries[1] < 0 else Scalar(-1) for x in xs]
x_train, x_test, y_train, y_test = train_test_split(xs, ys)
data = to_train_data(x_train, y_train)
w, b = perceptron_train(data, maxiter=500)
print("Ratio of correct predictions: {}".format(
evaluate(w, b, x_test, y_test)
))
# In[16]:
def shuffle_data(*args: List[Vector]) -> List[Vector]:
if len(args) < 1:
raise ValueError("Nothing to shuffle")
if not all(
map(lambda x: isinstance(x, Iterable),
args)):
raise TypeError("Can only process iterables")
common_length: int = len(args[0])
if not all(
map(lambda x: len(x) == common_length,
args)):
raise ValueError("All vectors should have equal length")
output: list = []
random_indices: list = [num for num in range(common_length)]
random.shuffle(random_indices)
for vector in args:
permuted = [vector[idx] for idx in random_indices]
output.append(permuted)
return output
# In[17]:
v = Vector(randint(-100, 100), randint(-100, 100))
xs = [Vector(randint(-100, 100), randint(-100, 100)) for i in range(500)]
ys = [v * x * Scalar(randint(-1, 9)) for x in xs]
x_train, x_test, y_train, y_test = train_test_split(xs, ys)
# In[18]:
#sort & prepare data
sorted_data = sorted(zip(xs, ys), key=lambda x: x[1].val)
sorted_x = [i[0] for i in sorted_data]
sorted_y = [i[1] for i in sorted_data]
sorted_data = to_train_data(sorted_x, sorted_y)
# In[19]:
# shuffle data 1 time
shuffled_x, shuffled_y = shuffle_data(sorted_x, sorted_y)
shuffled_data = to_train_data(shuffled_x, shuffled_y)
# In[20]:
epochs = []
# allocate paerformance lists
sorted_perf = []
shuffled_perf = []
ms_perf = []
# set default epoch length
epoch_len = len(sorted_x)
counter = 1
# set initial vectors before shuffling on each iteration
mult_shuffle_x = sorted_x
mult_shuffle_y = sorted_y
#set initial weights & biases
sorted_w, sorted_b = perceptron_train(sorted_data, maxiter=epoch_len)
shuffled_w, shuffled_b = perceptron_train(shuffled_data, maxiter=epoch_len)
mult_shuffle_w, mult_shuffle_b = perceptron_train(shuffled_data, maxiter=epoch_len)
#iterate to update weights
for number in range(7):
sorted_w, sorted_b = perceptron_train(sorted_data,
weights=sorted_w,
bias=sorted_b,
maxiter=epoch_len)
sorted_perf.append(
evaluate(sorted_w, sorted_b, xs, ys)
)
shuffled_w, shuffled_b = perceptron_train(shuffled_data,
weights=shuffled_w,
bias=shuffled_b,
maxiter=epoch_len)
shuffled_perf.append(
evaluate(shuffled_w, shuffled_b, xs, ys)
)
mult_shuffle_x, mult_shuffle_y = shuffle_data(mult_shuffle_x,
mult_shuffle_y)
mult_shuffle_data = to_train_data(mult_shuffle_x,
mult_shuffle_y)
mult_shuffle_w, mult_shuffle_b = perceptron_train(mult_shuffle_data,
weights=mult_shuffle_w,
bias=mult_shuffle_b,
maxiter=epoch_len)
ms_perf.append(
evaluate(mult_shuffle_w, mult_shuffle_b, xs, ys)
)
epochs.append(counter)
counter += 1
# In[21]:
fig, ax = plt.subplots()
ax.plot(epochs, sorted_perf, 'k--', label='No permutation')
ax.plot(epochs, shuffled_perf, 'k:', label='One permutation')
ax.plot(epochs, ms_perf, 'k', label='Multiple permutations')
legend = ax.legend(shadow=True, fontsize='x-large')
plt.show()
# In[23]:
def averaged_perceptron_train(data: List[tuple], maxiter: int, weights: Vector=None, bias: Scalar=None) -> tuple:
if not isinstance(data, list):
raise TypeError("param data should be of type list")
if weights is None:
weights = Vector.zero(len(data[0][0]))
cached_w: Vector = Vector.zero(len(data[0][0]))
if bias is None:
bias = Scalar(0)
cached_b: Scalar = Scalar(0)
iteration: int = 1
counter: Scalar = Scalar(1)
while iteration <= maxiter:
for x, y in data:
act: Scalar = Scalar(x * weights) + bias
if float(y * act) <= 0:
weights = weights + ( y * x )
bias = bias + y
cached_w = cached_w + counter * y * x
cached_b = cached_b + counter * y
counter.val += 1
iteration += 1
weigth_correction = cached_w / counter
bias_correction = cached_b / counter
return (weights - weigth_correction,
bias - bias_correction)
# In[24]:
v = Vector(randint(-100, 100), randint(-100, 100))
xs = [Vector(randint(-100, 100), randint(-100, 100)) for i in range(500)]
ys = [v * x * Scalar(randint(-1, 9)) for x in xs]
x_train, x_test, y_train, y_test = train_test_split(xs, ys)
data = to_train_data(x_train, y_train)
w, b = perceptron_train(data, maxiter=500)
w_avg, b_avg = averaged_perceptron_train(data, maxiter=500)
print("Ratio of correct predictions, no averaging: {}".format(
evaluate(w, b, x_test, y_test)
))
print("Ratio of correct predictions, with averaging: {}".format(
evaluate(w_avg, b_avg, x_test, y_test)
))