使用 Scikit-learn 进行鸢尾花分类

Machine LearningMachine LearningBeginner
立即练习

This tutorial is from open-source community. Access the source code

💡 本教程由 AI 辅助翻译自英文原版。如需查看原文,您可以 切换至英文原版

简介

这是一个循序渐进的实验,用于演示Python中流行的机器学习库Scikit-learn的用法。我们将使用鸢尾花数据集(Iris Dataset),其中包含不同类型鸢尾花的物理属性信息。本实验的目的是展示如何使用Scikit-learn执行基本的机器学习任务,如数据加载、数据预处理、特征选择和可视化。

虚拟机使用提示

虚拟机启动完成后,点击左上角切换到“笔记本”标签页,以访问Jupyter Notebook进行练习。

有时,你可能需要等待几秒钟让Jupyter Notebook完成加载。由于Jupyter Notebook的限制,操作验证无法自动化。

如果你在学习过程中遇到问题,随时向Labby提问。课程结束后提供反馈,我们会及时为你解决问题。


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL ml(("Machine Learning")) -.-> ml/FrameworkandSoftwareGroup(["Framework and Software"]) sklearn(("Sklearn")) -.-> sklearn/AdvancedDataAnalysisandDimensionalityReductionGroup(["Advanced Data Analysis and Dimensionality Reduction"]) sklearn/AdvancedDataAnalysisandDimensionalityReductionGroup -.-> sklearn/decomposition("Matrix Decomposition") ml/FrameworkandSoftwareGroup -.-> ml/sklearn("scikit-learn") subgraph Lab Skills sklearn/decomposition -.-> lab-49166{{"使用 Scikit-learn 进行鸢尾花分类"}} ml/sklearn -.-> lab-49166{{"使用 Scikit-learn 进行鸢尾花分类"}} end

导入库

我们将首先导入必要的库。在本实验中,我们将使用Scikit-learn、NumPy和Matplotlib。

import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from sklearn import datasets
from sklearn.decomposition import PCA

加载鸢尾花数据集

我们将使用Scikit-learn内置的load_iris函数来加载鸢尾花数据集。

iris = datasets.load_iris()
X = iris.data[:, :2]  ## 我们只取前两个特征。
y = iris.target

可视化数据

我们将使用散点图来可视化鸢尾花数据集。我们将绘制萼片长度与萼片宽度的关系,并根据点所属的类别为其着色。

x_min, x_max = X[:, 0].min() - 0.5, X[:, 0].max() + 0.5
y_min, y_max = X[:, 1].min() - 0.5, X[:, 1].max() + 0.5

plt.figure(2, figsize=(8, 6))
plt.clf()

## 绘制训练点
plt.scatter(X[:, 0], X[:, 1], c=y, cmap=plt.cm.Set1, edgecolor="k")
plt.xlabel("萼片长度")
plt.ylabel("萼片宽度")

plt.xlim(x_min, x_max)
plt.ylim(y_min, y_max)
plt.xticks(())
plt.yticks(())

执行主成分分析(PCA)

我们将执行主成分分析(PCA)以降低数据集的维度。我们会将数据投影到前三个主成分上,并以三维形式绘制结果。

fig = plt.figure(1, figsize=(8, 6))
ax = fig.add_subplot(111, projection="3d", elev=-150, azim=110)

X_reduced = PCA(n_components=3).fit_transform(iris.data)
ax.scatter(
    X_reduced[:, 0],
    X_reduced[:, 1],
    X_reduced[:, 2],
    c=y,
    cmap=plt.cm.Set1,
    edgecolor="k",
    s=40,
)

ax.set_title("First three PCA directions")
ax.set_xlabel("1st eigenvector")
ax.xaxis.set_ticklabels([])
ax.set_ylabel("2nd eigenvector")
ax.yaxis.set_ticklabels([])
ax.set_zlabel("3rd eigenvector")
ax.zaxis.set_ticklabels([])

总结

在本实验中,我们学习了如何使用Scikit-learn加载鸢尾花数据集,如何使用Matplotlib可视化数据,以及如何使用Scikit-learn执行主成分分析(PCA)。我们还学习了如何将数据投影到前三个主成分上,并以三维形式可视化结果。