一篇文章入门KNN算法

文章目录

  • KNN
    • KNN算法
    • KNN in practice
    • 推荐系统
      • 我们想回答什么问题?
      • 探索、清理和准备数据
      • 使用算法
    • Summary
  • 参考文献

KNN

监督学习是一种依赖输入数据来学习函数的算法,该函数在给定新的未标记数据时可以产生适当的输出

监督学习用于解决分类或回归问题。

分类问题的输出是离散值。例如,“喜欢披萨上的菠萝”和“不喜欢披萨上菠萝”是离散的,没有中间立场。

回归问题的输出是实数(带小数点的数字)。例如,我们可以使用下表中的数据来估计给定身高的人的体重。

在这里插入图片描述
我们有一个自变量(或一组自变量)和一个因变量(给定自变量,我们试图猜测的事情)。例如,我们可以说身高是自变量,体重是因变量。

无监督的机器学习算法使用没有任何标签的输入数据——换句话说,没有老师(标签)告诉孩子(计算机)什么时候是正确的,什么时候犯了错误

监督学习试图学习一个函数,该函数将允许我们在给定一些新的未标记数据的情况下进行预测;无监督学习试图学习数据的基本结构,让我们对数据有更多的了解。

KNN算法

KNN算法假设相似的事物存在于非常接近的地方,换句话说,相似的事物彼此接近

“Birds of a feather flock together.”

在这里插入图片描述
在上图中,大多数情况下,相似的数据点彼此接近。KNN算法取决于这个假设是否足够真实,从而使算法有用。

**直线距离(Euclidean Distance)**是一个流行且熟悉的选择。

The KNN Algorithm:

  1. Load the data
  2. Initialize K to your chosen number of neighbors
  3. For each example in the data: Calculate the distance between the query example and the current example from the data; Add the distance and the index of the example to an ordered collection.
  4. Sort the ordered collection of distances and indices from smallest to largest (in ascending order) by the distances.
  5. Pick the first K entries from the sorted collection.
  6. Get the labels of the selected K entries.
  7. If regression, return the mean of the K labels.
  8. If classification, return the mode of the K labels.
# --*-- coding:utf-8 --*--
# @Author : 一只楚楚猫
# @File : 03KNN.py
# @Software : PyCharm
from collections import Counter
import mathdef knn(data, query, k, distance_fn, choice_fn):""":param data: Regression Data:param query: Query Data:param k: K Neighbours:param distance_fn: Euclidean Distance:param choice_fn::return:"""neighbor_distances_and_indices = []# 3. For each example in the datafor index, example in enumerate(data):# 3.1 Calculate the distance between the query example and the current# example from the data.distance = distance_fn(example[:-1], query)# 3.2 Add the distance and the index of the example to an ordered collectionneighbor_distances_and_indices.append((distance, index))# 4. Sort the ordered collection of distances and indices from# smallest to largest (in ascending order) by the distancessorted_neighbor_distances_and_indices = sorted(neighbor_distances_and_indices)# 5. Pick the first K entries from the sorted collectionk_nearest_distances_and_indices = sorted_neighbor_distances_and_indices[:k]# 6. Get the labels of the selected K entriesk_nearest_labels = [data[i][-1] for distance, i in k_nearest_distances_and_indices]# 7. If regression (choice_fn = mean), return the average of the K labels# 8. If classification (choice_fn = mode), return the mode of the K labelsreturn k_nearest_distances_and_indices, choice_fn(k_nearest_labels)def mean(labels):return sum(labels) / len(labels)def mode(labels):"""most_common是Counter类的方法,用于返回出现频率最高的元素及其计数。在这里,most_common(1)返回一个包含一个元组的列表,元组的第一个元素是出现频率最高的元素,第二个元素是该元素出现的次数。由于我们指定参数1,因此它返回出现频率最高的1个元素。"""return Counter(labels).most_common(1)[0][0]def euclidean_distance(point1, point2):sum_squared_distance = 0for i in range(len(point1)):sum_squared_distance += math.pow(point1[i] - point2[i], 2)return math.sqrt(sum_squared_distance)def main():'''# Regression Data## Column 0: height (inches)# Column 1: weight (pounds)'''reg_data = [[65.75, 112.99],[71.52, 136.49],[69.40, 153.03],[68.22, 142.34],[67.79, 144.30],[68.70, 123.30],[69.80, 141.49],[70.01, 136.46],[67.90, 112.37],[66.49, 127.45],]# Question:# Given the data we have, what's the best-guess at someone's weight if they are 60 inches tall?reg_query = [60]reg_k_nearest_neighbors, reg_prediction = knn(reg_data, reg_query, k=3, distance_fn=euclidean_distance, choice_fn=mean)print(f"reg_prediction: {reg_prediction}")'''# Classification Data# # Column 0: age# Column 1: likes pineapple'''clf_data = [[22, 1],[23, 1],[21, 1],[18, 1],[19, 1],[25, 0],[27, 0],[29, 0],[31, 0],[45, 0],]# Question:# Given the data we have, does a 33 year old like pineapples on their pizza?clf_query = [33]clf_k_nearest_neighbors, clf_prediction = knn(clf_data, clf_query, k=3, distance_fn=euclidean_distance, choice_fn=mode)print(f"cls_prediction: {clf_prediction}")if __name__ == '__main__':main()

