-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathxor.py
More file actions
65 lines (44 loc) · 1.69 KB
/
xor.py
File metadata and controls
65 lines (44 loc) · 1.69 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
57
58
59
60
61
62
63
64
import numpy as np
# XOR Gate #
def sig(x):
return 1 / (1 + np.exp(x))
def sigDeriv(x):
return x * (1 - x)
input = np.array([[0,0],[0,1],[1,0],[1,1]])
target = np.array([[0],[1],[1],[0]])
inputLayerNeurons, hiddenLayerNeurons, outputLayerNeurons = 2, 2, 1
# Init random weights
hiddenWeights = np.random.uniform(size=(inputLayerNeurons,hiddenLayerNeurons))
hiddenBias = np.zeros((1, 2), dtype = float)
outputWeights = np.random.uniform(size=(hiddenLayerNeurons,outputLayerNeurons))
outputBias = np.zeros((1, 1), dtype = float)
epochs = 50000
lRate = 1
for _ in range(epochs):
# forward prop
hiddenLayerActivation = np.dot(input, hiddenWeights)
hiddenLayerActivation += hiddenBias
hiddenLayerOutput = sig(hiddenLayerActivation)
outputLayerActivation = np.dot(hiddenLayerOutput, outputWeights)
outputLayerActivation += outputBias
predictedOutput = sig(outputLayerActivation)
# back prop
error = target
dPredictedOutput = error
errorHiddenLayer = dPredictedOutput.dot(outputWeights.T)
dHiddenLayer = errorHiddenLayer * sigDeriv(hiddenLayerOutput)
# updating weights, bias
outputWeights += hiddenLayerOutput.T.dot(dPredictedOutput) * lRate
outputBias += np.sum(dPredictedOutput, axis = 0, keepdims=True)
hiddenWeights += input.T.dot(dHiddenLayer)
hiddenBias += np.sum(dHiddenLayer, axis = 0, keepdims=True) * lRate
print("Final hidden weights: ", end = '')
print(*hiddenWeights)
print("Final hidden bias: ", end = '')
print(*hiddenBias)
print("Final output weights: ", end = '')
print(*outputWeights)
print("Final output bias: ", end = '')
print(*outputBias)
print("\nOutput from nn: ", end = '')
print(*predictedOutput)