KNN实现以及一些好用的numpy函数

1. numpy求数组的最小k个数:

np.argpartition(arr, k) 做的是快排中的f分区步骤,它不改变原来的数组,只会返回分区好之后的数组的索引,保证前 k -1 个索引对应的元素 < = 第k个;例如:

      > arr= np.array([1, 3, 5, 4, 6, 2, 8])

      > np.argpartition(arr, 3)

      > [ 0, 5, 1, 2, 4, 3, 6]

如果要取最小k个,切片[ 0:k]; 要取最大k个,切片[ -k : ].

2. numpy求数组中出现次数最多的元素

np.bincount(arr), 是去数 [0, 数组最大的元素] 范围中的所有整数在数组中的出现次数。如:

       > arr = np.array( [ 1, 2, 1, 3, 4, 2] )

       > np.bincount(arr)

       > [0., 2., 2., 1., 1.,]

则用np.argmax(np.bincount(arr) ) 就可以得到出现次数最多的元素值。

3. kNN python实现:

class kNN:
    def __init__(self):
        self.x_train=[]
        self.y_train=[]
    def train(self, X,Y):
        self.x_train = np.array(X)
        self.y_train = np.array(Y)
        return self
    def predict(self, x_test, k=3, regularization = 'L1'):
        num_test = x_test.shape[0]
        y_predict = np.zeros(num_test, dtype=self.y_train.dtype)
        for i in range(num_test):
            if regularization == 'L1':
                distance = np.sum(np.abs(self.x_train - x_test[i,:]), axis=1 )
            elif regularization == 'L2':
                distance = np.sum(np.square(self.x_train - x_test[i,:]), axis=1)
            else:
                distance = np.sum(np.abs(self.x_train - x_test[i,:]), axis=1)
            nearest_idx = np.argpartition(distance, k-1)[0:k]
            votes = self.y_train[nearest_idx]
            y_predict[i] = np.argmax(np.bincount(votes))

        return y_predict
    def accuray(self, y_predict, y_test):
        acc = np.sum(y_predict==y_test)/y_predict.shape[0]
        return acc

用的数据集是MNIST手写数字辨认。http://yann.lecun.com/exdb/mnist/

自己用测试数据做了交叉验证,得到比较好的超参是 k=3,L2。

最后测试结果正确率为 97.05%( error rate 2.95%),比mnist首页同样的KNN 'L2'得到的结果错误率低0.14%

猜你喜欢

转载自www.cnblogs.com/rarecu/p/11546894.html