Python教程

k近邻算法之python实例

本文主要是介绍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实例的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!