import numpy as np
import matplotlib.pyplot as plt from sklearn import neighbors, datasets
from sklearn.model_selection import train_test_split def load_classification_data():
# 使用 scikit-learn 自带的手写识别数据集 Digit Dataset
digits=datasets.load_digits()
X_train=digits.data
y_train=digits.target
# 进行分层采样拆分,测试集大小占 1/4
return train_test_split(X_train, y_train,test_size=0.25,random_state=0,stratify=y_train) #KNN分类KNeighborsClassifier模型
def test_KNeighborsClassifier(*data):
X_train,X_test,y_train,y_test=data
clf=neighbors.KNeighborsClassifier()
clf.fit(X_train,y_train)
print("Training Score:%f"%clf.score(X_train,y_train))
print("Testing Score:%f"%clf.score(X_test,y_test)) # 获取分类模型的数据集
X_train,X_test,y_train,y_test=load_classification_data()
# 调用 test_KNeighborsClassifier
test_KNeighborsClassifier(X_train,X_test,y_train,y_test)

def test_KNeighborsClassifier_k_w(*data):
'''
测试 KNeighborsClassifier 中 n_neighbors 和 weights 参数的影响
'''
X_train,X_test,y_train,y_test=data
Ks=np.linspace(1,y_train.size,num=100,endpoint=False,dtype='int')
weights=['uniform','distance'] fig=plt.figure()
ax=fig.add_subplot(1,1,1)
### 绘制不同 weights 下, 预测得分随 n_neighbors 的曲线
for weight in weights:
training_scores=[]
testing_scores=[]
for K in Ks:
clf=neighbors.KNeighborsClassifier(weights=weight,n_neighbors=K)
clf.fit(X_train,y_train)
testing_scores.append(clf.score(X_test,y_test))
training_scores.append(clf.score(X_train,y_train))
ax.plot(Ks,testing_scores,label="testing score:weight=%s"%weight)
ax.plot(Ks,training_scores,label="training score:weight=%s"%weight)
ax.legend(loc='best')
ax.set_xlabel("K")
ax.set_ylabel("score")
ax.set_ylim(0,1.05)
ax.set_title("KNeighborsClassifier")
plt.show() # 获取分类模型的数据集
X_train,X_test,y_train,y_test=load_classification_data()
# 调用 test_KNeighborsClassifier_k_w
test_KNeighborsClassifier_k_w(X_train,X_test,y_train,y_test)

def test_KNeighborsClassifier_k_p(*data):
'''
测试 KNeighborsClassifier 中 n_neighbors 和 p 参数的影响
'''
X_train,X_test,y_train,y_test=data
Ks=np.linspace(1,y_train.size,endpoint=False,dtype='int')
Ps=[1,2,10] fig=plt.figure()
ax=fig.add_subplot(1,1,1)
### 绘制不同 p 下, 预测得分随 n_neighbors 的曲线
for P in Ps:
training_scores=[]
testing_scores=[]
for K in Ks:
clf=neighbors.KNeighborsClassifier(p=P,n_neighbors=K)
clf.fit(X_train,y_train)
testing_scores.append(clf.score(X_test,y_test))
training_scores.append(clf.score(X_train,y_train))
ax.plot(Ks,testing_scores,label="testing score:p=%d"%P)
ax.plot(Ks,training_scores,label="training score:p=%d"%P)
ax.legend(loc='best')
ax.set_xlabel("K")
ax.set_ylabel("score")
ax.set_ylim(0,1.05)
ax.set_title("KNeighborsClassifier")
plt.show() # 获取分类模型的数据集
X_train,X_test,y_train,y_test=load_classification_data()
# 调用 test_KNeighborsClassifier_k_p
test_KNeighborsClassifier_k_p(X_train,X_test,y_train,y_test)

