python导入鸢尾花数据集_python鸢尾花数据集的分类问题 -- 逻辑回归问题研究

原标题:python鸢尾花数据集的分类问题 -- 逻辑回归问题研究

1.背景介绍

1.1. 逻辑回归

Logistic Regression (对数几率回归 Logit Regression)名字关于名字,有文献将Logistic Regression译为“逻辑回归”, 但中文“逻辑”与logitic 和 logit 的含义相去甚远,因此在《机器学习》中意译为“对数几率回归”,简称“对率回归”。

线性回归在介绍对数几率回归之前先介绍一下线性回归,线性回归的主要思想是通过历史数据拟合出一条直线,因变量与自变量是线性关系,对新的数据用这条直线进行预测。 线性回归的公式如下:

~y=w0+w1x1+...+wnxn=wTx+b

逻辑回归对数几率回归是一种广义的线性回归分析模型,是一种预测分析。虽然它名字里带回归,但实际上对数几率回归是一种分类学习方法。它不是仅预测出“类别”, 而是可以得到近似概率预测,这对于许多需要利用概率辅助决策的任务很有用。普遍应用于预测一个实例是否属于一个特定类别的概率,比如一封email是垃圾邮件的概率是多少。 因变量可以是二分类的,也可以是多分类的。因为结果是概率的,除了分类外还可以做ranking model。LR的应用场景很多,如点击率预测(CTR)、天气预测、一些电商的购物搭配推荐、一些电商的搜索排序基线等。

对数几率函数是一种“Sigmoid”函数,呈现S型曲线,它将~z

值转化为一个接近0或1的 ~y

值。 对数几率回归公式如下:

~y=g(z)=11+e−z

, ~z=wTx+b

其中,~y=11+e−x

被称作Sigmoid函数。

Logistic Regression算法是将线性函数的结果映射到了Sigmoid函数中,即~y=11+e(wTx+b)

Sigmoid函数下图绘制了Sigmoid函数形状,如图所示,sigmoid函数输出值范围在(0,1)之间,即代表了数据属于某一类别的概率,0.5是作为判别的临界值。

In [3]:

# Sigmoid曲线:

df119511a1064ed5811481d44db9400c.png

1.2.IRIS数据集介绍

Iris也称鸢尾花卉数据集,是常用的分类实验数据集,由R.A. Fisher于1936年收集整理的。其中包含3种植物种类,分别是山鸢尾(setosa)变色鸢尾(versicolor)和维吉尼亚鸢尾(virginica),每类50个样本,共150个样本。

该数据集包含4个特征变量,1个类别变量。iris每个样本都包含了4个特征:花萼长度,花萼宽度,花瓣长度,花瓣宽度,以及1个类别变量(label)。我们需要建立一个分类器,分类器可以通过这4个特征来预测鸢尾花卉种类是属于山鸢尾,变色鸢尾还是维吉尼亚鸢尾。其中有一个类别是线性可分的,其余两个类别线性不可分,这在最后的分类结果绘制图中可观察到。

变量名变量解释数据类型sepal_length花萼长度(单位cmnumericsepal_width花萼宽度(单位cm)numericpetal_length花瓣长度(单位cm)numericpetal_width花瓣宽度(单位cm)numericspecies种类categorical

In [4]:

# 导入所需要的包

import pandas as pd

import numpy as np

import matplotlib.pyplot as plt

import plotly.plotly as py

import plotly.graph_objs as go

from sklearn.decomposition import PCA

1.2.1. 数据集预览

1.2.2. 鸢尾花三类品种数量的饼图

fig = go.Figure(data=[trace], layout=layout)

iplot(fig)

33.3%

33.3%

33.3%

In [8]:

# Feature Plot

8f326f33626c41fc89f1016ea9cab8c7.png

1.2.3. 绘制数据集的特征散点图特征对两两之间的相关性散点图: 如图所示,特征散点图成对角分布,4个特征两两组合(任意两个特征作为x轴,y轴),不同品种的花用不同颜色标注:setosa(橙色),versicolor(绿色),virginica(粉色)。共有12种组合,其实只有6种,因为另外6种与之对称。

In [9]:

7125a83bd20543cb95686421b3e3b276.png

2. Getting Started

2.1. 导入鸢尾花数据集矩阵在这篇入门教程中,暂且不进行数据转换至numpy矩阵的指导,因为scikit库中已经内置了矩阵形式的iris数据集,我们可以直接导入使用。 如果想了解 如何将原始数据转变成机器学习算法可学习的numpy数据集,以及 数据预处理 和 降维 的小伙伴,可以关注下一篇教程 用逻辑回归实现鸢尾花数据集分类(2)。

In [10]:

iris = load_iris()

les in total,%s features."%(iris.data.shape[0], iris.data.shape[1]))

target代表150个样本对应的类别label,即150行x1列的矩阵

样本的类别label含义

Class LabelMeaning0山鸢尾(setosa)1变色鸢尾(versicolor))2维吉尼亚鸢尾(virginica)

iris.target

Out[15]:

array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,

0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,

0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,

1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,

1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,

2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,

2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2])

2.2 创建训练集与测试集在这里我们先前取两列数据(即特征花萼长度与宽度)进行对数几率回归的分类。这个例子借鉴于此。 用train_test_split函数将原始数据集按7:3的比例分成训练集与测试集

2.3. 模型搭建与分类器训练

导入模型,调用逻辑回归LogisticRegression()函数。

penalty: 正则化选择参数(惩罚项的种类),默认方式为L2正则化

C: 正则项系数的倒数

solver: 对于多分类任务, 使用‘newton-cg’, ‘sag’, ‘saga’ and ‘lbfgs’ 来解决多项式loss

