机器学习之有监督学习实例_01 —— 鸢尾花数据集的分类

Iris 数据集简介 :

Iris Data Set(鸢尾属植物数据集)首次出现在著名的英国统计学家和生物学家Ronald Fisher 1936年的论文《The use of multiple measurements in taxonomic problems》中,被用来介绍线性判别式分析。该数据集种包括三类不同的鸢尾属植物:Iris Setosa,Iris Versicolour,Iris Virginica;且每类收集了50个样本,故这个数据集一共包含了150个样本

  • **特征:**该数据集种包括150个样本的4个特征(单位: c m cm cm) : s p e a l speal speal l e n t h ( 花 萼 长 度 ) lenth (花萼长度) lenth() s e p a l sepal sepal w i d t h ( 花 萼 宽 度 ) width(花萼宽度) width() p e t a l petal petal l e n t h ( 花 瓣 长 度 ) lenth(花瓣长度) lenth() p e t a l petal petal w i d t h ( 花 瓣 宽 度 ) width(花瓣宽度) width(),通常用 m m m 来表示样本量的大小, n n n 表示每个样本所具有的特征数,即 m = 150 、 n = 4 m=150、n=4 m=150n=4;
1. 从 s k l e a r n sklearn sklearn 中导入数据集
from sklearn import datasets
iris = datasets.load_iris() 

将鸢尾花卉数据集中所有的数据和元数据都加载到 i r i s iris iris 变量中,使用 i r i s iris iris 变量的 d a t a data data t a r g e t target target属性

iris.data #查看其包含的数据

输出结果为包含 150 150 150 个元素的数组,每个元素包含四个数值 :分别为萼片和花瓣的数据

array([[5.1, 3.5, 1.4, 0.2],
       [4.9, 3. , 1.4, 0.2],
       [4.7, 3.2, 1.3, 0.2],
       [4.6, 3.1, 1.5, 0.2],
       [5. , 3.6, 1.4, 0.2],
       [5.4, 3.9, 1.7, 0.4],
       ···

查看 150 150 150 个数据集的种类,包含三种:山鸢尾、变色鸢尾和维吉尼亚鸢尾

iris.target

输出结果包含 150 个数值,其中取值为:0、1 和 2分别代表山鸢尾、变色鸢尾和维吉尼亚鸢尾。

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])

三种不同的鸢尾花卉的类别为

iris.target_names #访问iris的target_names属性

输出结果为鸢尾花的三个类别:

array(['setosa', 'versicolor', 'virginica'], dtype='<U10')
2. 可视化鸢尾花数据集

使用 m a t p l o t l i b 库 matplotlib库 matplotlib ,用三种颜色来表示三种花卉的种类,绘制一幅散点图;其中蓝、绿和红分别代表山鸢尾、变色鸢尾和维吉尼亚鸢尾, x x x 轴表示萼片的长度, y y y 轴表示萼片的宽度 ,。

import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
from sklearn import datasets
iris = datasets.load_iris()
x = iris.data[:,0] #x_Axis sepal length
y = iris.data[:,1] #y_Axis sepal length
species = iris.target
x_min,x_max = x.min() - 0.5,x.max() + 0.5
y_min,y_max = y.min() - 0.5,y.max() + 0.5

plt.figure()
plt.title('Iris Dataset - Classification By Spepal Sizes ')
plt.scatter(x,y,c=species)
plt.xlabel('Sepal length')
plt.ylabel('Sepal width')
plt.xlim(x_min,x_max)
plt.ylim(y_min,x_max)
plt.xticks(())
plt.yticks(())

用不同颜色表示不同鸢尾花卉种类
对代码进行修改,用花瓣的长和宽两个变量来绘制图表:

import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
from sklearn import datasets
iris = datasets.load_iris()
x = iris.data[:,2] #x_label
y = iris.data[:,3] #y_label
species = iris.target
x_min,x_max = x.min() - .5,x.max() + .5
y_min,y_max = y.min() - .5,y.max() + .5

plt.figure()
plt.title('Iris Dataset - Classification By Petal Sizes ',size=14)
plt.scatter(x,y,c=species)
plt.xlabel('Petal length')
plt.ylabel('Petal width')
plt.xlim(x_min,x_max)
plt.ylim(y_min,x_max)
plt.xticks(())
plt.yticks(())

3. 主成分分析法 P C A PCA PCA

主成分分析法: P r i n c i p a l Principal Principal C o m p o n e n t Component Component A n a l i s i s Analisis Analisis ,特点:该方法可以减少系统的维数,保留足以描述各数据点特征的信息,其中新生成的各维称作主成分。此处的应用是将花瓣、萼片的四个测量数据来描述三种花卉的特点,把四个测量数据整合到一起 —— 3D散点图。

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

