赞
踩
在python的sklearn库中,有一些小型数据集,我们可以直接拿来进行模型训练学习。
Iris(鸢尾花)数据集是常用的分类实验数据集,由Fisher, 1936收集整理。Iris也称鸢尾花卉数据集,是一类多重变量分析的数据集。关于数据集共有150个样本,4个特征,3个目标值,我们可以这样引用:
from sklearn.datasets import load_iris
# 1.获取鸢尾花数据集
iris = load_iris()
print("鸢尾花数据集的返回值:\n", iris)
# 返回值是一个继承自字典的Bench
print("鸢尾花的特征值:\n", iris["data"])
print("鸢尾花的目标值:\n", iris.target)
print("鸢尾花特征的名字:\n", iris.feature_names)
print("鸢尾花目标值的名字:\n", iris.target_names)
print("鸢尾花的描述:\n", iris.DESCR)
部分结果:
鸢尾花的特征值:
[[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]
[4.6 3.4 1.4 0.3]
[5. 3.4 1.5 0.2]
[4.4 2.9 1.4 0.2]
[4.9 3.1 1.5 0.1]
[5.4 3.7 1.5 0.2]
[4.8 3.4 1.6 0.2]
[4.8 3. 1.4 0.1]
[4.3 3. 1.1 0.1]
[5.8 4. 1.2 0.2]
[5.7 4.4 1.5 0.4]
[5.4 3.9 1.3 0.4]
[5.1 3.5 1.4 0.3]
[5.7 3.8 1.7 0.3]
[5.1 3.8 1.5 0.3]
[5.4 3.4 1.7 0.2]
[5.1 3.7 1.5 0.4]
[4.6 3.6 1. 0.2]
[5.1 3.3 1.7 0.5]
[4.8 3.4 1.9 0.2]
[5. 3. 1.6 0.2]
[5. 3.4 1.6 0.4]
[5.2 3.5 1.5 0.2]
[5.2 3.4 1.4 0.2]
[4.7 3.2 1.6 0.2]
[4.8 3.1 1.6 0.2]
[5.4 3.4 1.5 0.4]
[5.2 4.1 1.5 0.1]
[5.5 4.2 1.4 0.2]
[4.9 3.1 1.5 0.2]
[5. 3.2 1.2 0.2]
[5.5 3.5 1.3 0.2]
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 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]
鸢尾花特征的名字:
[‘sepal length (cm)’, ‘sepal width (cm)’, ‘petal length (cm)’, ‘petal width (cm)’]
鸢尾花目标值的名字:
[‘setosa’ ‘versicolor’ ‘virginica’]
在载入了iris数据后,使用KNN算法(k-近邻算法)进行分类训练。如果一个样本在特征空间中的k个最相似(即特征空间中最邻近)的样本中的大多数属于某一个类别,则该样本也属于这个类别。
这里训练集和测试集比例为8:2。
在进行训练前,需要对数据进行预处理,这里使用的是标准化。
# 2.数据基本处理
# x_train,x_test,y_train,y_test为训练集特征值、测试集特征值、训练集目标值、测试集目标值的类别
x_train, x_test, y_train, y_test = train_test_split(iris.data, iris.target, test_size=0.2, )#x为特征值,y为目标值
# 3、特征工程:标准化
transfer = StandardScaler() #标准化API用transfer承接
x_train = transfer.fit_transform(x_train) #训练值类别标准化
x_test = transfer.transform(x_test) #测试值类别标准化
在进行数据训练使用API: KNeighborsClassifier的fit()方法
# 4、机器学习(模型训练)
estimator = KNeighborsClassifier(n_neighbors=9) #将API用estimator变量承接
estimator.fit(x_train, y_train) #使用fit方法进行模型训练
最后进行模型评估,通过对比真实值和预测值以及准确率进行评估:
# 5、模型评估
# 方法1:比对真实值和预测值
y_predict = estimator.predict(x_test) #输入预测值进行预测
print("预测结果为:\n", y_predict)
print("比对真实值和预测值:\n", y_predict == y_test) #相同输出True
# 方法2:直接计算准确率
score = estimator.score(x_test, y_test)
print("准确率为:\n", score)
预测结果:
如果想绘制出鸢尾花的分类图,可以使用seaborn:
Seaborn 是基于 Matplotlib 核心库进行了更高级的 API 封装,可以让你轻松地画出更漂亮的图形。而 Seaborn 的漂亮主要体现在配色更加舒服、以及图形元素的样式更加细腻。
安装: pip3 install seaborn
seaborn.lmplot() 是一个非常有用的方法,它会在绘制二维散点图时,自动完成回归拟合
sns.lmplot() 里的 x, y 分别代表横纵坐标的列名,
data= 是关联到数据集,
hue=*代表按照 species即花的类别分类显示,
fit_reg=是否进行线性拟合。
from sklearn.datasets import load_iris import seaborn as sns import matplotlib.pyplot as plt import pandas as pd from pylab import mpl #设置字体 mpl.rcParams["font.sans-serif"] = ["SimHei"] mpl.rcParams["axes.unicode_minus"]=False iris = load_iris() # 把数据转换成dataframe的格式 iris_d = pd.DataFrame(iris['data'], columns = ['Sepal_Length', 'Sepal_Width', 'Petal_Length', 'Petal_Width']) iris_d['Species'] = iris.target #加1列类别 #绘制分类图像,形参有iris矩阵,两个坐标轴分别为任意两个特征 def plot_iris(iris, col1, col2): sns.lmplot(x = col1, y = col2, data = iris, hue = "Species", fit_reg = False) plt.xlabel(col1) plt.ylabel(col2) plt.title('鸢尾花种类分布图') plt.show() plot_iris(iris_d, 'Petal_Width', 'Sepal_Length')
结果:
k近邻算法总结
优点:
简单有效
重新训练的代价低
适合类域交叉样本
KNN方法主要靠周围有限的邻近的样本,而不是靠判别类域的方法来确定所属类别的,因此对于类域的交叉或重叠较多的待分样本集来说,KNN方法较其他方法更为适合。
适合大样本自动分类
该算法比较适用于样本容量比较大的类域的自动分类,而那些样本容量较小的类域采用这种算法比较容易产生误分。
缺点:
惰性学习
KNN算法是懒散学习方法(lazy learning,基本上不学习),一些积极学习的算法要快很多
类别评分不是规格化
输出可解释性不强
计算量较大
附男生受欢迎程度
三个特征值(每月飞行公里数,吃甜点量,打游戏时间),三个目标值(1:差,2:中3:优)
import sklearn from sklearn.model_selection import train_test_split from sklearn.preprocessing import StandardScaler from sklearn.neighbors import KNeighborsClassifier import pandas as pd import numpy as np from pylab import mpl #设置字体 man = pd.read_csv("E:\\dating.txt") #导入txt文本数据 man_1=man[['milage','Liters','Consumtime']] man_2=man['target'] man.data=np.array(man_1) man.target=np.array(man_2) x_train, x_test, y_train, y_test = train_test_split(man.data, man.target, test_size=0.2, ) # 3、特征工程:标准化 transfer = StandardScaler() x_train = transfer.fit_transform(x_train) x_test = transfer.transform(x_test) # 4、机器学习(模型训练) estimator = KNeighborsClassifier(n_neighbors=9) estimator.fit(x_train, y_train) # 5、模型评估 # 方法1:比对真实值和预测值 y_predict = estimator.predict(x_test) print("预测结果为:\n", y_predict) print("比对真实值和预测值:\n", y_predict == y_test) # 方法2:直接计算准确率 score = estimator.score(x_test, y_test) print("准确率为:\n", score) y_test
结果:
可以看出训练的成果还是比较好的的
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。