# -*- coding: utf-8 -*- """ Created on Sat Mar 19 13:49:04 2016 @author: fengxinhe """ import copy
from matplotlib import pyplot as pl
from matplotlib import animation as ani
"""
if y(wx+b)<=0,return false; else, return true
"""
#函数sign,判断误分类点,如果是误分类点返回"-1",否则返回"1"
def sign(vec):
global w,b
res=0
res=vec[1]*(w[0]*vec[0][0]+w[1]*vec[0][1]+b) #y(wx+b)
if res>0: return 1
else: return -1
"""
update the paramaters w&b
"""
#函数update,调整参数
def update(vec):
global w,b,record
w[0]=w[0]+yita*vec[1]*vec[0][0] #w = w + yita * yi * xi
w[1]=w[1]+yita*vec[1]*vec[0][1] #w = w + yita * yi * xi
b=b+yita*vec[1] #b = b + yita * yi
record.append([copy.copy(w),b])
"""
check and calculate the whole data one time
if all of the input data can be classfied correctly at one time,
we get the answer
"""
def perceptron():
count=1
for ele in data:
flag=sign(ele) #判断是否为误分类点
if not flag>0: #如果是误分类点则调整参数
count=1
update(ele)
else:
count+=1
if count>=len(data): #满足该条件表示已经全部正确分类
return 1
if __name__ == "__main__":
while 1:
if perceptron() > 0: #调用感知机函数,返回值大于0,表示全部正确分类,则跳出循环。
break
print record
x1=[]
y1=[]
x2=[]
y2=[]
#display the animation of the line change in searching process
fig = pl.figure()
ax = pl.axes(xlim=(-1, 5), ylim=(-1, 5))
line,=ax.plot([],[],'g',lw=2)
def init():
line.set_data([],[])
for p in data:
if p[1]>0:
x1.append(p[0][0])
y1.append(p[0][1])
else:
x2.append(p[0][0])
y2.append(p[0][1])
pl.plot(x1,y1,'or')
pl.plot(x2,y2,'ob')
return line,