-
Notifications
You must be signed in to change notification settings - Fork 0
/
Perceptron_XOR.py
82 lines (67 loc) · 2.66 KB
/
Perceptron_XOR.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
# ----------
#
# In this exercise, you will create a network of perceptrons that can represent
# the XOR function, using a network structure like those shown in the previous
# quizzes.
#
# You will need to do two things:
# First, create a network of perceptrons with the correct weights
# Second, define a procedure EvalNetwork() which takes in a list of inputs and
# outputs the value of this network.
#
# ----------
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, values):
"""
Takes in @param values, 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.
"""
# First calculate the strength with which the perceptron fires
strength = np.dot(values,self.weights)
# Then return 0 or 1 depending on strength compared to threshold
return int(strength > self.threshold)
# Part 1: Set up the perceptron network
Network = [
# input layer, declare input layer perceptrons here
[[1, 0], [0, 1], [0.5, 0.5]], \
# output node, declare output layer perceptron here
[0.25, 0.25, 0]
]
# Part 2: Define a procedure to compute the output of the network, given inputs
def EvalNetwork(inputValues, Network):
"""
Takes in @param inputValues, a list of input values, and @param Network
that specifies a perceptron network. @return the output of the Network for
the given set of inputs.
"""
# YOUR CODE HERE
# Be sure your output value is a single number
x1 = np.dot(inputValues, Network[0][0])
x2 = np.dot(inputValues, Network[0][1])
and_perceptron = np.dot(inputValues, Network[0][2])
#print "({}, {}, {})".format(x1, x2, and_perceptron)
y = np.dot([x1, x2, and_perceptron], Network[1])
OutputValue = 1 if y == .25 else 0
return OutputValue
def test():
"""
A few tests to make sure that the perceptron class performs as expected.
"""
print "0 XOR 0 = 0?:", EvalNetwork(np.array([0,0]), Network)
print "0 XOR 1 = 1?:", EvalNetwork(np.array([0,1]), Network)
print "1 XOR 0 = 1?:", EvalNetwork(np.array([1,0]), Network)
print "1 XOR 1 = 0?:", EvalNetwork(np.array([1,1]), Network)
if __name__ == "__main__":
test()