chapter02 K近邻分类器对Iris数据进行分类预测

寻找与待分类的样本在特征空间中距离最近的K个已知样本作为参考,来帮助进行分类决策。

与其他模型最大的不同在于:该模型没有参数训练过程。无参模型,高计算复杂度和内存消耗。

#coding=utf8
# 从sklearn.datasets 导入 iris数据加载器。
from sklearn.datasets import load_iris
# 从sklearn.model_selection中导入train_test_split用于数据分割。
from sklearn.model_selection import train_test_split
# 从sklearn.preprocessing里选择导入数据标准化模块。
from sklearn.preprocessing import StandardScaler
# 从sklearn.neighbors里选择导入KNeighborsClassifier,即K近邻分类器。
from sklearn.neighbors import KNeighborsClassifier
# 依然使用sklearn.metrics里面的classification_report模块对预测结果做更加详细的分析。
from sklearn.metrics import classification_report

iris = load_iris()
# 从使用train_test_split,利用随机种子random_state采样25%的数据作为测试集。
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)

# 使用K近邻分类器对测试数据进行类别预测,预测结果储存在变量y_predict中。
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)

结果:

posted on 2017-10-11 20:30  TMatrix52  阅读(248)  评论(0编辑  收藏  举报

导航