用sk实现感知机

该博客介绍了如何使用sklearn库中的Perceptron类实现感知机模型,通过鸢尾花数据集进行训练和测试。首先加载数据,然后划分训练集和测试集,接着训练感知机模型,并输出模型参数。最后,绘制了感知机决策边界的示意图。
摘要由CSDN通过智能技术生成

#载入相关模块
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
%matplotlib inline
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from collections import Counter

#载入数据
iris = load_iris()
z = pd.DataFrame(iris.data,columns=iris.feature_names)
z[‘label’] = iris.target
z.columns = [‘sepal length’, ‘sepal width’, ‘petal length’, ‘petal width’, ‘label’]

#提取特征和样品
#取前面100个数,第一列、第二列和最后一列
data = np.array(z.iloc[:100, [0, 1, -1]])
#最后一个特征作为标签,其他的作为特征
X, y = data[:,:-1], data[:,-1]
#取80%作为训练,20%作为测试
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)

#载入sklearn中的感知机模块
import sklearn
from sklearn.linear_model import Perceptron

l = Perceptron(fit_intercept=True,
max_iter=1000,
shuffle=True)
l.fit(X_train, y_train)

# 输出感知机参数
print(l.coef_)

#画图
#画布大小
plt.figure(figsize=(10,10))
#中文标题
plt.rcParams[‘font.sans-serif’]=[‘SimHei’]
plt.rcParams[‘axes.unicode_minus’] = False
plt.title(‘鸢尾花线性数据示例’)

plt.scatter(data[:50, 0], data[:50, 1], c=‘b’, label=‘Iris-setosa’,)
plt.scatter(data[50:100, 0], data[50:100, 1], c=‘orange’, label=‘Iris-versicolor’)

#画感知机的线
x_ponits = np.arange(4, 8)
y_ = -(l.coef_[0][0]*x_ponits + l.intercept_)/l.coef_[0][1]
plt.plot(x_ponits, y_)

#其他部分
plt.legend() # 显示图例
plt.grid(False) # 不显示网格
plt.xlabel(‘sepal length’)
plt.ylabel(‘sepal width’)
plt.legend()

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值