找回密码
 立即注册

扫一扫,访问微社区

QQ登录

只需一步,快速开始

查看: 1546|回复: 0

[求助] python感知机算法实现,球球了有偿,最后di'y做出来了的我....

1

主题

1

帖子

1

积分

贫民

积分
1
Superb_Z 发表于 2022-5-25 09:46:58 | 显示全部楼层 |阅读模式
2威望
# -*- 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  
  
w=[0,0]  #系数,初始化为0
b=0      #偏移量,初始化为0
yita=0.5   #学习率
data=[[(1,4),1],[(0.5,2),1],[(2,2.3), 1], [(1, 0.5), -1], [(2, 1), -1],[(4,1),-1],[(3.5,4),1],[(3,2.2),-1]]  #数据
record=[]  
  
"""
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,  
  
  
def animate(i):  
    global record,ax,line  
    w=record[0]  
    b=record[1]  
    x1=-5  
    y1=-(b+w[0]*x1)/w[1]  
    x2=6  
    y2=-(b+w[0]*x2)/w[1]  
    line.set_data([x1,x2],[y1,y2])  
    return line,  
      
animat=ani.FuncAnimation(fig,animate,init_func=init,frames=len(record),interval=1000,repeat=True,  
                                   blit=True)  
pl.show()  
要怎么样才可以达到这样的效果

回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

快速回复 返回顶部 返回列表