-
Notifications
You must be signed in to change notification settings - Fork 0
/
perceptron.py
85 lines (69 loc) · 2.58 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
import backend
import numpy as np
class Perceptron(object):
def __init__(self, dimensions):
"""
Initialize a new Perceptron instance.
A perceptron classifies data points as either belonging to a particular
class (+1) or not (-1). `dimensions` is the dimensionality of the data.
For example, dimensions=2 would mean that the perceptron must classify
2D points.
"""
self.get_data_and_monitor = backend.make_get_data_and_monitor_perceptron()
"*** YOUR CODE HERE ***"
self.weights = np.zeros(dimensions)
def get_weights(self):
"""
Return the current weights of the perceptron.
Returns: a numpy array with D elements, where D is the value of the
`dimensions` parameter passed to Perceptron.__init__
"""
"*** YOUR CODE HERE ***"
return self.weights
def predict(self, x):
"""
Calculates the predicted class for a single data point `x`.
Returns: 1 or -1
"""
"*** YOUR CODE HERE ***"
if np.dot(self.weights, x) >= 0:
return 1
else:
return -1
def update(self, x, y):
"""
Update the weights of the perceptron based on a single example.
x is a numpy array with D elements, where D is the value of the
`dimensions` parameter passed to Perceptron.__init__
y is either 1 or -1
Returns:
True if the perceptron weights have changed, False otherwise
"""
"*** YOUR CODE HERE ***"
if self.predict(x) == y:
return False
else:
new_weights = self.get_weights() + (np.dot(x, y))
self.weights = new_weights
return True
def train(self):
"""
Train the perceptron until convergence.
To iterate through all of the data points once (a single epoch), you can
do:
for x, y in self.get_data_and_monitor(self):
...
get_data_and_monitor yields data points one at a time. It also takes the
perceptron as an argument so that it can monitor performance and display
graphics in between yielding data points.
"""
"*** YOUR CODE HERE ***"
boolean = False
accomplished = False
while boolean is False:
accomplished = True
for x, y in self.get_data_and_monitor(self):
if self.update(x, y) == True:
accomplished = False
if accomplished == True:
boolean = True