-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathFirstNetwork.py
More file actions
72 lines (59 loc) · 2.72 KB
/
FirstNetwork.py
File metadata and controls
72 lines (59 loc) · 2.72 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
65
66
67
68
69
70
71
72
# neural network definition
import numpy
import scipy.special
class neuralNetwork:
# initialise the neural network
def __init__(self, inputnodes, hiddennodes, outputnodes, learningrate):
# set number of nodes in each input,hidden,output layer
self.inodes = inputnodes
self.hnodes = hiddennodes
self.onodes = outputnodes
self.lr = learningrate
# link weight matrices,wih and who
# weights inside the arrays are w_i_j,where link is from node i to node j in the next layer
# w11 w21
# w12 w22 etc
# self.wih = (numpy.random.random(self.hnodes,self.inodes)-0.5)
# self.who = (numpy.random.random(self.onodes,self.hnodes)-0.5)
self.wih = (numpy.random.normal(0.0, pow(self.hnodes, -0.5), (self.hnodes, self.inodes)))
self.who = (numpy.random.normal(0.0, pow(self.onodes, -0.5), (self.onodes, self.hnodes)))
self.activation_funcation = lambda x: scipy.special.expit(x)
pass
# train the neural network
def train(self, inputs_list, targets_list):
inputs = numpy.array(inputs_list, ndmin=2).T
targes = numpy.array(targets_list, ndmin=2).T
hidden_inputs = numpy.dot(self.wih, inputs)
hidden_outputs = self.activation_funcation(hidden_inputs)
final_inputs = numpy.dot(self.who, hidden_outputs)
final_ouputs = self.activation_funcation(final_inputs)
output_errors = targes - final_ouputs
hidden_errors = numpy.dot(self.who.T, output_errors)
self.who += self.lr * numpy.dot((output_errors * final_ouputs * (1.0 - final_ouputs)),
numpy.transpose(hidden_outputs))
self.wih += self.lr * numpy.dot((hidden_errors * hidden_outputs * (1.0 - hidden_outputs)),
numpy.transpose(inputs))
pass
# query the neural network
def query(self, inputs_list):
inputs = numpy.array(inputs_list, ndmin=2).T
hidden_inputs = numpy.dot(self.wih, inputs)
hidden_outputs = self.activation_funcation(hidden_inputs)
final_inputs = numpy.dot(self.who, hidden_outputs)
final_ouputs = self.activation_funcation(final_inputs)
return final_ouputs
# number of input ,hidden and output nodes
input_nodes = 3
hidden_nodes = 3
output_nodes = 3
# learning rate is 0.3
learning_rate = 0.3
# create insrance of neural network
n = neuralNetwork(input_nodes, hidden_nodes, output_nodes, learning_rate)
# print(n.query([1.0, 0.5, -1.5]))
n.train([1.0, 0.5, 1.5],[1.0, 0.5, 1.5])
n.train([2.0, 0.6, 1.6],[2.0, 0.6, 1.6])
n.train([1.9, 10.5, 8],[1.9, 10.5, 8])
n.train([20.0, 0.66, 1.98],[20.0, 0.66, 1.98])
print(n.query([2.0, 0.5, 1.5]))
# numpy.random.rand(3, 3) - 0.5