KNN

1、K近邻算法(K-nearest neighbor)python

算法:
输入:
$T = { (x_{1},y_{1}),(x_{2},y_{2}),..,(x_{n},y_{n})}$
其中,$x_{i} \in X \subseteq R^{n}$为特征向量,$y_{i} \in Y ={c_{1},c_{2},..,c_{k}}$为类别,$i=1,2,3,..,N$;实例x
输出:x所属类别y
(1). 根据距离度量,在训练集T中找出与$x$最近邻的$k$个点,涵盖这$k$个点的邻域为$N_{k}(x)$
(2). 在$N_{k}(x)$中根据分类决策规则(如多数表决)决定$x$的类别$y$:
$y = argmax_{c_{j}} \sum_{x_{i} \in N_{k}(x)} I(y_{i} = c_{j}),i=1,2,..,M;j=1,2,..,K$
其中$I$为指示函数,即当$y_{i} = c_{j}$时$I$为1,不然$I$为0。算法

import numpy as np

class KNN:
    def __init__(self,X,Y,k):
        self.K = k
        self.X = X
        self.Y = Y
    def predict(self,x):
        num_samples,feat_dim = self.X.shape
        dist = np.zeros((num_samples))
        for n in range(num_samples):
            dist[n] = self.__calc_dist(X[n,:],x)
        nsmallest_idx = self.__nsmallest(dist,self.K)
        rsp = [self.Y[k] for k in nsmallest_idx]
        yset = list(set(rsp))
        return yset[np.array([rsp.count(i) for i in yset]).argmax()]
    def __calc_dist(self,x1,x2):
        return np.sum((x1-x2)**2)
    
    def __nsmallest(self,x,n):
        return x.argsort()[0:n]

例2.贷款申请样本数据表函数

ID 年龄 有工做 有本身的房子 信贷状况 类别
1 青年 通常
2 青年
3 青年
4 青年 通常
5 青年 通常
6 中年 通常
7 中年
8 中年
9 中年 很是好
10 中年 很是好
11 老年 很是好
12 老年
13 老年
14 老年 很是好
15 老年 通常

试预测:$x = (老年,是,否,通常,是)$ 是否发放贷款rest

X = np.array([[1,0,0,0,0,1,0,0,0],[1,0,0,0,0,0,1,0,0],[1,0,0,1,0,0,1,0,1],
             [1,0,0,1,1,1,0,0,1],[1,0,0,0,0,1,0,0,0],[0,1,0,0,0,1,0,0,0],
             [0,1,0,0,0,0,1,0,0],[0,1,0,1,1,0,1,0,0],[0,1,0,0,1,0,0,1,1],
             [0,1,0,0,1,0,0,1,1],[0,0,1,0,1,0,0,1,1],[0,0,1,0,1,0,1,0,1],
             [0,0,1,1,0,0,1,0,1],[0,0,1,1,0,0,0,1,1],[0,0,1,0,0,1,0,0,0]])
Y = np.array([0,0,1,1,0,0,0,1,1,1,1,1,1,1,0])
x = np.array([[0,0,1,1,0,1,0,0,1]])

clf = KNN(X,Y,3)
print clf.predict(x)
1
相关文章
相关标签/搜索