KNN实战之酒的分类
使用scikit-learn中内置的酒数据集来进行实验,划分训练集和测试集,对KNN模型进行评分。
from sklearn.datasets import load_wine
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsClassifier
import numpy as np
#导入数据集
wine_dataset = load_wine()
#keys:data,target(目标分类),target_names,DESCR(数据描述),feature_names
#三类:class_0:59,class_1:71,class_2:48
X_train,X_test,y_train,y_test = train_test_split(
wine_dataset['data'],wine_dataset['target'],random_state=0)
#训练模型
knn = KNeighborsClassifier(n_neighbors = 1)
knn.fit(X_train,y_train)
#测试得分
print("测试数据集得分:{:.2f}".format(knn.score(X_test,y_test)))
测试结果如下:
可以看到这个模型在预测测试数据集的样本分类上得分并不好,仅有0.76的准确率。
下面进行新酒数据的测试,加入这瓶酒的数据为Alcohol:13.2,Malic acid:2.77,Ash:2.51,
Alcalinity of ash:18.5,Magnesium:96.6,Total phenols:1.04,Flavanoids:2.55,Nonflavanoid phenols:0.57,Proanthocyanins:1.57,Color intensity:6.2,Hue:1.05,OD280:3.33,Proline:829:
from sklearn.datasets import load_wine
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsClassifier
import numpy as np
#导入数据集
wine_dataset = load_wine()
#keys:data,target(目标分类),target_names,DESCR(数据描述),feature_names
#三类:class_0:59,class_1:71,class_2:48
X_train,X_test,y_train,y_test = train_test_split(
wine_dataset['data'],wine_dataset['target'],random_state=0)
#训练模型
knn = KNeighborsClassifier(n_neighbors = 1)
knn.fit(X_train,y_train)
X_new = np.array([[13.2,2.77,2.51,18.5,96.6,1.04,2.55,0.57,1.47,6.2,1.05,3.33,820]])
predicition = knn.predict(X_new)
print("预测新红酒的分类为:{}".format(wine_dataset["target_names"][predicition]))
执行结果为:
模型把新酒的分类预测为class_2,正确率还是很不错的。
总结:KNN算法是一个比较经典并且原理容易理解的一个算法,但是它需要对数据集进行预处理、对于规模较大的数据集拟合时间长、表现不佳。