03.KNN算法 李航统计学习方法
原文链接:https://blog.csdn.net/qq_39355828/article/details/117513999 (opens new window)
# 03.KNN算法 李航统计学习方法
# 1.基本思想
KNN是一种简单的分类算法,可以用于简单的分类问题中。 对给定的训练实例点和输入实例点,首先确定输入实例点的k个最近邻训练实例点,然后利用这k个训练实例点的类的多数来预测输入实例点的类。
k近邻法三要素:距离度量、k值的选择和分类决策规则。常用的距离度量是欧氏距离及更一般的pL距离。k值小时,k近邻模型更复杂;k值大时,k近邻模型更简单。k值的选择反映了对近似误差与估计误差之间的权衡,通常由交叉验证选择最优的k。 图来自百度:

# 2.代码实现
import math
from numpy import *
import operator
from itertools import combinations
from numpy import array, tile
def L(x,y,p=2):#度量求取方法
if len(x)==len(y) and len(x)>1:
sum=0
for i in range(len(x)):
sum=sum+math.pow(abs(x[i]-y[i]),p)
return math.pow(sum,1/p)
else:
return 0
def KNNClassify(newInput,k):
group=array([[1.0,0.9],[1.0,1.0],[0.1,0.2],[0.0,0.1]])
labels=['A','A','B','B']
numsamples=group.shape[0]#记录样本数
diff=tile(newInput,(numsamples,1))-group#计算距离
print(diff)
distance=sum(diff**2,axis=1)**0.5
sortDistance=argsort(distance)#对距离进行排序,返回序号
print(sortDistance)
classCount={}
for i in range(k):#前k个的标签,统计输出
vote=labels[sortDistance[i]]#取出第i个对应的标签
classCount[vote]=classCount.get(vote,0)+1
maxCount=0
print(vote)
print(classCount)
for key, value in classCount.items():#排序
if value > maxCount:
maxCount = value
maxIndex = key
return maxIndex
testX = array([1.2, 1.0])
k = 3
outputLabel = KNNClassify(testX, 3)
print("Your input is:", testX, "and classified to class: ", outputLabel)
testX = array([0.1, 0.3])
outputLabel = KNNClassify(testX, 3)
print("Your input is:", testX, "and classified to class: ", outputLabel)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
代码参考: 机器学习算法与Python实践之(一)k近邻(KNN)_zouxy09的专栏-CSDN博客 (opens new window)
编辑 (opens new window)
上次更新: 2026/08/11, 13:36:18