Advantages:

  1. 该算法简单,易于实现。
  2. 无需构建模型、调整多个参数或做出额外的假设。
  3. 该算法具有通用性。它可用于分类、回归和搜索。

Disadvantages:

  1. 随着自变量的增加,算法会明显变慢

KNN in practice

KNN 的主要缺点是随着数据量的增加而明显变慢,这使得它在需要快速做出预测的环境中成为不切实际的选择。

在推荐系统中可以使用KNN算法

推荐系统

我们想回答什么问题?

给定我们的电影数据集,与电影查询最相似的 5 部电影是什么?

探索、清理和准备数据

我们上面的 KNN 实现依赖于结构化数据。它需要采用表格格式。此外,该实现假设所有列都包含数字数据,并且数据的最后一列具有可以执行某些功能的标签。因此,无论我们从哪里获取数据,我们都需要使其符合这些约束。

该数据包含 30 部电影,包括七种类型的每部电影的数据及其 IMDB 评级。标签列全为零,因为我们不使用该数据集进行分类或回归。

此外,在使用 KNN 算法时,电影之间的关系(例如演员、导演和主题)不会被考虑在内,因为捕获这些关系的数据在数据集中丢失了。因此,当我们对数据运行 KNN 算法时,相似性将仅基于所包含的类型和电影的 IMDB 评级。

使用算法

想象一下。我们正在浏览 MoviesXb 网站(一个虚构的 IMDb 衍生产品),然后遇到了《华盛顿邮报》。我们不确定我们是否想看它,但它的类型引起了我们的兴趣;我们对其他类似的电影感到好奇。我们向下滚动到 “更多类似内容” 部分,看看 MoviesXb 会提出什么建议,算法齿轮开始转动。

MoviesXb 网站向其后端发送请求,获取与《华盛顿邮报》最相似的 5 部电影。后端有一个和我们一模一样的推荐数据集。它首先为《华盛顿邮报》创建行表示(更广为人知的名称是特征向量),然后运行类似于下面的程序来搜索与《华盛顿邮报》最相似的 5 部电影,最后将结果发送回 MoviesXb 网站。

import sys"""
python import模块时, 是在sys.path里按顺序查找的。
sys.path是一个列表,里面以字符串的形式存储了许多路径。
使用KNN.py文件中的函数需要先将它的文件路径放到sys.path中
"""
sys.path.append(r"E:\楚楚猫\code\python\02NLP\01文本分析")from KNN import knn, euclidean_distancedef recommend_movies(movie_query, k_recommendations):raw_movies_data = []with open('./data/movies_recommendation_data.csv', 'r') as md:# Discard the first line (headings)next(md)# Read the data into memoryfor line in md.readlines():data_row = line.strip().split(',')raw_movies_data.append(data_row)# Prepare the data for use in the knn algorithm by picking# the relevant columns and converting the numeric columns# to numbers since they were read in as stringsmovies_recommendation_data = []for row in raw_movies_data:data_row = list(map(float, row[2:]))movies_recommendation_data.append(data_row)# Use the KNN algorithm to get the 5 movies that are most# similar to The Post.recommendation_indices, _ = knn(movies_recommendation_data, movie_query, k=k_recommendations,distance_fn=euclidean_distance, choice_fn=lambda x: None)movie_recommendations = []for _, index in recommendation_indices:movie_recommendations.append(raw_movies_data[index])return movie_recommendationsif __name__ == '__main__':the_post = [7.2, 1, 1, 0, 0, 0, 0, 1, 0]  # feature vector for The Postrecommended_movies = recommend_movies(movie_query=the_post, k_recommendations=5)# Print recommended movie titlesfor recommendation in recommended_movies:print(recommendation[1])

