使用这个著名的数据集IRIS开始构建你的第一个机器学习项目

使用这个著名的数据集开始构建您的第一个机器学习项目

在这里插入图片描述

  • 每个机器学习项目都适于了解什么数据并得出目标。在将机器学习算法应用于数据集时,你正在理解、构建和分析数据以获得最终结果。

  • 以下是创建定义良好的ML项目所涉及的步骤:
    1. 了解并定义问题
    2. 分析并准备数据
    3. 应用算法
    4. 减少错误
    5. 预测结果

  • 为了了解各种机器学习算法,让我们使用Iris数据集,该数据集是可用的最著名的数据集之一。

在这里插入图片描述

1.问题描述

  • 该数据集由三种花的物理参数组成:Versicolor、Setosa和Virginica。数据集包含的数字参数是“Sepal(花萼) length”、“Sepal width”、“Petal(花瓣) length”和“Petal width”。在这些数据中,我们将基于这些参数预测花朵的类别。该数据由描述各个特征尺寸的连续数值组成。我们将基于这些功能来训练模型。

  • 让我们深入研究ML项目的构建。我们将使用Python来理解和训练我们的模型。
  • Numpy、Pandas、matplotlib和SciKit Learn(sklearn)是Python中的一些第三方库。
    • 第三方库一般需要单独下载,如:pip install numpy
    • 注:sklearn依赖于scipy,而scipy依赖于numpy+mkl;建议直接安装Anaconda,集成了python环境和机器学习的库等等
# Numpy支持大量的维度数组与矩阵运算,此外也针对数组运算提供大量的数学函数库。
import numpy as np
# Pandas是基于NumPy的一种工具,该工具是为了解决数据分析任务而创建的。
import pandas as pd
# Matplotlib是Python的绘图库,其中的pyplot包封装了很多画图的函数。
# https://baijiahao.baidu.com/s?id=1645640305376517667&wfr=spider&for=pc
import matplotlib.pyplot as plt
# metris指标;accuracy_score(分类)准确率分数
# https://blog.csdn.net/u011630575/article/details/79645814
from sklearn.metrics import accuracy_score
# LinearRegression(基于最小二乘法的)线性回归
# https://blog.csdn.net/weixin_39175124/article/details/79465558
from sklearn.linear_model import LinearRegression
# LogisticRegression逻辑回归
# https://blog.csdn.net/u012915522/article/details/100025541
from sklearn.linear_model import LogisticRegression
# ensemble整体;RandomForestClassifier随机森林分类器
# https://blog.csdn.net/qq_29750461/article/details/81516008
from sklearn.ensemble import RandomForestClassifier
# neighbors邻居;KNeighborsClassifier K-近邻
# https://www.cnblogs.com/YukiNote/p/11381246.html
from sklearn.neighbors import KNeighborsClassifier
# 支持向量机SVC
# https://blog.csdn.net/qq_41577045/article/details/79859902
from sklearn.svm import SVC

建议初学者学习前,打开以上的全部网站

  • Iris数据集已在SciKit Learn库中提供,我们可以使用以下代码直接将其导入:
from sklearn import datasets
iris = datasets.load_iris()
/Users/zhaowenchuan/anaconda3/lib/python3.7/importlib/_bootstrap.py:219: RuntimeWarning: numpy.ufunc size changed, may indicate binary incompatibility. Expected 192 from C header, got 216 from PyObject
  return f(*args, **kwds)
  • 鸳尾花的参数可以用下图所示的数据框的形式表示,‘class’列告诉我们它属于哪个类别(目标)。
# sklearn提供了iris2种数据类:data特征X,target目标y。
iris_data = iris.data
iris_data = pd.DataFrame(iris_data, columns=iris.feature_names)
iris_data['class'] = iris.target  # 添加列
iris_data.head()
sepal length (cm)sepal width (cm)petal length (cm)petal width (cm)class
05.13.51.40.20
14.93.01.40.20
24.73.21.30.20
34.63.11.50.20
45.03.61.40.20
  • 如上所述,我们的数据集中有三种花。让我们看一下每朵花的目标(target)名称吧。
# 方法一:通过sklearn通过的iris自带的类
iris.target_names
array(['setosa', 'versicolor', 'virginica'], dtype='<U10')
# 方法二:通过前面生成的iris_data二维表(DataFrame)查看
iris_data['class'].value_counts()
2    50
1    50
0    50
Name: class, dtype: int64
  • 需要向上游确定0,1,2分别表示哪种花;以下仅针对sklearn提供的iris
# 查看sklearn提供的iris有哪些函数调用方法
dir(iris)
['DESCR', 'data', 'feature_names', 'filename', 'target', 'target_names']
# help
print(iris.DESCR)
# 大致确认:0-Setosa\1-Versicolour\2-Virginica
.. _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.
   - Many, many more ...

