感知器——python实现

import numpy as np;
import matplotlib  
import matplotlib.pyplot as plt

X = np.mat([[1.24,1.27],[1.36,1.74],[1.38,1.64],[1.38,1.82],[1.38,1.90],[1.40,1.70],[1.48,1.82],[1.54,1.82],
            [1.56,2.08],[1.14,1.82],[1.18,1.96],[1.20,1.86],[1.26,2.00],[1.28,2.00],[1.30,1.96]]);

#plt.plot(X[:,0],X[:,1],'o')# use pylab to plot x and y
#pl.xlim(0.0, 2.0)# set axis limits
#pl.ylim(0.0, 2.0)
#plt.show()# show the plot on the screen


def perce(X,y,rho,w_ini):
    N,C = X.shape                  # 训练样本集的大小
    max_iter = 10000               # 最大允许的迭代次数               
    w = w_ini                      # 初始化的参数向量,比如 w_ini=[0;0];
    iter = 0                       # 迭代计数器,初置为0
    mis_clas=N                     # 分类错误数,可初置为N

    while (mis_clas>0 and iter<max_iter): #停机准则:分类完全正确或达到最大迭代次数
        iter = iter + 1                   # (外循环)迭代计数
        mis_clas = 0                      # 进行新一次内循环前,回置分类错误数为0
        gradi = np.zeros((C,1),dtype=int)            # 回置“梯度”为0
        for i in range(0,N):                 # 内循环,每次学习完全部训练样本
            if((X[i] * w) * y[i] < 0):       # 判断:在第i个样本上是否分类错误
                mis_clas = mis_clas + 1      # 分类错误计数
                gradi =  gradi + rho * (X[i].transpose() * -y[i]) # 计算“梯度”
        w=w-rho*gradi               # 更新参数向量
                
    EN = mis_clas                   # 最终分类(训练)错误
    print '感知器错误分类率=%f\t当rho=%f\n' % (EN/N,rho)  #显示分类错误率
    return w
        
y1 = np.mat(np.ones((9,1),dtype=int))
y2 = np.mat(-np.ones((6,1),dtype=int))
y = np.vstack((y1,y2))             #按列合并,即增加行数
#print y
rho = 0.05                         #学习速率
w_ini = np.mat([[0.5],[0.5]]);     # 初始权重
w = perce(X,y,rho,w_ini)           # 调用编写的函数
print w


N,C = X.shape
for i in range(0,N):
    if X[i] * w > 0:
        plt.plot(X[i,0],X[i,1],'ro')# use pylab to plot x and y
    else:
        plt.plot(X[i,0],X[i,1],'bo')# use pylab to plot x and y

plt.show()# show the plot on the screen


感知器错误分类率=0.000000	当rho=0.050000

[[ 0.1565 ]
 [-0.10955]]



  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值