吴裕雄 python 机器学习——KNN分类KNeighborsClassifier模型的更多相关文章

  1. 吴裕雄 python 机器学习——KNN回归KNeighborsRegressor模型

    import numpy as np import matplotlib.pyplot as plt from sklearn import neighbors, datasets from skle ...

  2. 吴裕雄 python 机器学习——半监督学习LabelSpreading模型

    import numpy as np import matplotlib.pyplot as plt from sklearn import metrics from sklearn import d ...

  3. 吴裕雄 python 机器学习——层次聚类AgglomerativeClustering模型

    import numpy as np import matplotlib.pyplot as plt from sklearn import cluster from sklearn.metrics ...

  4. 吴裕雄 python 机器学习——密度聚类DBSCAN模型

    import numpy as np import matplotlib.pyplot as plt from sklearn import cluster from sklearn.metrics ...

  5. 吴裕雄 python 机器学习——支持向量机非线性回归SVR模型

    import numpy as np import matplotlib.pyplot as plt from sklearn import datasets, linear_model,svm fr ...

  6. 吴裕雄 python 机器学习——支持向量机线性回归SVR模型

    import numpy as np import matplotlib.pyplot as plt from sklearn import datasets, linear_model,svm fr ...

  7. 吴裕雄 python 机器学习-KNN(2)

    import matplotlib import numpy as np import matplotlib.pyplot as plt from matplotlib.patches import ...

  8. 吴裕雄 python 机器学习-KNN算法(1)

    import numpy as np import operator as op from os import listdir def classify0(inX, dataSet, labels, ...

  9. 吴裕雄 python 机器学习——支持向量机SVM非线性分类SVC模型

    import numpy as np import matplotlib.pyplot as plt from sklearn import datasets, linear_model,svm fr ...

随机推荐

  1. AcWing 6. 多重背包问题 III

    //f[i,j] 所有只从前i块能量石中选,且总体积恰好为j的方案数 #include <iostream> #include <algorithm> #include < ...

  2. 题解【洛谷P2679】[NOIP2015]子串

    题面 看到求方案数,还要对 \(1000000007\ (1e9+7)\) 取模,一般这样的问题都要考虑 动态规划. 我们设 \(dp_{i,j,k,0/1}\) 表示 \(A_{1\dots i}\ ...

  3. [CQOI2009] 中位数 - 桶

    给出 \(1~n\) 的一个排列,统计该排列有多少个长度为奇数的连续子序列的中位数是 \(b\).中位数是指把所有元素从小到大排列后,位于中间的数. Solution (这个题为什么会被打上数学标签? ...

  4. (转)linux 之 grep命令

    转自:http://www.cnblogs.com/ggjucheng/archive/2013/01/13/2856896.html 简介 grep (global search regular e ...

  5. 基于 Octotree 的[码云]文件树插件

      之前一直在用github上面的Octotree,现在在用gitee(主要是github的访问速度太慢了).   现在主要转到了gitee上面了,那么有没有基于 Octotree 的[码云]文件树插 ...

  6. python特性

    # for用法 for i in range(0,100,2): print(i) n = 0 # while用法 while n < 100: print(n) n += 2 else: pr ...

  7. Python环境搭建(win)——Pycharm(破解+汉化)

    Pycharm搭建方法(破解+汉化): 本文以pycharm2019.2为例 写在前面:有能力的朋友,希望大家支持正版. IDE是集成开发环境 “Integrated Development Envi ...

  8. JavaScript的严格检查模式

    JavaScript的严格检查模式 前提:IDEA设置为ECMAScript 6语法. 'use strict':严格检查模式,用来预防JS的随意性导致的问题. 比如:直接 i=1;这样定义成了全局变 ...

  9. Xshell5配置ssh免密码登录-公钥与私钥登录linux服务器(xshell如何登陆上阿里云服务器)

    原文地址:https://blog.csdn.net/longgeaisisi/article/details/78680180 ssh登录提供两种认证方式:口令(密码)认证方式和密钥认证方式.其中口 ...

  10. DFT测试-OCC电路介绍

    https://www.jianshu.com/p/f7a2bcaefb2e SCAN技术,也就是ATPG技术-- 测试std-logic, 主要实现工具是: 产生ATPG使用Mentor的 Test ...