forked from udacity/machine-learning
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathperceptron_xor.py
55 lines (41 loc) · 1.63 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
#
# In this exercise, you will create a network of perceptrons which
# represent the xor function use the same network structure you used
# 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 EvalNet() which takes in a list of
# inputs and ouputs the value of this network.
import numpy as np
class Perceptron:
def evaluate(self,values):
'''Takes in @param values, @param weights lists of numbers
and @param threshold a single number.
@return the output of a threshold perceptron with
given weights and threshold, given values as inputs.
'''
#First calculate the strength with which the perceptron fires
strength = np.dot(values,self.weights)
#Then evaluate the return value of the perceptron
if strength >= self.threshold:
result = 1
else:
result = 0
return result
def __init__(self,weights=None,threshold=None):
if weights is not None:
self.weights = weights
if threshold is not None:
self.threshold = threshold
Network = [
#input layer, declare perceptrons here
Perceptron([0.5, 0.5], 0.75),
#output node, declare one perceptron here
Perceptron([1, -2, -1], 0)
]
def EvalNetwork(inputValues, Network):
# Be sure your output values are single numbers
outputAnd = Network[0].evaluate(inputValues)
OutputValues = Network[1].evaluate([inputValues[0], outputAnd, inputValues[1]])
return OutputValues