一些基本概念
什么是KNN
k近邻算法,是一种比较基础的机器学习算法,其基本规则为,相同类别的样本之间在特征空间中应该聚集在一起。这样一来,我们就无需构建一个模型,那么就没有训练学习的成本,对待预测的数据样本,我们只需要根据KNN的逻辑判断其属于哪一类即可。
惰性学习
knn就属于一种惰性学习的例子,这样的模型会对训练的数据记性记忆,即基于实例学习,它不会从训练集中通过学习得到一个判别函数,在学习训练的阶段计算成本为零。
那么就意味着,knn在预测过程中直接遍历预测点与所有点的距离,找到最近的k个点即可。在找到k个点后,用投票机制来确定预测点的类别。
距离度量方式
在
n
n
n维特征空间中,
x
i
,
x
j
x_i,x_j
xi,xj的
L
p
L_p
Lp距离定义为
L
p
(
x
i
,
x
j
)
=
(
∑
1
=
1
n
∣
x
i
(
l
)
−
x
j
(
l
)
∣
p
)
1
p
(1)
L_p(x_i,x_j)=(\sum_{1=1}^{n}|x_i^{(l)}-x_j^{(l)}|^p)^\frac {1}{p} \tag{1}
Lp(xi,xj)=(1=1∑n∣xi(l)−xj(l)∣p)p1(1)
当p=1的时候,被称为曼哈顿距离,即
L
p
(
x
i
,
x
j
)
=
(
∑
1
=
1
n
∣
x
i
(
l
)
−
x
j
(
l
)
∣
)
(2)
L_p(x_i,x_j)=(\sum_{1=1}^{n}|x_i^{(l)}-x_j^{(l)}|) \tag{2}
Lp(xi,xj)=(1=1∑n∣xi(l)−xj(l)∣)(2)
当p=2的时候,被称为欧式距离,即
L
p
(
x
i
,
x
j
)
=
(
∑
1
=
1
n
∣
x
i
(
l
)
−
x
j
(
l
)
∣
2
)
1
2
(3)
L_p(x_i,x_j)=(\sum_{1=1}^{n}|x_i^{(l)}-x_j^{(l)}|^2)^\frac {1}{2} \tag{3}
Lp(xi,xj)=(1=1∑n∣xi(l)−xj(l)∣2)21(3)
KNN的基本步骤
1)选择近邻的数量 k和距离度量方法
2)找到待分类样本的k个最近邻居
3)基于投票机制对最近邻的类标进行多数投票
代码实现
import numpy as np
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
class K_Neighbors(object):
def __init__(self,top_k):
self.top_k = top_k
def fit(self,x_train,y_train,x_test,y_test):
self.x_train = x_train
self.y_train = y_train
self.x_test = x_test
self.y_test = y_test
# 欧式距离
def _calc_Dict(self,v1,v2):
return np.sqrt(np.sum(np.square(v1-v2)))
# 计算当前点跟数据集中距离最近的k个点,得到判断该点属于哪一个类别,返回该类别
def _get_closest(self,cur_x):
distList = [0]*len(self.y_train)
for i in range(len(self.x_train)):
x1 = self.x_train[i]
curDist = self._calc_Dict(x1,cur_x)
distList[i] = curDist
topk_List = np.argsort(np.array(distList))[:self.top_k]
labelList = [0]*10
for idx in topk_List:
labelList[int(self.y_train[idx])] += 1
return labelList.index(max(labelList))
def test(self):
error = 0
for i in range(len(self.x_test)):
pred_y = self._get_closest(self.x_test[i])
if pred_y != self.y_test[i]:error += 1
return 1 - (error / len(self.x_test))
iris = load_iris()
x = iris.data
y = iris.target
x_train, x_test, y_train, y_test = train_test_split(x,y,test_size=0.2,random_state=0)
knn = K_Neighbors(top_k=5)
knn.fit(x_train,y_train,x_test,y_test)
print(knn.test())