sklearn训练感知器用iris数据集
简化版代码
1 from sklearn import datasets 2 import numpy as np 3 4 #获取data和类标 5 iris = datasets.load_iris() 6 X = iris.data[:,[2,3]] 7 y = iris.target 8 9 #测试样本和训练样本三七分 10 from sklearn.model_selection import train_test_split 11 X_train,X_test,y_train,y_test = train_test_split(X,y,test_size=0.3,random_state=0) 12 13 #数据特征标准化 14 from sklearn.preprocessing import StandardScaler 15 sc = StandardScaler() 16 sc.fit(X_train) 17 X_test_std = sc.transform(X_test) 18 X_train_std = sc.transform(X_train) 19 20 #训练感知器模型 21 from sklearn.linear_model import Perceptron 22 ppn = Perceptron(max_iter=40,eta0=0.1,random_state=0) 23 ppn.fit(X_train_std,y_train) 24 25 #训练完成后,对测试数据进行预测 26 y_pred = ppn.predict(X_test_std) 27 print('Missclassified samples:%d'%(y_pred!=y_test).sum()) 28 from sklearn.metrics import accuracy_score 29 print('Accuracy:%.2f'%accuracy_score(y_test,y_pred))
解释版+可视化
from sklearn import datasets#iris已包含在sklearn库中 import numpy as np iris = datasets.load_iris()#提取150个花朵样本中的花瓣长度和花瓣宽度两个特征的值,并由此构建特征矩阵X,同时将对应花朵所属类型的类标赋值给向量y #打印出来iris可以发现iris包括的key包括五个值:data(其中有四列)、target、target_name、DESCR、feature_names #X提取的是data里面的3、4列,y提取的是target,即类型的类标#print(iris) #print(iris.keys()) #print(iris.data.shape) #print(iris.data[:5])#显示样本前五行,因为iris是字典不是列表,所以不能调用head()的方法获取前五行 X = iris.data[:, [2, 3]] y = iris.target#iris的每个样本都包含了品种信息,即目标属性(第5列,也叫target或label)'''如果执行np.unique(y)返回存储在iris.target中的各类花朵的类标,可以看到,scikit-learn已分别将Iris-Sentosa、Iris-Versicolor 和Iris-Virginia的类名另存为整数(0,1,2),对许多机器学习库来说,这是针对性能优化一种推荐的做法 print(np.unique(y)) ''' ''' 为了评估训练得到的模型在未知数据上的表现,我们进一步将数据集划分为训练数据集和测试数据集 使用scikit-learn中model_selection模块中的train_test_split函数,随机将数据矩阵X与类标向量y按照3:7的比例划分为测试数据集( 45个样本)和训练数据集(105个样本) ''' from sklearn.model_selection import train_test_split X_train, X_test, y_train,y_test = train_test_split(X, y, test_size=0.3, random_state=0) ''' 许多机器学习和优化算法都要求对数据做特征缩放。我们将使用scikit-learn的preprocessing模块中的StandardScaler类 对特征进行标准化处理 在下面的代码中,从preprocessing模块中加载了StandardScaler类,并实例化了一个StandScaler对象,用变量sc作为对它的引用 使用StandardScaler中的fit方法,可以计算训练数据中的每个特征的μ(样本均值)和σ(标准差)。通过调用transform方法, 可以使用前面计算得到的μ和σ来对训练数据做标准化处理。注意:需要使用相同的缩放参数分别处理训练和测试数据。 ''' from sklearn.preprocessing import StandardScaler sc = StandardScaler() sc.fit(X_train) X_train_std = sc.transform(X_train) X_test_std = sc.transform(X_test) ''' 在对训练数据做了标准化处理后,下面训练感知器模型 ''' from sklearn.linear_model import Perceptron ppn = Perceptron(max_iter=40, eta0=0.1, random_state=0)#n_iter是迭代次数,eta是学习速率,random_state参数在每次迭代后初始化重新排练数据集 ppn.fit(X_train_std, y_train) ''' 使用scikit-learn完成模型的训练后,就可以在测试数据集上使用predict方法进行预测了 ''' y_pred = ppn.predict(X_test_std)#predict class labels for samples in X print('Misclassified samples:%d'%(y_test != y_pred).sum()) ''' 计算感知器在测试数据集上的分类准确率 ''' from sklearn.metrics import accuracy_score print('Accuracy:%.2f' % accuracy_score(y_test,y_pred))''' 使用plot_decision_regions函数来绘制刚刚训练过得模型的决策区域,并观察不同花朵样本的分类项 ''' from matplotlib.colors import ListedColormap import matplotlib.pyplot as pltdef plot_decision_regions(X,y,classifier,test_idx = None,resolution = 0.02):#setup marker generator and color mapmarkers = ('s', 'x', 'o', '^', 'v')colors = ('red', 'blue', 'lightgreen', 'gray', 'cyan')cmap = ListedColormap(colors[:len(np.unique(y))])#plot the decision surfacex1_min, x1_max = X[:, 0].min()-1, X[:, 0].max()+1x2_min, x2_max = X[:, 0].min()-1, X[:, 1].max()+1xx1, xx2 = np.meshgrid(np.arange(x1_min, x1_max, resolution), np.arange(x2_min, x2_max, resolution))Z = classifier.predict(np.array([xx1.ravel(), xx2.ravel()]).T)Z = Z.reshape(xx1.shape)plt.contourf(xx1, xx2, Z, alpha=0.4, cmap=cmap)plt.xlim(xx1.min(), xx1.max())plt.ylim(xx2.min(), xx2.max())#plot all samplesX_test,y_test = X[test_idx, :], y[test_idx]for idx, cl in enumerate(np.unique(y)):plt.scatter(x=X[y == cl, 0], y=X[y == cl, 1], alpha=0.8, c=cmap(idx), marker=markers[idx], label=cl)#highlight test samplesif test_idx:X_test, Y_test = X[test_idx, :], y[test_idx]plt.scatter(X_test[:, 0],X_test[:, 1], c='', alpha=1.0, linewidth=1, marker='o', s=55, label='test set') X_combined_std = np.vstack((X_train_std, X_test_std)) Y_combined = np.hstack((y_train, y_test)) plot_decision_regions(X=X_combined_std,y=Y_combined,classifier=ppn,test_idx=range(105, 150)) plt.xlabel('petal length [standardized]') plt.ylabel('petal width [standardized]') plt.legend(loc='upper left') print(plt.show())
自己手动注释
转载于:https://www.cnblogs.com/aixiao07/p/9038059.html
sklearn训练感知器用iris数据集相关推荐
- 【Python-ML】SKlearn库感知器(perceptron) 使用
# -*- coding: utf-8 -*- ''' Created on 2018年1月12日 @author: Jason.F @summary: Scikit-Learn库感知器学习算法 '' ...
- 逻辑回归(Logistic regression)详解-并用scikit-learn训练逻辑回归拟合Iris数据集
这篇文章主要介绍逻辑回归背后的一些概率概念,给你一些直观感觉关于它的代价函数的由来.并且我也介绍了关于最大似然估计(maximum likelihood)的概念,用这个强大的工具来导出逻辑回归的cos ...
- Python机器学习iris数据集预处理和模型训练
机器学习模型训练 一.iris数据集简介 二.基本数据操作和模型训练 一.iris数据集简介 iris数据集的中文名是安德森鸢尾花卉数据集,英文全称是Anderson`s Iris data set. ...
- Sklearn学习-iris数据集学习
Sklearn学习-逻辑回归(iris数据集) 使用load_iris加载数据集,查看包含的keys 查看数据的列名,分类目标的名称 获取data和target,并打印各自的shape 拆分训练集和测 ...
- 神经网络入门回顾(感知器、多层感知器)
神经网络属于"联结主义",和统计机器学习的理论基础区别还是很不一样. 以我自己的理解,统计机器学习的理论基于统计学,理论厚度足够强,让人有足够的安全感:而神经网络的理论更侧重于代数 ...
- 感知器及其在python中的实现_感知器及其在Python中的实现
什么是感知器? 生物神经元示意图 感知器的概念类似于大脑基本处理单元神经元的工作原理.神经元由许多由树突携带的输入信号.胞体和轴突携带的一个输出信号组成.当细胞达到特定阈值时,神经元会发出一个动作信号 ...
- 【火炉炼AI】深度学习001-神经网络的基本单元-感知器
[火炉炼AI]深度学习001-神经网络的基本单元-感知器 (本文所使用的Python库和版本号: Python 3.6, Numpy 1.14, scikit-learn 0.19, matplotl ...
- 支持向量机SVM Iris数据集 分类预测
目录 支持向量机对iris数据集进行分类预测 1. 基础概念 2. 实验步骤与分析 2.1 数据理解 2.2 数据读入 2.3 训练集和测试集划分 2.4 支持向量机 2.5 预测 2.6 ...
- 感知器算法解决xor函数
from itertools import count import numpy import random #用到的库.step_function = lambda x: 1 if x>=0 ...
最新文章
- mysql union group by_Mysql UNION和GROUP BY
- 32位数据源中没有mysql_[SpringBoot实战]快速配置多数据源(整合MyBatis)
- python杨辉三角_yiduobo的每日leetcode 118.杨辉三角 amp;amp; 119.杨辉三角II
- idea python工程zip打包_【面试划重点】-- Python常见知识点
- linux下用c语言写黄金矿工,C语言写的黄金矿工O(∩_∩)O---初稿,能玩了
- 第六届省赛(软件类)真题----Java大学C组答案及解析
- 不止承上启下,带你了解工业物联网关
- i3wm学习笔记-基础快捷键
- linux u盘无损分区,Unix/Linux无损分区解决方案[原创]
- 【图神经网络】ChebyNet-切比雪夫多项式近似图卷积核
- 卡西欧电子词典EV-SP3900(英汉日版)
- 手机qq2010java触屏_手机QQ2010(Java触屏)Beta2发布:操作更流畅
- 联通光猫上海贝尔阿尔卡特 100A-AA 刷 OpenWRT
- python协程爬取斗鱼美女图片
- 程序员《周易》入门一
- setTimeout 实现 setInterval
- 可视化网络拓扑:两天之内从零到英雄
- 2021-09-02 Day17-JS-第七天 Web APIs和DOM
- ecg心率和ppg心率区别_基于ppg的心率变异性hrv分析的伪影去除
- 炎炎夏日教你利用小米智能家居配件+树莓派4接入Apple HomeKit