multi_class: 默认值‘ovr’适用于二分类问题,对于多分类问题,用‘multinomial’在全局的概率分布上最小化损失

训练LogisticRegression分类器

调用fit(x,y)的方法来训练模型,其中x为数据的属性,y为所属类型。

利用训练得到的模型对数据集进行预测 predict(),返回预测结果。

Tips: 可以通过点击cell中的~+ 来“添加代码片段功能”来直接导入需要的代码

In [20]:

from sklearn.linear_model import LogisticRegression

# lr = LogisticRegression(C = 1e5) # C: Inverse of regularization strength

lr = LogisticRegression(penalty='l2',solver='newton-cg',multi_class='multinomial')

lr.fit(x_train,y_train)

2.4. 模型评估

In [21]:

print("Logistic Regression模型训练集的准确率:%.3f" %lr.score(x_train, y_train))

print("Logistic Regression模型测试集的准确率:%.3f" %lr.score(x_test, y_test))

Logistic Regression模型训练集的准确率:0.829

Logistic Regression模型测试集的准确率:0.822

LogisticRegression分类器正确率分析

In [22]:

setosa 1.00 1.00 1.00 16

versicolor 0.81 0.72 0.76 18

virginica 0.62 0.73 0.67 11

avg / total 0.83 0.82 0.82 45

2.5. 可视化分类结果

绘制图像下图会绘制逻辑回归分类器在鸢尾花数据集上的决策边界,不同类别的数据点用不同颜色标注。 为了能可视化分类效果,我们会画出决策边界(decision boundry)。

1.确定坐标轴范围,x,y轴各表示一个特征

- 先取二维数组的第一列特征(花萼长度)的最大最小值和步长h = .02生成数组,

- 再取二维数组的第二列特征(花萼宽度)的最大最小值和步长h = .02生成数组,

最后由meshgrid()函数在网格[x_min, x_max] x [y_min, y_max] 中绘制出。生成两个网格矩阵x1, x2

类的三类区域

plt.show()

a0564f3cc67a43c09d5a036306f84f2f.png

如图所示,setosa类线性可分,而versicolor类与virginica类线性不可分。

▍关注我们

 趋势报告、案例精选、最新洞察 第一时间与您分享

【拓端数据】第三方数据服务提供商,提供全面的统计分析与数据挖掘咨询服务,为客户定制个性化的数据解决方案与行业报告等。

官网: tecdat.cn

微信公众号:拓端数据

商务合作:contact@tecdat.cn返回搜狐,查看更多

责任编辑:

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
你可以使用Scikit-learn库中的`load_iris()`函数来导入鸢尾花数据集,示例如下: ```python from sklearn.datasets import load_iris # 导入鸢尾花数据集 iris = load_iris() # 查看数据集的描述信息 print(iris.DESCR) # 获取数据集的特征数据和标签数据 X = iris.data y = iris.target # 查看特征数据和标签数据的形状 print('特征数据的形状:', X.shape) print('标签数据的形状:', y.shape) ``` 输出结果如下: ``` .. _iris_dataset: Iris plants dataset -------------------- **Data Set Characteristics:** :Number of Instances: 150 (50 in each of three classes) :Number of Attributes: 4 numeric, predictive attributes and the class :Attribute Information: - sepal length in cm - sepal width in cm - petal length in cm - petal width in cm - class: - Iris-Setosa - Iris-Versicolour - Iris-Virginica :Summary Statistics: ============== ==== ==== ======= ===== ==================== Min Max Mean SD Class Correlation ============== ==== ==== ======= ===== ==================== sepal length: 4.3 7.9 5.84 0.83 0.7826 sepal width: 2.0 4.4 3.05 0.43 -0.4194 petal length: 1.0 6.9 3.76 1.76 0.9490 (high!) petal width: 0.1 2.5 1.20 0.76 0.9565 (high!) :Missing Attribute Values: None :Class Distribution: 33.3% for each of 3 classes. :Creator: R.A. Fisher :Donor: Michael Marshall (MARSHALL%PLU@io.arc.nasa.gov) :Date: July, 1988 The famous Iris database, first used by Sir R.A. Fisher. The dataset is taken from Fisher's paper. Note that it's the same as in R, but not as in the UCI Machine Learning Repository, which has two wrong data points. This is perhaps the best known database to be found in the pattern recognition literature. Fisher's paper is a classic in the field and is referenced frequently to this day. (See Duda & Hart, for example.) The data set contains 3 classes of 50 instances each, where each class refers to a type of iris plant. One class is linearly separable from the other 2; the latter are NOT linearly separable from each other. .. topic:: References - Fisher, R.A. "The use of multiple measurements in taxonomic problems" Annual Eugenics, 7, Part II, 179-188 (1936); also in "Contributions to Mathematical Statistics" (John Wiley, NY, 1950). - Duda, R.O., & Hart, P.E. (1973) Pattern Classification and Scene Analysis. (Q327.D83) John Wiley & Sons. ISBN 0-471-22361-1. See page 218. - Dasarathy, B.V. (1980) "Nosing Around the Neighborhood: A New System Structure and Classification Rule for Recognition in Partially Exposed Environments". IEEE Transactions on Pattern Analysis and Machine Intelligence, Vol. PAMI-2, No. 1, 67-71. - Gates, G.W. (1972) "The Reduced Nearest Neighbor Rule". IEEE Transactions on Information Theory, May 1972, 431-433. - See also: 1988 MLC Proceedings, 54-64. Cheeseman et al"s AUTOCLASS II conceptual clustering system finds 3 classes in the data. 特征数据的形状: (150, 4) 标签数据的形状: (150,) ``` 其中,`iris.data`为特征数据,`iris.target`为标签数据。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值