k近邻算法之python实例
2022/3/19 11:29:34
本文主要是介绍k近邻算法之python实例,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
import math import numpy as np # 在本代码中需要您进行预测我们需要准备多少根香肠。record里的数据分别对应。 #================ def knn(record, target, k): distances = [] record_numbers = [] for i in record: distance = 0 for j in range(len(target)-1): distance += (target[j] - i[j])**2 distances.append(math.sqrt(distance)) record_numbers.append(i[len(target)-1]) knn_distance = [] knn_numbers = [] for i in range(k): min_distance = min(distances) min_index = distances.index(min_distance) knn_distance.append(distances.pop(min_index)) knn_numbers.append(record_numbers.pop(min_index)) return knn_distance, knn_numbers def agression(knn_numbers): return np.mean(knn_numbers) target = [1, 5, 2, 'value'] record = [[0, 3, 3, 100], [2, 4, 3, 250], [2, 5, 5, 350], [1, 4, 2, 180], [2, 3, 1, 170], [1, 5, 4, 300], [0, 1, 1, 50], [2, 4, 3, 275], [2, 2, 4, 230], [1, 3, 5, 165], [1, 5, 5, 320], [2, 5, 1, 210]] k = 5 distances, numbers = knn(record, target, k) number = agression(numbers) print('应该准备%d根香肠'%number) for i in range(k): print('k近邻的距离%6.4f, 销售数量为%d'%(distances[i], numbers[i]))
这篇关于k近邻算法之python实例的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-11-21Python编程基础教程
- 2024-11-20Python编程基础与实践
- 2024-11-20Python编程基础与高级应用
- 2024-11-19Python 基础编程教程
- 2024-11-19Python基础入门教程
- 2024-11-17在FastAPI项目中添加一个生产级别的数据库——本地环境搭建指南
- 2024-11-16`PyMuPDF4LLM`:提取PDF数据的神器
- 2024-11-16四种数据科学Web界面框架快速对比:Rio、Reflex、Streamlit和Plotly Dash
- 2024-11-14获取参数学习:Python编程入门教程
- 2024-11-14Python编程基础入门