您的位置:首页 > 编程语言 > Python开发

模式识别(一):感知机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个为类别:

  • 点赞
  • 收藏
  • 分享
  • 文章举报
取不到名字的Z先生 发布了9 篇原创文章 · 获赞 4 · 访问量 551 私信 关注
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: