-
Notifications
You must be signed in to change notification settings - Fork 0
/
1 感知机算法.py
101 lines (62 loc) · 1.35 KB
/
1 感知机算法.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
# -*- coding: utf-8 -*-
"""
Spyder Editor
This is a temporary script file.
感知机算法
Python 3.6
"""
import copy
#输入数据
trainist_set=[[(3,3),1],[(4,3),1],[(1,1),-1]]
w=[0,0]
b=0
#w和b更新
def update(item):
global w,b
#w分量的更新
w[0]=w[0]+1*item[1]*item[0][0]
w[1]=w[1]+1*item[1]*item[0][1]
#b分量的更新
b=b+1*item[1]
print("w=",w,",b=",b)
#返回yi(wx+b)的结果
def judge(item):
res=0
for i in range(len(item[0])):
res=item[0][i]*w[i] #w*x
res=res+b #w*x+b
res=res*item[1] #yi(wx+b)
return res
#检查数据点是否分对
def check():
flag=False
for item in trainist_set:
if judge(item)<=0:
flag=True
update(item)
return flag
if __name__ == '__main__':
flag=False
for i in range(1000):
if not check():
flag=True
break
if flag:
print("1000 all true")
else:
print("something error")
"""
运行结果
runfile('E:/ml/感知机算法.py', wdir='E:/ml')
w= [3, 3] ,b= 1
w= [2, 2] ,b= 0
w= [1, 1] ,b= -1
w= [0, 0] ,b= -2
w= [3, 3] ,b= -1
w= [2, 2] ,b= -2
w= [1, 1] ,b= -3
w= [4, 4] ,b= -2
w= [3, 3] ,b= -3
w= [2, 2] ,b= -4
1000 all true
"""