-
Notifications
You must be signed in to change notification settings - Fork 0
/
neurals.py
141 lines (83 loc) · 2.88 KB
/
neurals.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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
#!/usr/bin/env python
# coding: utf-8
# In[1]:
import numpy as np
from keras.datasets import mnist
# In[2]:
(train_input, train_label), (test_input, test_label) = mnist.load_data()
# In[3]:
train_input = (train_input.reshape(60000, 784) / 255.0 * 0.99) + 0.01
targets = np.zeros((60000, 10)) + 0.01
i = 0
for target in targets:
target[int(train_label[i])] = 0.99
i += 1
# In[4]:
class neuralnetwork:
def __init__(self, inode , hnode, onode):
self.input_node = inode
self.output_node = onode
self.hidden_node = hnode
self.wih = 2 * np.random.random((self.input_node, self.hidden_node)) - 1
self.who = 2 * np.random.random((self.hidden_node, self.output_node)) - 1
def activate(self, x, deriv = False):
if deriv == True:
return x * (1 - x)
return 1 / (1 + np.exp(-x))
def training(self, input_list, target):
for i in range(1500):
layer0 = input_list
targets = target
layer1 = self.activate(np.dot(layer0, self.wih))
layer2 = self.activate(np.dot(layer1, self.who))
errors = targets - layer2
hidden_errors = np.dot(errors, self.who.T)
self.who += np.transpose(np.dot((errors * self.activate(layer2, deriv = True)).T, layer1))
self.wih += np.transpose(np.dot((hidden_errors * self.activate(layer1, deriv = True)).T, layer0))
# if i % 10 == 0:
# print("Error: ", errors)
# print("outputs: ", layer2)
# print()
def testing(self, input_list):
layer0 = input_list
layer1 = self.activate(np.dot(layer0, self.wih))
layer2 = self.activate(np.dot(layer1, self.who))
return layer2
# In[10]:
nn = neuralnetwork(784, 100 , 10)
#nn.testing(testing_inputs)
# In[11]:
for i in range(1,20):
inputs = train_input[:i]
target = targets[:i]
nn.training(inputs, target)
a = nn.testing(inputs)
a
# In[ ]:
# In[ ]:
inputss = np.array([
[1,0,0,1,0,1,1,1,1,1,1,0,0,0,1,0,1,0,1],
[1,0,0,1,0,1,1,0,1,0,1,0,0,0,1,0,1,0,1],
[0,1,0,1,0,1,1,0,1,1,1,0,0,0,1,0,1,0,1],
[1,1,0,1,0,1,1,1,1,1,1,0,0,0,1,0,1,0,1],
[1,0,0,1,0,1,1,1,1,0,1,0,0,0,1,0,1,0,1],
[1,1,0,1,0,1,1,1,1,1,1,0,0,0,1,0,1,0,1],
[0,0,1,1,0,1,1,1,1,1,1,0,0,0,1,0,1,0,1],
[0,0,0,1,0,1,1,0,1,1,1,0,0,0,1,0,1,0,1]
])
targetss = np.array([
[1,0,0],
[0,0,0],
[0,1,0],
[1,1,0],
[1,0,0],
[1,1,0],
[0,0,1],
[1,1,1]
])
testing_inputs = np.array([
[1,1,0,1,0,1,1,1,1,1,1,0,0,0,1,0,1,0,1],
[1,0,0,1,0,1,1,0,1,0,1,0,0,0,1,0,1,0,1],
[0,0,0,1,0,1,1,0,1,1,1,0,0,0,1,0,1,0,1],
[0,1,0,1,0,1,1,0,1,1,1,0,0,0,1,0,1,0,1],
])