码农知识堂 - 1000bd
  •   Python
  •   PHP
  •   JS/TS
  •   JAVA
  •   C/C++
  •   C#
  •   GO
  •   Kotlin
  •   Swift
  • 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

    参考

  • 相关阅读:
    从永远到永远-Map传值的坑map.values()
    如何在BI中增加“路线地图”并进行数据分析?
    第2章:类加载子系统 详解
    obsidian加git备份,同时忽略掉自己不想同步的文件夹
    微信小程序项目源码ssm校园二手交易小程序+后台管理系统|前后分离VUE含论文+PPT+源码
    airflow重启
    大话超越菜鸟C#的实践入门进阶必知点,深入浅出解析 33 算法逻辑入门 抽象现实世界之大佬打一眼看不明白的代码,才是够技术含量的代码类
    Android 13.0 系统settings详情页卸载修改为停止,禁止卸载app功能实现
    非对称加密之RSA是怎么加密的?
    支付宝支付接口的调用
  • 原文地址:https://blog.csdn.net/qq_61735602/article/details/128054887
  • 最新文章
  • 攻防演习之三天拿下官网站群
    数据安全治理学习——前期安全规划和安全管理体系建设
    企业安全 | 企业内一次钓鱼演练准备过程
    内网渗透测试 | Kerberos协议及其部分攻击手法
    0day的产生 | 不懂代码的"代码审计"
    安装scrcpy-client模块av模块异常,环境问题解决方案
    leetcode hot100【LeetCode 279. 完全平方数】java实现
    OpenWrt下安装Mosquitto
    AnatoMask论文汇总
    【AI日记】24.11.01 LangChain、openai api和github copilot
  • 热门文章
  • 十款代码表白小特效 一个比一个浪漫 赶紧收藏起来吧!!!
    奉劝各位学弟学妹们,该打造你的技术影响力了!
    五年了,我在 CSDN 的两个一百万。
    Java俄罗斯方块,老程序员花了一个周末,连接中学年代!
    面试官都震惊,你这网络基础可以啊!
    你真的会用百度吗?我不信 — 那些不为人知的搜索引擎语法
    心情不好的时候,用 Python 画棵樱花树送给自己吧
    通宵一晚做出来的一款类似CS的第一人称射击游戏Demo!原来做游戏也不是很难,连憨憨学妹都学会了!
    13 万字 C 语言从入门到精通保姆级教程2021 年版
    10行代码集2000张美女图,Python爬虫120例,再上征途
Copyright © 2022 侵权请联系2656653265@qq.com    京ICP备2022015340号-1
正则表达式工具 cron表达式工具 密码生成工具

京公网安备 11010502049817号