movies_recommendation_data.csv数据获取链接

Summary

KNN算法是一种简单的监督学习算法,用于解决分类问题和回归问题。它很容易实现和理解,但有一个主要缺点,随着数据大小的增长,速度会明显变慢。

KNN的工作原理是查询Query与数据中所有示例之间的距离,选择最接近查询的指定数量(K)。然后投票选出最频繁的标签(在分类的情况下)或对标签进行平均(在回归的情况)

参考文献

[1]Machine Learning Basics with the K-Nearest Neighbors Algorithm
[2]在一个.py文件中调用另一个py文件中的类或函数
[3]一篇文章入门python基础

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/125530.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

LLM - 训练与推理过程中的 GPU 算力评估

目录 一.引言 二.FLOPs 和 TFLOPs ◆ FLOPs [Floating point Opearation Per Second] ◆ TFLOPs [Tera Floating point Opearation Per Second] 三.训练阶段的 GPU 消耗 ◆ 影响训练的因素 ◆ GPT-3 训练统计 ◆ 自定义训练 GPU 评估 四.推理阶段的 GPU 消耗 ◆ 影响…

bitsandbytes 遇到CUDA Setup failed despite GPU being available.

使用conda 管理环境时加载大模型会遇到bitsandbytes无法识别cuda的情况: 此处windows系统: pip install bitsandbytes-windowslinux 系统: 将bitsandbytes版本降低至0.39.0 pip install bitsandbytes0.39.0

Pap.er for Mac:高清壁纸应用打造你的专属视觉盛宴

在浩瀚的互联网海洋中,你是否曾为寻找一张心仪的高清壁纸而烦恼?或者是在大量的壁纸应用中感到困扰,不知道哪一个能满足你的需求?今天,我要向你介绍的,是一款独特的5K高清壁纸应用——Pap.er for Mac。 Pa…

leetcode:374. 猜数字大小(二分查找)

一、题目 函数原型:int guessNumber(int n) 二、思路 本题其实就是从 1 - n 中找出所要的答案。利用guess函数来判断数字是否符合答案。 答案小于当前数字,guess函数返回-1 答案等于当前数字,guess函数返回0 答案大于当前数字,gue…

golang工程— grpc-gateway健康检查和跨域配置

grpc健康检查网关跨域配置 grpc健康检查 grpc健康检查使用 服务端配置 import ("google.golang.org/grpc/health""google.golang.org/grpc/health/grpc_health_v1" )//添加健康检查服务,多路复用 grpc_health_v1.RegisterHealthServer(s, health.NewSe…

Java Web 项目通用基础响应结果类 BaseRespResult

文章归档&#xff1a;https://www.yuque.com/u27599042/coding_star/cl36rbz6b51t5x44 BaseRespResult&#xff1a;用于封装响应客户端数据的基本结果类 依赖 <parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-…

织梦dedecms后台档案列表显示空白或显示不了文章的解决方法

织梦dedecms后台档案列表显示空白或显示不了文章的解决方法 dede/content_list.php空白解决方法如下 dede/content_list.php空白 在DEDE后台可以查看栏目文章&#xff0c;但是所有档案列表却为空白或者显示不了文章,如图所示&#xff1a; 后来找到dede/content_list.php,看了下…

Android NDK开发详解之ndk-build 脚本

Android NDK开发详解之ndk-build 脚本 内部原理从命令行调用选项可调试 build 与发布 build要求 ndk-build 脚本使用 NDK 的基于 Make 的构建系统构建项目。我们针对 ndk-build 使用的 Android.mk 和 Application.mk 配置提供了更具体的文档。 内部原理 运行 ndk-build 脚本相…

使用pytorch解析mnist数据集

