-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPerceptron.py
More file actions
56 lines (44 loc) · 1.68 KB
/
Perceptron.py
File metadata and controls
56 lines (44 loc) · 1.68 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
# ----------
#
# In this exercise, you will put the finishing touches on a perceptron class.
#
# Finish writing the activate() method by using np.dot to compute signal
# strength and then add in a threshold for perceptron activation.
#
# ----------
import numpy as np
class Perceptron:
"""
This class models an artificial neuron with step activation function.
"""
def __init__(self, weights = np.array([1]), threshold = 0):
"""
Initialize weights and threshold based on input arguments. Note that no
type-checking is being performed here for simplicity.
"""
self.weights = weights
self.threshold = threshold
def activate(self,inputs):
"""
Takes in @param inputs, a list of numbers equal to length of weights.
@return the output of a threshold perceptron with given inputs based on
perceptron weights and threshold.
"""
# INSERT YOUR CODE HERE
# TODO: calculate the strength with which the perceptron fires
activation = np.sum(np.multiply(inputs, self.weights))
print activation
# TODO: return 0 or 1 based on the threshold
result = 1 if activation > self.threshold else 0
return result
def test():
"""
A few tests to make sure that the perceptron class performs as expected.
Nothing should show up in the output if all the assertions pass.
"""
p1 = Perceptron(np.array([1, 2]), 0.)
assert p1.activate(np.array([ 1,-1])) == 0 # < threshold --> 0
assert p1.activate(np.array([-1, 1])) == 1 # > threshold --> 1
assert p1.activate(np.array([ 2,-1])) == 0 # on threshold --> 0
if __name__ == "__main__":
test()