iris = datasets.load_iris()
x = iris.data[:,1] #X_Axis-petal length
y = iris.data[:,2] #Y_Axis_petal length
species = iris.target
x_reduced = PCA(n_components=3).fit_transform(iris.data)
# SCATTERPLOT 3D
fig = plt.figure()
ax = Axes3D(fig)
ax.set_title('Iris Dataset by PCA',size =14)
ax.scatter(x_reduced[:,0],x_reduced[:,1],x_reduced[:,2],c=species)

ax.set_xlabel('First eigenvector')
ax.set_ylabel('Second eigenvetor')
ax.set_zlabel('Third eigenvector')
ax.w_xaxis.set_ticklabels(())
ax.w_yaxis.set_ticklabels(())
ax.w_zaxis.set_ticklabels(())

如下图,三种鸢尾花卉被 3 D 3D 3D 散点图表示出来,各自形成一簇。
在这里插入图片描述

鸢尾花数据集分类

在模型测试过程这一阶段,我们会验证用先前采集的数据创建的模型是否有效。初始采集的数据会被分为训练集和检验集用于建模的数据称为训练集,用来验证模型的数据称为验证集。其中最著名的是交叉检验,基础操作是把训练集分为不同的部分,每一部分轮流作为验证集,同时其余部分用作训练集,通过这种迭代的方式,进而得到最佳模型

K - 近邻分类器

1. 将数据分为训练集、验证集,其中 140 个数据用于模型的训练,10 个数据作为验证集。

# K-近邻分类器
import numpy as np
from sklearn import datasets
np.random.seed(0)
iris = datasets.load_iris()
x = iris.data
y = iris.target
i = np.random.permutation(len(iris.data)) #先打乱数组各元素的顺序,再进行切分
#训练数据集
x_train = x[i[:-10]]
y_train = y[i[:-10]]
#验证数据集
x_test = x[i[-10:]]
y_test = y[i[-10:]]

2. 调用 K N N KNN KNN 分类器的构造函数,然后用 f i t ( ) fit() fit() 函数对其进行训练,用140条观测数据训练 k n n knn knn分类器,得到预测模型。

In[ ]:	from sklearn.neighbors import KNeighborsClassifier
  		knn = KNeighborsClassifier()
		knn.fit(x_train,y_train) 
		#调用用分类器的构造函数,用fit()函数对其进行训练
Out[ ]: KNeighborsClassifier(algorithm='auto', leaf_size=30, metric='minkowski',
                     metric_params=None, n_jobs=None, n_neighbors=5, p=2,
                     weights='uniform')

3. 用验证集验证模型的效果,要获取预测结果,直接在预测模型 k n n knn knn 上调用 p r e d i c t ( ) predict( ) predict() 函数。

In[1]:  knn.predict(x_test)
Out[1]: array([1, 2, 1, 0, 0, 0, 2, 1, 2, 0])
 #将预测结果与y_test 中的实际值进行比较
In[2]:y_test 
Out[2]: array([1, 1, 1, 0, 0, 0, 2, 1, 2, 0])

由上面可知,错误率为 10 10 10 %,为了更加直观看懂决策结果,我们分别画出萼片测量数据、花瓣测量数据的决策边界。

  • 萼片测量数据决策边界
#画出决策边界
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.colors import ListedColormap
from sklearn import datasets
from sklearn.neighbors import KNeighborsClassifier
iris = datasets.load_iris()
x = iris.data[:,:2]
y = iris.target
x_min,x_max = x[:,0].min()- .5,x[:,0].max() + .5
y_min,y_max = x[:,1].min() - .5,x[:,1].max() + .5

#MESH
#用三种不同颜色表示的三个决策边界
cmap_light = ListedColormap(['#AAAAFF','#AAFFAA','#FFAAAA'])
h = 0.02 
xx,yy = np.meshgrid(np.arange(x_min,x_max,h),np.arange(y_min,y_max,h))
knn = KNeighborsClassifier()
knn.fit(x,y)
Z = knn.predict(np.c_[xx.ravel(),yy.ravel()])
Z = Z.reshape(xx.shape)
plt.figure()
plt.pcolormesh(xx,yy,Z,cmap=cmap_light)
# plot the training data
plt.scatter(x[:,0],x[:,1],c=y)
plt.title('Sepal Length Decision Boundary ',size=14)
plt.xlim(xx.min(),xx.max())
plt.ylim(yy.min(),yy.max())

在这里插入图片描述
我们可以清晰的从散点图中看出,红色部分有一小块区域伸入到其他决策边界之中,即编号为1、2的变色鸢尾和维吉尼亚鸢尾存在交集,导致训练后得到模型在预测中存在偏差,也就是我们在预测 x x x t e s t test test 得到的预测结果与验证集中 y y y t e s t test test存在的 10 10 10% 错误 。

  • 花瓣测量数据决策边界
