-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPerceptron Test.py
More file actions
147 lines (109 loc) · 2.93 KB
/
Copy pathPerceptron Test.py
File metadata and controls
147 lines (109 loc) · 2.93 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
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
141
142
143
144
145
146
147
import decimal as d
import random as r
import turtle as t
#supervised learning
#We know the answer
lr = 0.1
w = [r.random(), r.random()]
#actuation function that process the sum and return either 1 or -1
def actuation_func(n):
if n >= 0:
return 1
elif n < 0:
return -1
#calculate the sum of input*wieghts
def total(a, b):
return a[0]*b[0] + a[1]*b[1]
#training data and change the weight
def train(data, point, target):
error = target - data
print(error)
#tune all the weights
for i in range(len(w)):
w[i] += error * point[i] * lr
def paint(i):
t.penup()
t.setpos(i)
t.pendown()
t.dot(10)
#setup a canvas
def setcanvas():
t.setup(width = 500, height = 500, startx = 0, starty = 0)
t.ht()
t.pu()
t.setpos(-250,-250)
t.pd()
t.pencolor("red")
t.setpos(250,250)
t.pu()
t.setpos(-250,0)
t.pd()
t.setpos(250,0)
t.pu()
t.setpos(0,250)
t.pd()
t.setpos(0,-250)
def main():
row = 100
setcanvas()
rand = [[float(r.randrange(-250, 250)) for i in range(2)] for j in range(row)]
target = [0]*row
for i in range(row):
if rand[i][0] > rand[i][1]:
target[i] = 1
else:
target[i] = -1
to = [0]*row
t.pencolor("black")
for i in rand:
print(i)
paint(i)
for i in range(row):
to[i] = actuation_func(total(rand[i],w))
print(to)
print(w)
i = 0
flag = False
while not flag:
while i < row:
print("This is index:", i)
train(to[i], rand[i], target[i])
#print('before:', to[i], '--', target[i])
to[i] = actuation_func(total(rand[i],w))
#print('after:', to[i], '--', target[i])
if to[i] != target[i]:
t.pencolor("red")
paint(rand[i])
#print(i, "Wrong!")
flag = False
i = 0
else:
t.pencolor("green")
paint(rand[i])
#print(i, "resolve")
i+=1
i = 0
while i < row:
to[i] = actuation_func(total(rand[i],w))
if to[i] != target[i]:
i = 0
print("not pass second test")
flag = False
break
else:
i+=1
flag = True
print(w)
print(target)
print(to)
print()
print("Check")
for i in range(row):
to[i] = actuation_func(total(rand[i],w))
if to[i] != target[i]:
print("index:", i, "wrong")
print()
print(w)
print(target)
print(to)
main()