2.了解数据

  • 这是一个相对较小的数据集,只有150个样本。由于数据框具有四个特征(“Sepal(花萼) length”、“Sepal width”、“Petal(花瓣) length”和“Petal width”),其中’class’特征(列)的150个样本属于三个目标类别之一(‘setosa’, ‘versicolor’, ‘virginica’),因此我们的矩阵为:
print(iris_data.shape)
(150, 5)
  • 现在进入数据集的数字,让我们找出数据的标准差、均值、最小值和四个四分位数。
iris_data.describe()
sepal length (cm)sepal width (cm)petal length (cm)petal width (cm)class
count150.000000150.000000150.000000150.000000150.000000
mean5.8433333.0573333.7580001.1993331.000000
std0.8280660.4358661.7652980.7622380.819232
min4.3000002.0000001.0000000.1000000.000000
25%5.1000002.8000001.6000000.3000000.000000
50%5.8000003.0000004.3500001.3000001.000000
75%6.4000003.3000005.1000001.8000002.000000
max7.9000004.4000006.9000002.5000002.000000
  • 由于它是一个预处理过的数据集,因此每个类别的样本数量均相等(均为150)。

3.可视化分析数据

  • 让我们看一下数据集的箱线图,它向我们展示了我们的数据如何在平面上分散的视觉表示。
    • 箱线图是基于百分比的图形,它将数据分为四个四分位数,每个四分位数的比例为25%。
    • 此方法用于统计分析以了解各种度量,例如均值、中位数和偏差。
# Seaborn是基于matplotlib的图形可视化python包。它提供了一种高度交互式界面,便于用户能够做出各种有吸引力的统计图表。
# https://www.jianshu.com/p/94931255aede
import seaborn as sns
sns.boxplot(data=iris_data, width=0.5, fliersize=5)
sns.set(rc={'figure.figsize':(2,5)})

在这里插入图片描述

  • 下面用matplotlib实现相同的功能对比
# 就写2个了,不方便
fig, axs = plt.subplots(nrows=1, figsize=(5,5))
plt.boxplot([iris_data['sepal width (cm)'],
             iris_data['sepal length (cm)']])
plt.show()

在这里插入图片描述

  • 为了了解每个要素如何解释数据分类,我们可以构建一个散点图,向我们显示与其他要素的相关性。这种方法仅有助于找出最能说明模型中分类的重要特征。
# 这分析没卵用
fig, axs = plt.subplots(nrows=1, figsize=(5,5),ncols=2)
sns.scatterplot(data=iris_data['sepal length (cm)'], ax=axs[0])
sns.scatterplot(data=iris_data['sepal width (cm)'], ax=axs[1])
<matplotlib.axes._subplots.AxesSubplot at 0x7fc233e51f50>

在这里插入图片描述

# 第3种绘图方法,pandas自带的;分析没卵用
iris_data.hist(figsize=(14,14), color='maroon', bins=20)
plt.show()

在这里插入图片描述

# 用panadas的绘图似乎更简单。。
iris_data.boxplot(figsize=(12,8))
plt.show()

在这里插入图片描述

# 皮尔逊相关性,sns就是花哨
fig, axs = plt.subplots(nrows=1, figsize=(13,13))
sns.heatmap(iris_data.corr(), annot=True, square=True, cmap='YlGnBu', linewidths=2, linecolor='black', annot_kws={'size':12})
<matplotlib.axes._subplots.AxesSubplot at 0x7fc23390f4d0>

在这里插入图片描述

  • 根据上图看出,class目标与花瓣长、宽和花萼长相似度都很高。。特别是花瓣宽度0.96,几乎现在就可以下结论。。下面来看一下花瓣宽度和calss的柱状图
fig, axs = plt.subplots(nrows=1, figsize=(13,13))
sns.barplot(x=iris_data['petal width (cm)'], y=iris_data['class'])
<matplotlib.axes._subplots.AxesSubplot at 0x7fc231838d50>

在这里插入图片描述

  • 果然。。。花瓣宽度和class相似度太高了。。花瓣宽度在1-1.3cm就是setosa。。
    • 之所以有一个特征与目标相似度如此之高的情况发生,离不开挖掘数据产链,可能这花瓣宽度特征是通过不断挖掘数据工程中’进化‘得来的。
    • 高价值的数据,在后面的算法中,注定。。。别说机器学习了,我人来学习也秒学会。。。
    • 数据质量决定挖掘的上限,而算法仅仅是逼近这个上限!!!
    • 重庆人得咽喉炎和痔疮的多-----重庆火锅,这就是好的数据质量

4.应用算法

