模式识别(一):感知机python实现
2020-04-22 08:35
841 查看
模式识别(一):感知机python实现
课件PPT资源下载:
https://download.csdn.net/download/qq_42233962/12285717
import numpy as np import pandas as pd import matplotlib.pyplot as plt # load data from xlsx df = pd.read_excel(io = 'lris.xlsx',header = None) #读取数据为Dataframe结构,没有表头行 label = df.iloc[0:100,4].values #取前100列数据,4列为标识 label = np.where(label == 'Iris-setosa', -1,1) data = df.iloc[0:100,[0,2]].values #iloc为选取表格区域,此处取二维特征进行分类,values为返回不含索引的表 # 初始化w, b, alpha w = np.array([0, 0]) b = 0 alpha = 1 # 计算 y*(w*x+b) f = (np.dot(data, w.T) + b) * label idx = np.where(f <= 0) #记录分类错误的坐标,f的矩阵有几维,idx就有几个 # 使用随机梯度下降法求解w, b iteration = 1 while f[idx].size != 0: point = np.random.randint(f[idx].shape[0]) #求出f矩阵的列长度L,并从【0,L-1】中随机取一个数 x = data[idx[0][point]] #f只有1维,找出一个训练出错的数据 y = label[idx[0][point]] #f只有1维(idex【0】),找出一个训练出错的标签 w = w + alpha * y * x b = b + alpha * y print('Iteration:%d w:%s b:%s' % (iteration, w, b)) f = (np.dot(data, w.T) + b) * label idx = np.where(f <= 0) iteration = iteration + 1 # 绘图显示以及实现新数据的分类功能 test = (2,3) test_label=(np.dot(test, w.T) + b)and 1 or -1 #相当于问号表达式 print(test_label) x1 = np.arange(0, 8, 0.1) x2 = (w[0] * x1 + b) / (-w[1]) idx_p = np.where(label == 1) idx_n = np.where(label != 1) data_p = data[idx_p] data_n = data[idx_n] plt.scatter(data_p[:, 0], data_p[:, 1], color='red') plt.scatter(data_n[:, 0], data_n[:, 1], color='blue') plt.scatter(test[0], test[1], color='green') plt.plot(x1, x2) plt.show() print('\nPerceptron learning algorithm is over')
补充:“lris.xlsx”这个文件的格式如下(可以自己创建一个),前4个为特征,第5个为类别:
- 点赞
- 收藏
- 分享
- 文章举报
相关文章推荐
- 感知机(Perceptron)的python实现
- 感知机原理及python实现
- 统计学习方法 感知机python实现
- python 实现 Peceptron Learning Algorithm ( 二) 感知机模型实现
- 感知机相关概念及Python实现
- python 实现 Peceptron Learning Algorithm ( 三) 感知机模型应用于Iris数据集
- 感知机实现Python
- 统计学习方法笔记1——感知机(perceptron)的Python实现
- python 实现简单的感知机
- python 实现 Peceptron Learning Algorithm ( 二) 感知机模型实现
- Python实现PLA(感知机)
- 感知机相关概念及Python实现
- python 实现 Peceptron Learning Algorithm ( 三) 感知机模型应用于Iris数据集
- 用python实现感知机
- 感知机学习算法 python实现
- 统计学习方法(2)——感知机原始形式、对偶形式及Python实现
- 神经网络之多层感知机MLP的实现(Python+TensorFlow)
- python 实现 Peceptron Learning Algorithm ( 二) 感知机模型实现
- 感知机相关概念及Python实现
- python 实现 Peceptron Learning Algorithm ( 二) 感知机模型实现