代码如下:
# -*- coding: utf-8 -*-
"""
Created on Fri May 11 10:26:58 2018
@author: eagle
"""
# =============================================================================
# 用K近邻预测Iris(鸢尾)数据集
# =============================================================================
from sklearn.datasets import load_iris
from sklearn.cross_validation import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.neighbors import KNeighborsClassifier
from sklearn.metrics import classification_report
#导入数据集
iris = load_iris()
#print(iris.data.shape) #(150,4)共150条数据,4个属性
#查看数据描述
#print(iris.DESCR)
#对数据集进行分割(训练数据、测试数据)
X_train,X_test,y_train,y_test = train_test_split(iris.data,iris.target,test_size=0.25,random_state=33)
#数据标准化
ss = StandardScaler()
X_train = ss.fit_transform(X_train)
X_test = ss.transform(X_test)
#预测
knc=KNeighborsClassifier()
knc.fit(X_train,y_train) #训练
y_predict = knc.predict(X_test) #预测
#评价
print('The Accuracy of K-Nearest Neighbor Classifier is:',knc.score(X_test,y_test))
print(classification_report(y_test,y_predict,target_names=iris.target_names))