1. 划分数据以进行培训和测试

  • 一旦了解了数据集的含义,就可以开始基于算法训练模型。在这里,我们将实现一些机器学习中常用的算法。让我们从使用一些样本训练模型开始。我们将使用一个名为“ train_test_split”的sklearn内置库,该库将我们的数据集分成70:30的比例。可以通过以下代码完成:
# train test Split
# model_selection模型选择
from sklearn.model_selection import train_test_split
X = iris_data.values[:,0:4]
y = iris_data.values[:,4]
X.shape
(150, 4)
y.shape
(150,)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)
[x.shape for x in [X_train, X_test, y_train, y_test] ]
[(105, 4), (45, 4), (105,), (45,)]

2.训练模型

  • 使用一些常用算法,我们将训练多个模型以检查每种算法的准确性。我们将实现这些算法以进行比较:

    1. K-Nearest Neighbored (KNN) K近邻
    2. Support Vector Machine (SVM) 支持向量机
    3. Randomforest 随机森林
    4. Logistic Regression 逻辑回归
  • 我们可以从第一个具有邻居数5的算法KNN开始:

# 建立模型
model = KNeighborsClassifier()
# 训练模型
model.fit(X_train,y_train)
# 预测模型
# predicitons预测: 它就是预测y_test
predicitons = model.predict(X_test)
# 评估
print(accuracy_score(y_test, predicitons))
1.0
# 评估结果为1,不可能;上交叉验证:
from sklearn.model_selection import cross_val_score
scores = cross_val_score(KNeighborsClassifier(), X_train, y_train, cv=5)
scores.mean()
0.9428571428571428
  • 接下来,支持向量机模型基于带有默认参数的径向基函数原理。我们将使用REF内核检查准确性。
# 建立模型
model = SVC()
# 训练模型
model.fit(X_train, y_train)
# 预测模型
pred = model.predict(X_test)
# 评估验证
print(accuracy_score(y_test, pred))
1.0
# 交叉验证
cross_val_score(SVC(), X_train, y_train, cv=5).mean()
0.9523809523809523
  • Randomforest是一种高精度的非线性算法,它基于决策树分类原理。让我们看看它有多精确:
# 建立模型
model = RandomForestClassifier(n_estimators=5)
# 训练模型
model.fit(X_train, y_train)
# 预测模型
pred = model.predict(X_test)
# 评估验证
print(accuracy_score(y_test, pred))
1.0
# ...
# 算法越高级,并不能说明越好,反而降低了;而且这里不适合RandomForest(个人猜的,好像错了。。)
cross_val_score(RandomForestClassifier(n_estimators=5), X_train, y_train, cv=5).mean()
0.9428571428571428
  • Logisitic回归适用于两种方案,首先,如果是二进制分类问题,则与其他方案一样步骤;如果是多类分类问题,则其与多个方案–对应。
model = LogisticRegression()
model.fit(X_train, y_train)
pred = model.predict(X_test)
print(accuracy_score(y_test, pred))
1.0
print(cross_val_score(LogisticRegression(), X_train, y_train, cv=5).mean())
0.9619047619047618


/Users/zhaowenchuan/anaconda3/lib/python3.7/site-packages/sklearn/linear_model/_logistic.py:940: ConvergenceWarning: lbfgs failed to converge (status=1):
STOP: TOTAL NO. of ITERATIONS REACHED LIMIT.

Increase the number of iterations (max_iter) or scale the data as shown in:
    https://scikit-learn.org/stable/modules/preprocessing.html
Please also refer to the documentation for alternative solver options:
    https://scikit-learn.org/stable/modules/linear_model.html#logistic-regression
  extra_warning_msg=_LOGISTIC_SOLVER_CONVERGENCE_MSG)
/Users/zhaowenchuan/anaconda3/lib/python3.7/site-packages/sklearn/linear_model/_logistic.py:940: ConvergenceWarning: lbfgs failed to converge (status=1):
STOP: TOTAL NO. of ITERATIONS REACHED LIMIT.

Increase the number of iterations (max_iter) or scale the data as shown in:
    https://scikit-learn.org/stable/modules/preprocessing.html
Please also refer to the documentation for alternative solver options:
    https://scikit-learn.org/stable/modules/linear_model.html#logistic-regression
  extra_warning_msg=_LOGISTIC_SOLVER_CONVERGENCE_MSG)

3.选择一个模型并调整参数

  • 低配。。将随机森林里的树改一下数量。。
# 建立模型
model = RandomForestClassifier(n_estimators=500)
# 训练模型
model.fit(X_train, y_train)
# 预测模型
pred = model.predict(X_test)
# 评估验证
print(accuracy_score(y_test, pred))
1.0
cross_val_score(RandomForestClassifier(n_estimators=50), X_train, y_train, cv=5).mean()
0.9428571428571428

结论

  • 选择SVC。。
  • 0
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值