模式识别(一):感知机python实现

模式识别(一):感知机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个为类别:
在这里插入图片描述

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

取不到名字的Z先生

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值