机器学习中感知机的Python实现——解决分类中的线性可分问题

什么是线性可分问题

线性可分就是说可以用一个线性函数把两类样本分开,比如二维空间中的直线、三维空间中的平面以及高维空间中的线性函数。所谓可分指可以没有误差地分开。

Python实现

import numpy as np
import matplotlib.pyplot as plt

# 读入训练数据
train = np.loadtxt('images1.csv', delimiter=',', skiprows=1)
train_x = train[:, 0:2]
train_y = train[:, 2]

# 权重的初始化
w = np.random.rand(2)


# 判别函数
def f(x):
    if np.dot(w, x) >= 0:
        return 1
    else:
        return -1


# 重复次数
epoch = 10

# 更新次数
count = 0

# 学习权重
for _ in range(epoch):
    for x, y in zip(train_x, train_y):
        if f(x) != y:
            w = w + y * x
            # 输出日志
            count += 1
            print('第{}次:w={}'.format(count, w))

# 绘图
x1 = np.arange(0, 500)
# Numpy多维数组索引与布尔索引的混合操作
# 大前提是train_x(数组轴索引)和train_y(定义的布尔值数组)长度相同,参考链接:https://blog.csdn.net/weixin_59131972/article/details/129668117
plt.plot(train_x[train_y == 1, 0], train_x[train_y == 1, 1], 'o')
plt.plot(train_x[train_y == -1, 0], train_x[train_y == -1, 1], 'x')
plt.plot(x1, -w[0] / w[1] * x1, linestyle='dashed')
# axis('equal') 更改 x 或 y 轴的限制,以便 x 和 y 的相等增量具有相同的长度;一个圆是圆形的。
# axis('scaled') 通过更改图框的尺寸而不是轴数据限制来实现相同的结果。
plt.axis('scaled')
plt.show()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

秃头鸭鸭鸭

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

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

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

打赏作者

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

抵扣说明:

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

余额充值