博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
线性可分感知机
阅读量:4209 次
发布时间:2019-05-26

本文共 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/

你可能感兴趣的文章
【一天一道LeetCode】#47. Permutations II
查看>>
【一天一道LeetCode】#48. Rotate Image
查看>>
【一天一道LeetCode】#56. Merge Intervals
查看>>
【一天一道LeetCode】#57. Insert Interval
查看>>
【一天一道LeetCode】#58. Length of Last Word
查看>>
【一天一道LeetCode】#59. Spiral Matrix II
查看>>
【一天一道LeetCode】#30. Substring with Concatenation of All Words
查看>>
【一天一道LeetCode】#60. Permutation Sequence.
查看>>
【一天一道LeetCode】#113. Path Sum II
查看>>
【一天一道LeetCode】#114. Flatten Binary Tree to Linked List
查看>>
【unix网络编程第三版】阅读笔记(二):套接字编程简介
查看>>
【一天一道LeetCode】#115. Distinct Subsequences
查看>>
【一天一道LeetCode】#116. Populating Next Right Pointers in Each Node
查看>>
【一天一道LeetCode】#117. Populating Next Right Pointers in Each Node II
查看>>
【一天一道LeetCode】#118. Pascal's Triangle
查看>>
【一天一道LeetCode】#119. Pascal's Triangle II
查看>>
【unix网络编程第三版】阅读笔记(三):基本套接字编程
查看>>
同步与异步的区别
查看>>
IT行业--简历模板及就业秘籍
查看>>
JNI简介及实例
查看>>