当解析MNIST数据集时&#xff0c;以下是代码的详细介绍&#xff1a; 1. **导入必要的库**&#xff1a; import torch import torchvision from torchvision import transforms from torchvision.datasets import MNIST import matplotlib.pyplot as plt 这些库是用于处理数…

持续集成部署-k8s-服务发现-Ingress 路径匹配与虚拟主机匹配

持续集成部署-k8s-服务发现-Ingress 路径匹配与虚拟主机匹配 1. 安装 Ingress-Nginx2. 创建要代理的 Service3. 创建一个新的 Ingress-Nginx1. 安装 Ingress-Nginx 要使用 Ingress-Nginx 首先第一步是需要先安装它,安装的步骤可以参考:持续集成部署-k8s-服务发现-Ingress 2…

C++基础复习

C—Cherno 一、C中的引用 #include<iostream> #include"Log.h"void Increment(int& value) {value; }int main() {int a 5;int b 10;//引用不能只声明不赋值//&就和数据类型差不多&#xff0c;要和int写在一起&#xff0c;int&int& ref a…

JVM 分代垃圾回收过程

堆空间划分了代&#xff1a; 年轻代&#xff08;Young Generation&#xff09;分为 eden 和 Survivor 两个区&#xff0c;Survivor 又分为2个均等的区&#xff0c;S0 和 S1。 首先&#xff0c;新对象都分配到年轻代的 eden 空间&#xff0c;Survivor 刚开始是空的。 当 eden …

4. 一文快速学懂常用工具——GDB(上)

本章讲解知识点 什么是GDB?GDB 的安装在Windows平台上使用GDB攻略为什么 Git 可以?本专栏适合于软件开发刚入职的学生或人士,有一定的编程基础,帮助大家快速掌握工作中必会的工具和指令。本专栏针对面试题答案进行了优化,尽量做到好记、言简意赅。如专栏内容有错漏,欢迎在…

添加多个单元对象

开发环境&#xff1a; Windows 11 家庭中文版Microsoft Visual Studio Community 2019VTK-9.3.0.rc0vtk-example参考代码 demo解决问题&#xff1a;不同阶段添加多个单元对象。 定义一个点集和一个单元集合&#xff0c;单元的类型可以是点、三角形、矩形、多边形等基本图形。只…

2023NOIP A层联测21-异或

给定一长度为 N N N 的由非负整数组成的数组 a a a&#xff0c;你需要进行一系列操作&#xff0c;每次操作选择一个区间 [ l , r ] [l,r] [l,r]&#xff0c;将 a [ l , r ] a_{[l,r]} a[l,r]​ 异或上 w w w。你需要将 a i a_i ai​ 全部变为 0 0 0。 求最小操作次数。…

MaxPatrol SIEM 8.0:用于行为分析的 ML,降低了硬件要求,每秒可处理超过 50 万个信息安全事件

Positive Technologies 发布了 MaxPatrol SIEM 信息安全事件监控和事件检测系统的第八个版本。更新后的产品将使该公司在需要超大型安装的公司和需要使用人工智能技术的政府机构中的市场份额增加近三分之一。 主要变化包括降低了硬件要求&#xff0c;提高了系统性能&#xff0…

【Windows】线程同步之信号量(Semaphores)

概述&#xff1a; semaphores 的说明和使用 微软官方文档&#xff1a; Semaphore Objects - Win32 apps | Microsoft Learn Semaphores是解决各种 producer/consumer问题的关键要素。这种问题会存有一个缓冲区&#xff0c;可能在同一时间内被读出数据或被写入数据。 理论可以证…

招生报名缴费小程序开发笔记(上)

前期调研 1.数字化趋势&#xff1a; 随着社会的数字化转型&#xff0c;越来越多的教育机构倾向于采用数字工具来简化和优化他们的招生和报名过程。招生报名缴费小程序是应对这一趋势的一种解决方案&#xff0c;可以提供高效、方便、快速的在线招生渠道。2.用户需求&#xff1a…

Jtti:Apache服务的反向代理及负载均衡怎么配置

配置Apache服务的反向代理和负载均衡可以帮助您分散负载并提高应用程序的可用性和性能。下面是一些通用的步骤&#xff0c;以配置Apache反向代理和负载均衡。 1. 安装和配置Apache&#xff1a; 确保您已经安装了Apache HTTP服务器。通常&#xff0c;Apache的配置文件位于/etc…