-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNeural Net
More file actions
53 lines (42 loc) · 1.4 KB
/
Copy pathNeural Net
File metadata and controls
53 lines (42 loc) · 1.4 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
import numpy as np
# define the sigmoid function
def sigmoid(x):
return 1 / (1 + np.exp(-x))
# define the derivative of the sigmoid function
def sigmoid_derivative(x):
return x * (1 - x)
# define the neural net
class NeuralNet:
def __init__(self, x, y):
self.input = x
self.weights1 = np.random.rand(self.input.shape[1], 4)
self.weights2 = np.random.rand(4, 1)
self.y = y
self.output = np.zeros(self.y.shape)
def feedforward(self):
self.layer1 = sigmoid(np.dot(self.input, self.weights1))
self.output = sigmoid(np.dot(self.layer1, self.weights2))
def backprop(self):
# calculate the error
error = self.y - self.output
# calculate the gradient
gradient = sigmoid_derivative(self.output)
gradient *= error
gradient = gradient.mean()
# adjust the weights
self.weights2 += gradient
self.weights1 += np.dot(self.input.T, np.dot(error, self.weights2.T) * sigmoid_derivative(self.layer1))
# define the input and expected output
x = np.array([[0,0,1],
[0,1,1],
[1,0,1],
[1,1,1]])
y = np.array([[0],[1],[1],[0]])
# create the neural net
nn = NeuralNet(x, y)
# train the neural net
for i in range(1000):
nn.feedforward()
nn.backprop()
# print the output of the trained neural net
print(nn.output)