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]))
标签:knn,distance,distances,python,近邻,min,record,实例,numbers 来源: https://blog.csdn.net/weixin_56636204/article/details/123589297