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. MySql 中IFNULL、ISNULL、NULLIF用法(数据库判空)

    来源:http://blog.csdn.net/a466350665/article/details/52994761 http://blog.csdn.net/xingyu0806/article/ ...

  2. 用数学解赌博问题不稀奇,用赌博解数学问题才牛B

    有一个经典的概率问题:平均需要抛掷多少次硬币,才会首次出现连续的 n 个正面?它的答案是 2^(n+1) – 2 .取 n=2 的话,我们就有这样的结论:平均要抛掷 6 次硬币,才能得到两个连续的正面 ...

  3. nginx中部署前端,后端打成jar包运行

    项目是前后端分离:前端用vue开发,后端用的是springboot开发 会产生跨域问题,故在前端里用了代理 1.本前端项目是用vue开发: 1.1打包:终端 vscode快捷键:crtl+~  然后n ...

  4. requests-验证码登录

    ModuleNotFoundError: No module named 'bs4': 解决方法:pip install beautifulsoup4 https://blog.csdn.net/wi ...

  5. JS高级---复习和课程介绍

    课程介绍 浅拷贝 深拷贝----------|======>递归 遍历DOM树-------|======>递归------晚上能够把代码写出来是最好的   正则表达式-------很重要 ...

  6. jdk8-》joining、groupingBy、summarizingInt函数

    拼接函数 Collectors.joining // 3种重载方法 Collectors.joining() Collectors.joining("拼接符") Collector ...

  7. macaron 根目录默认为templates文件夹,所以如果启动目录同目录下有templates目录,要给它指定另一个文件夹

    m *macaron.Macaron //随便指向一个目录,因为web没用到模板,不能使用默认值templates,因为这个目录被其他模板占用了m.Use(macaron.Renderer(macar ...

  8. error C2825: '_Iter': 当后面跟“::”时必须为类或命名空间 -- 原因可能是参数错误或者自定义函数名和库函数名冲突

    今天运行程序的时候遇到了下面这个bug > B1020.cpp >e:\vs2013\vs2013_rtm_ult_chs\data\vc\include\xutility(): erro ...

  9. [HNOI2017] 礼物 - 多项式乘法FFT

    题意:给定两个 \(n\) 元环,环上每个点有权值,分别为 \(x_i, y_i\).定义两个环的差值为 \[\sum_{i=0}^{n-1}{(x_i-y_i)^2}\] 可以旋转其中的一个环,或者 ...

  10. 使用Vue-MUI轮播图失效问题解决案例(在Vue的update中执行)

    我使用的是mui+vue,社区关于轮播图失效的问题也有几个.我这边遇到的一个情况是我把所有的东西都写到plusReady事件中会导致轮播图搞死都不动,按照其他问答解决了vue生命周期等等的问题.提出来 ...