本文共 1604 字,大约阅读时间需要 5 分钟。
PLA全称是Perceptron Linear Algorithm,即线性感知机算法,属于一种最简单的感知机(Perceptron)模型。
import numpy as npx=np.array([[1,2],[3,4],[5,6],[10,1],[23,23]])y=np.array([1,-1,1,-1,1])#数据可视化import matplotlib.pyplot as plt# plt.scatter(x[:,0],x[:,1],color='blue',marker='o',label='POsitive')# plt.show()# 对数据进行归一化处理u=np.mean(x,0)v=np.var(x,0)x=(x-u)/v# print(x)# x 加上偏置x=np.hstack((np.ones((x.shape[0],1)),x))# 权重初始化w=np.random.rand(3,1)print(w)print(x)# 公式 w0*b+w1*x1+w2*x2=0# 直线第一个坐标(x1,y1)x1 = -2y1 = -1 / w[2] * (w[0] * 1 + w[1] * x1)# 直线第二个坐标(x2,y2)x2 = 2y2 = -1 / w[2] * (w[0] * 1 + w[1] * x2)# 作图# plt.scatter(x[:,1], x[:, 2], color='blue', marker='o', label='Positive')# plt.plot([x1,x2], [y1,y2],'r')# plt.show()# 计算scores=np.dot(x,w)y_predict=np.ones_like(y)loc_n=np.where(s<0)[0]y_predict[loc_n]=-1 # 获取预测的结果#接着从分类错误的样本中选择一个t=np.where(y_predict!=y)[0][0]w=y[t]*x[t,:].reshape((3,1))#更新权重w是个迭代过程,只要存在分类错误的样本,就不断进行更新,直至所有的样本都分类正确。(注意,前提是正负样本完全可分)for i in range(1000): s = np.dot(x, w) y_pred = np.ones_like(y) loc_n = np.where(s < 0)[0] y_pred[loc_n] = -1 num_fault = len(np.where(y != y_pred)[0]) print('第%2d次更新,分类错误的点个数:%2d' % (i, num_fault)) if num_fault == 0: break else: t = np.where(y != y_pred)[0][0] w += y[t] * x[t, :].reshape((3,1))#迭代完毕之后画出曲线# 直线第一个坐标(x1,y1)x1 = -2y1 = -1 / w[2] * (w[0] * 1 + w[1] * x1)# 直线第二个坐标(x2,y2)x2 = 2y2 = -1 / w[2] * (w[0] * 1 + w[1] * x2)# 作图plt.scatter(x[:,0],x[:,1],color='blue',marker='o',label='POsitive')# plt.show()plt.plot([x1,x2], [y1,y2],'r')plt.xlabel('Feature 1')plt.ylabel('Feature 2')plt.legend(loc = 'upper left')plt.show()
转载地址:http://mbwmi.baihongyu.com/