• 2022年 11月26日 KNN 学习笔记


    参考

    KNN算法是监督学习里的分类算法,利用一个已知的分类图,我们取定K值,通过计算K个最近点的距离,看要预测的点在K个值里某个类别数目最多它就是该类别。K值的确定可以通过交叉验证来得到。KNN可以利用sklearn库来计算。

    寻找样本数据集K个最近的元素

    计算K个元素中各种类别的占比

    占比最高的类别即为新数据的类别

    K的取值对结果有很大的影响

    交叉验证法选取最佳 k值

    from sklearn.datasets import load_iris
    from sklearn.model_selection import cross_val_score
    import matplotlib.pyplot as plt
    from sklearn.neighbors import KNeighborsClassifier
    
    #加载鸢尾花数据集
    iris = load_iris()
    x = iris.data
    y = iris.target
    k_range = range(1, 31) # 设置循环次数
    k_error = []
    #循环,取k从1~30,查看误差效果
    for k in k_range:
        knn = KNeighborsClassifier(n_neighbors=k)
        #cv参数决定数据集划分比例,这里是按照5:1划分训练集和测试集
        scores = cross_val_score(knn, x, y, cv=6, scoring='accuracy')
        k_error.append(1 - scores.mean())
    
    #画图,x轴为k值,y值为误差值
    plt.plot(k_range, k_error)
    plt.xlabel('Value of K in KNN')
    plt.ylabel('Error')
    plt.show()
    
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25

    KNN实例

    import numpy as np
    import matplotlib.pyplot as plt
    from matplotlib.colors import ListedColormap
    from sklearn import neighbors, datasets
    
    n_neighbors = 11
    
    # 加载鸢尾花数据集
    iris = datasets.load_iris()
    # 选择其中的两个特征
    X = iris.data[:, :2]
    y = iris.target
    
    h = .02 # 网格步长
    
    # 创建色彩图
    cmap_light = ListedColormap(['orange', 'cyan', 'cornflowerblue'])
    cmap_bold = ListedColormap(['darkorange', 'c', 'darkblue'])
    
    # 在两种权重下绘制图像
    for weights in ['uniform', 'distance']:
    	# 创建knn分类器实例, 并进行训练拟合
    	clf = neighbors.KNeighborsClassifier(n_neighbors, weights = weights)
    	clf.fit(X,y)
    
    	 # 绘制决策边界
    	x_min, x_max = X[:,0].min() - 1, X[:,0].max() + 1
    	y_min, y_max = X[:,1].min() - 1, X[:,1].max() + 1
    	xx, yy = np.meshgrid(np.arange(x_min, x_max, h),
    						 np.arange(y_min, y_max, h))
    	Z = clf.predict(np.c_[xx.ravel(), yy.ravel()])
    	
    	Z = Z.reshape(xx.shape)
    	plt.figure()
    	plt.pcolormesh(xx, yy, Z, cmap = cmap_light)
    
    	# 绘制训练点
    	plt.scatter(X[:, 0], X[:, 1], c = y, cmap = cmap_bold, edgecolor='k', s=20)
    	plt.xlim(xx.min(), xx.max())
    	plt.ylim(yy.min(), yy.max())
    	plt.title('3-Class classification (k = %i, weights = "%s")' % (n_neighbors, weights))
    
    plt.show()
    
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45

    参考

  • 相关阅读:
    OpenAI 推出ChatGPT Edu,为高校定制版本
    【非技术】对自己接到工作任务时的一些提醒
    ps gif动图怎么做,教你一招更简单
    抽象工厂
    企业防护墙管理,有什么防火墙管理工具?
    学习开发一个RISC-V上的操作系统(汪辰老师) — 环境配置
    一个实用的链接导航页的站点设计 支持自定义链接
    【光学】基于matlab GUI矩阵法和等效界面法光学薄膜对反射率影响【含Matlab源码 2102期】
    mysql启动报错The server quit without updating PID file几种解决办法
    HTTP协议 学习笔记
  • 原文地址:https://blog.csdn.net/qq_61735602/article/details/128054887