-
Notifications
You must be signed in to change notification settings - Fork 0
/
perceptron.py
58 lines (53 loc) · 1.42 KB
/
perceptron.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
class Perceptron:
def __init__(self, n, rate=1, thresh=1):
self.count = n+1
self.rate = rate
self.thresh = thresh
self.edges = [0]*(n+1)
def activation(self, x):
if x > self.thresh:
return 1
elif x < -1*self.thresh:
return -1
else:
return 0
def _update(self, s, z):
# s --> input
# z --> output
self.edges[0] += 1*z*self.rate
for i in range(1, self.count):
self.edges[i] += s[i-1]*z*self.rate
return
def fit(self, s, z, info=False):
# s --> list of inputs
# z --> list of corresponding outputs
# info --> show information or not
flag = True
while(flag):
flag = False
for i in range(len(s)):
if self.predict(s[i]) != z[i]:
flag = True
self._update(s[i],z[i])
if not info :
return
print("Training Complete")
for i in range(len(s)):
out = self.predict(s[i])
print("Output is: ",out," should be: ",z[i])
return
def predict(self, s):
# s is an input
ans = self.edges[0]
for i in range(1,self.count):
ans += s[i-1]*self.edges[i]
return self.activation(ans)
if __name__ == "__main__":
n = int(input("The number of neurons:"))
t = int(input("The number of inputs(training_data_count):"))
s = [list(map(int,input("Input? :").strip(" ").split(" "))) for i in range(t)]
z = [int(input("Output? :")) for i in range(t)]
net = Perceptron(n)
net.fit(s, z, False)
for i in s:
print(net.predict(i))