#!/usr/bin/env python
-- coding: utf-8 --
@Time : 2020/10/22 19:43
@Author : Scheaven
@File : 13_kNN.py
@description:
简易写法
def kNN(inX,dataSet,labels,k):
m, n = dataSet.shape
distances = []
for i in range(m):
sum = 0
for j in range(n):
sum += (inX[j] - dataSet[i][j])2
distances.append(sum0.5)
sortDist = sorted(distances)
classCount = {}
for i in range(k):
voteLabel = labels[distances.index(sortDist[i])]
classCount[voteLabel] = classCount.get(voteLabel) + 1
sortedClass = sorted(classCount.items(), key=lambda d:d[1] ,reverse = True)
return sortedClass[0][0]
// 综合知识写法----------------------------
import math
import numpy as np
from collections import Counter
def my_kNN(inX, X_trains, labels, k):
distances = [math.sqrt(np.sum((inX - x_train) ** 2)) for x_train in X_trains]
nearest = np.argsort(distances)
topK_label = [labels[i] for i in nearest[0:k]]
votes = Counter(topK_label)
return votes.most_common(1)[0][0]