#画出决策边界
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.colors import ListedColormap
from sklearn import datasets
from sklearn.neighbors import KNeighborsClassifier
iris = datasets.load_iris()
x = iris.data[:,2:4]
y = iris.target

x_min,x_max = x[:,0].min()- .5,x[:,0].max() + .5
y_min,y_max = x[:,1].min() - .5,x[:,1].max() + .5
#MESH
#用三种不同颜色表示的三个决策边界
cmap_light = ListedColormap(['#AAAAFF','#AAFFAA','#FFAAAA'])
h = 0.02 
xx,yy = np.meshgrid(np.arange(x_min,x_max,h),np.arange(y_min,y_max,h))
knn = KNeighborsClassifier()
knn.fit(x,y)
Z = knn.predict(np.c_[xx.ravel(),yy.ravel()])
Z = Z.reshape(xx.shape)
plt.figure()
plt.pcolormesh(xx,yy,Z,cmap=cmap_light)

# plot the training data
plt.scatter(x[:,0],x[:,1],c=y)
plt.title('Petal Length Decision Boundary ',size=14)
plt.xlim(xx.min(),xx.max())
plt.ylim(yy.min(),yy.max())

在这里插入图片描述
同样,我们可以从散点图中看出,红色部分与绿色部分存在交叉部分,即编号为1、2的变色鸢尾 ( G r e e n ) (Green) (Green)和维吉尼亚鸢尾 ( R e d ) (Red) (Red)存在交叉部分,导致训练得到的模型在预测中存在偏差,也就解释了我们在对比 x x x t e s t test test 得到的预测结果与验证集中 y y y t e s t test test存在的预测错误 。

鸢尾花数据集作为机器学习中最为常见的数据集,在学习导入数据集、访问属性、用 m a t p l o t l i b matplotlib matplotlib直观的转化为 2 D 2D 2D 3 D 3D 3D图形对理解模型更加透彻,但仍需要对该数据集进行更广泛的数据分析,才能掌握数据分析的内容。

### 使用KNN算法处理鸢尾花数据集进行机器学习分类 #### 导入必要的库 为了使用KNN算法对鸢尾花数据集进行分类,首先需要导入一些常用的Python库。这些库包括用于数据分析的`pandas`和`numpy`,以及用于机器学习的`scikit-learn`。 ```python import numpy as np import pandas as pd from sklearn import datasets from sklearn.model_selection import train_test_split from sklearn.preprocessing import StandardScaler from sklearn.neighbors import KNeighborsClassifier from sklearn.metrics import accuracy_score, classification_report, confusion_matrix import matplotlib.pyplot as plt import seaborn as sns ``` #### 加载并预处理数据 接下来,加载鸢尾花数据集,并对其进行初步探索和预处理。这一步骤对于确保数据适合于建模至关重要。 ```python # 加载鸢尾花数据集 iris = datasets.load_iris() X = iris.data # 特征变量 y = iris.target # 目标变量 # 将数据分为训练集和测试集 X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42) # 数据标准化 scaler = StandardScaler().fit(X_train) X_train_scaled = scaler.transform(X_train) X_test_scaled = scaler.transform(X_test) ``` #### 训练KNN模型 一旦完成了数据准备阶段的工作,就可以创建一个KNN分类实例,并利用训练好的模型来进行预测。这里选择了K值为5作为例子[^1]。 ```python knn = KNeighborsClassifier(n_neighbors=5) knn.fit(X_train_scaled, y_train) # 预测 predictions = knn.predict(X_test_scaled) print(f'Accuracy: {accuracy_score(y_test, predictions)*100:.2f}%') ``` #### 可视化结果 最后,可以通过绘制混淆矩阵等方式来评估模型的表现情况。这样不仅有助于了解模型的整体准确性,还能发现哪些类别的误判较多。 ```python conf_mat = confusion_matrix(y_test, predictions) plt.figure(figsize=(8,6)) sns.heatmap(conf_mat, annot=True, fmt='d', cmap="YlGnBu", xticklabels=iris.target_names, yticklabels=iris.target_names) plt.ylabel('Actual Label') plt.xlabel('Predicted Label') plt.title('Confusion Matrix Heatmap') plt.show() print(classification_report(y_test, predictions, target_names=iris.target_names)) ``` 上述过程展示了如何运用KNN算法针对鸢尾花数据集执行基本的监督式学习任务——即分类问题。值得注意的是,在实际操作过程中可能还需要进一步优化超参数(比如尝试不同的K值),并对特征工程给予更多关注以提升最终的效果[^3]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值