sklearn 机器学习实战入门之—iris 数据集分析与可视化
导读:Scikit-learn是一个Python第三方提供的非常强大的机器学习库,广泛用于统计分析和机器学习建模等领域,官方文档(http://scikit-learn.org/stable/)。 本文使用一个非常经典的数据集——iris数据集来简单介绍使用sklearn训练机器学习模型的基本方法、一些参数的含义、以及试图使用seaborn进行简单的可视化,供大家交流学习,笔者也是刚刚入门,如有谬误,欢迎讨论。
使用环境为PyCharm,为方便看到结果直接在console模式中来写代码
一、介绍
引入:鸢尾花是单子叶植物纲,鸢尾科多年生草本植物。鸢尾花大而美丽,叶片青翠碧绿,观赏价值很高。很多种类供庭园观赏用,在园林中可用作布置花坛,栽植于水湿畦地、池边湖畔,或布置成鸢尾专类花园,亦可作切花及地被植物,是一种重要的庭园植物。鸢尾花有诸多品种,不同品种的花有其各自的特征,可以简要的选取以下四个方面来观察:花萼长度sepal length , 花萼宽度sepal width, 花瓣长度petal length , 花瓣宽度petal width,我们希望计算机可以通过一些已知的样本数据,找到其中的规律,从而通过这几项特征来辨识花的品种。
首先我们导入iris数据,看看这个数据到底是什么样的
In[2]:from sklearn.datasets import load_iris # 导入sklearn中自带的iris数据集
... :iris = load_iris()
In[3]:iris # 展示数据内容
#输出结果
Out[3]:
{'data': 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],
.
.
. (共150行)
.
.
.
[6.3, 2.5, 5. , 1.9],
[6.5, 3. , 5.2, 2. ],
[6.2, 3.4, 5.4, 2.3],
[5.9, 3. , 5.1, 1.8]]),
'target': 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]),
'frame': None,
'target_names': array(['setosa', 'versicolor', 'virginica'], dtype='<U10'),
'DESCR': '.. _iris_dataset:\n\nIris plants dataset\n--------------------\n\n**Data Set Characteristics:**\n\n :Number of Instances: 150 (50 in each of three classes)\n :Number of Attributes: 4 numeric, predictive attributes and the class\n :Attribute Information:\n - sepal length in cm\n - sepal width in cm\n - petal length in cm\n - petal width in cm\n - class:\n - Iris-Setosa\n - Iris-Versicolour\n - Iris-Virginica\n \n :Summary Statistics:\n\n ============== ==== ==== ======= ===== ====================\n Min Max Mean SD Class Correlation\n ============== ==== ==== ======= ===== ====================\n sepal length: 4.3 7.9 5.84 0.83 0.7826\n sepal width: 2.0 4.4 3.05 0.43 -0.4194\n petal length: 1.0 6.9 3.76 1.76 0.9490 (high!)\n petal width: 0.1 2.5 1.20 0.76 0.9565 (high!)\n ============== ==== ==== ======= ===== ====================\n\n :Missing Attribute Values: None\n :Class Distribution: 33.3% for each of 3 classes.\n :Creator: R.A. Fisher\n :Donor: Michael Marshall (MARSHALL%PLU@io.arc.nasa.gov)\n :Date: July, 1988\n\nThe famous Iris database, first used by Sir R.A. Fisher. The dataset is taken\nfrom Fisher\'s paper. Note that it\'s the same as in R, but not as in the UCI\nMachine Learning Repository, which has two wrong data points.\n\nThis is perhaps the best known database to be found in the\npattern recognition literature. Fisher\'s paper is a classic in the field and\nis referenced frequently to this day. (See Duda & Hart, for example.) The\ndata set contains 3 classes of 50 instances each, where each class refers to a\ntype of iris plant. One class is linearly separable from the other 2; the\nlatter are NOT linearly separable from each other.\n\n.. topic:: References\n\n - Fisher, R.A. "The use of multiple measurements in taxonomic problems"\n Annual Eugenics, 7, Part II, 179-188 (1936); also in "Contributions to\n Mathematical Statistics" (John Wiley, NY, 1950).\n - Duda, R.O., & Hart, P.E. (1973) Pattern Classification and Scene Analysis.\n (Q327.D83) John Wiley & Sons. ISBN 0-471-22361-1. See page 218.\n - Dasarathy, B.V. (1980) "Nosing Around the Neighborhood: A New System\n Structure and Classification Rule for Recognition in Partially Exposed\n Environments". IEEE Transactions on Pattern Analysis and Machine\n Intelligence, Vol. PAMI-2, No. 1, 67-71.\n - Gates, G.W. (1972) "The Reduced Nearest Neighbor Rule". IEEE Transactions\n on Information Theory, May 1972, 431-433.\n - See also: 1988 MLC Proceedings, 54-64. Cheeseman et al"s AUTOCLASS II\n conceptual clustering system finds 3 classes in the data.\n - Many, many more ...',
'feature_names': ['sepal length (cm)',
'sepal width (cm)',
'petal length (cm)',
'petal width (cm)'],
'filename': 'C:\\Program Files (x86)\\Microsoft Visual Studio\\Shared\\Python37_64\\lib\\site-packages\\sklearn\\datasets\\data\\iris.csv'}
可以看到,其中主要有'data'、'target'、'targetname'、'feature_names'这几项,以及一些描述性的信息。
data是一个150行*4列的二维数组,每一行代表一个数据样本,一共150个样本,四列则对应feature_names中的四个特征名,即'sepal length (cm)', 'sepal width (cm)', 'petal length (cm)', 'petal width (cm)'。
target是一个含150个元素的一维数组,与data中的150个样本依次对应,0、1、2所代表的是target_names中的三类品种:山鸢尾(setosa)、变色鸢尾(versicolor)和维吉尼亚鸢尾(virginica)
下面我们开始拟合机器学习模型
sklearn中提供了很多分类和回归模型供大家使用,这里所使用的模型为梯度提升决策树(GBDT)
from sklearn.ensemble import GradientBoostingClassifier
X = iris.data #特征
Y = iris.target #类别
from sklearn.model_selection import train_test_split #用来划分测试集与训练集
X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size=0.2, random_state=66) # 数据划分
clas = GradientBoostingClassifier(random_state=58)#使用默认参数,如果数据比较复杂的话需要调参
clas.fit(X_train,Y_train)#训练模型
Y_pre1=clas.predict(X_train)#预测训练集
Y_pre2=clas.predict(X_test)#预测测试集
在数据划分时,test_size表示测试集所占比例,可以为浮点或整数,为浮点时,表示测试集占总样本的百分比;为整数时,表示测试集所含样本个数;不设置的话默认为0.25
random_state参数代表一个随机状态,可以给予任意int型值,模型的构建、数据集的生成、数据集的拆分等都是一个随机的过程,如果你希望换一台电脑仍然可以重现你的结果的话,只要random_state保持固定即可。
print("训练集准确率:%s"%clas.score(X_train,Y_train)) #输出测试集准确度
print("测试集准确率:%s"%clas.score(X_test,Y_test)) #输出测试集准确度
from sklearn.metrics import classification_report
print("report is:",classification_report(Y_test,Y_pre2))#查看模型报告
输出结果如下
训练集准确率:1.0
测试集准确率:0.9666666666666667
report is: precision recall f1-score support
setosa 1.00 1.00 1.00 9
versicolor 0.91 1.00 0.95 10
virginica 1.00 0.91 0.95 11
accuracy 0.97 30
macro avg 0.97 0.97 0.97 30
weighted avg 0.97 0.97 0.97 30
-
precision(精确度):预测值为该类的样本中有多少正确的,例:预测结果中有11个变色鸢尾(versicolor),其中有10个正确,1个错误,则变色鸢尾的precision=10/11=0.91
-
recall (召回率):真实值为该类的样本 有多少被成功预测,例:真实值中有10个变色鸢尾(versicolor),这10个全被正确预测,则变色鸢尾的recall=1
-
f1-score(f1得分):精确度和召回率的调和平均数
-
support:该类的数量(以真实值计算)
-
accuracy(准确率):正确预测的样本数比上总样本数, 例:测试集一共30个样本,其中29个预测正确,则accuracy=29/30=0.97
-
macro avg(宏平均值):即直接求均值,例:precision的宏平均值=(1.0+0.91+1.0)/3=0.97
-
weighted avg(加权平均值):以support为权重进行加权平均
二、可视化
下面进行可视化
先使用pandas库将数据制作成dataframe格式
import pandas as pd
df_iris=pd.DataFrame(iris.data, columns=iris.feature_names)#将data加入到数据框中
df_iris['target']=iris.target#将target加入到数据框中
df_iris.head()#展示数据框前五行
#输出结果
Out[10]:
sepal length (cm) sepal width (cm) ... petal width (cm) target
0 5.1 3.5 ... 0.2 0
1 4.9 3.0 ... 0.2 0
2 4.7 3.2 ... 0.2 0
3 4.6 3.1 ... 0.2 0
4 5.0 3.6 ... 0.2 0
可以将target中的数字换为名称,0代表setosa,1代表versicolor,2代表virginica
class_mapping = {0:'setosa',1:'versicolor',2:'virginica'}
df_iris['target'] = df_iris['target'].map(class_mapping)
df_iris
#输出结果
Out[20]:
sepal length (cm) sepal width (cm) ... petal width (cm) target
0 5.1 3.5 ... 0.2 setosa
1 4.9 3.0 ... 0.2 setosa
2 4.7 3.2 ... 0.2 setosa
3 4.6 3.1 ... 0.2 setosa
4 5.0 3.6 ... 0.2 setosa
.. ... ... ... ... ...
145 6.7 3.0 ... 2.3 virginica
146 6.3 2.5 ... 1.9 virginica
147 6.5 3.0 ... 2.0 virginica
148 6.2 3.4 ... 2.3 virginica
149 5.9 3.0 ... 1.8 virginica
然后使用seaborn库进行可视化
import seaborn as sns
#x轴设置为花萼长度,y轴设置为花瓣长度,按照不同的target赋予不同的点型和颜色
sns.scatterplot(x='sepal length (cm)', y='petal length (cm)', hue='target', style='target', data=df_iris)
结果如图所示。
相关文章:
sklearn机器学习实战入门之—iris数据集分析与可视化
为者常成,行者常至
自由转载-非商用-非衍生-保持署名(创意共享3.0许可证)