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. 欢迎来到L T X的博客 & 博客转型公告

    这里是L T X,一位来自重庆的学生的个人博客. 由于博主以前是OIer,目前博客里主要是OI相关的内容. 但是现在博主已经退役了,因此博客将会转向...嗯...那种...就是那种...比较奇怪的类型 ...

  2. flaskapp

    前置知识 https://blog.csdn.net/u013457794/article/details/88997699?depth_1-utm_source=distribute.pc_rele ...

  3. Mono提供脚本机制(C#绑定C++)

    1.下载安装最新版mono,https://www.mono-project.com/ 2.添加头文件路径C:\Program Files\Mono\include\mono-2.0,添加库路径C:\ ...

  4. tcp与http协议 以及python的实现

    htpp协议 Rquest Headers格式: 请求方法空格URL空格协议版本回车符换行符 头部字段名:值回车符换行符 ··· 头部字段名:值回车符换行符 回车符换行符 请求数据 socket网络聊 ...

  5. centos7下编译安装redis5.05

    准备环境: 1.一台centos7机器,配置没有什么要求(能联网) 2.下载好redis压缩包 下载redis包: 1.登录redis官网: https://redis.io/download 2.选 ...

  6. 洛谷P1068 分数线划定

    https://www.luogu.org/problem/P1068 #include<bits/stdc++.h> using namespace std; struct Can { ...

  7. c语言修炼之一

    1.C项目要高内聚(模块功能必须明确,一个模块完成一个功能).低耦合(接口尽可能简单,减少各模块间的联系). 2.register类型不能为模块间的全局变量.模块内的全局变量.局部static变量.( ...

  8. lua学习,笔者自用

    标识符与关键字A:常量用全大写和下划线,eg: My_ACCOUNTB: 变量的第一个字母小写,eg: strNumberC: 全局变量第一个字母用小写g表示,eg: gMyAcountD: 函数名第 ...

  9. 数据库 oracle 函数

    static OracleConnection mQracleConnecting = null; public static OracleConnection QracleConnecting { ...

  10. Spring家族几大插件

    Spring家族很庞大,从最早先出现的服务于企业级程序开发的Core.安全方面的Security.到后来的作为各种数据源桥梁的Data.最近几年很火的Boot,以及最新推出的正在蓬勃发展的Cloud( ...