代码实现KNN算法

import numpy as np
from math import sqrt
from collections import Counter

def kNN_classify(k, X_train, y_train, x):
    assert 1 <= k <= X_train.shape[0], "k must be valid"
    assert X_train.shape[0] == y_train.shape[0], "the size of X_train must equal to the size of y_train"
    assert X_train.shape[1] == x.shape[0], "the feature number of x must be equal to X_train"

    distances = [sqrt(np.sum((x_train-x)**2)) for x_train in X_train]
    nearst = np.argsort(distances)

    topK_y = [y_train[i] for i in nearst[:k]]
    votes = Counter(topK_y)

    return votes.most_common(1)[0][0]

准备数据

import numpy as np
raw_data_X = [[3.39, 2.33],
              [3.11, 1.78],
              [1.34, 3.36],
              [3.58, 4.67],
              [2.28, 2.86],
              [7.42, 4.69],
              [5.74, 3.53],
              [9.17, 2.51],
              [7.79, 3.42],
              [7.93, 0.79]
             ]
raw_data_y = [0, 0, 0, 0, 0, 1, 1, 1, 1, 1]

X_train = raw_data_X
y_train = raw_data_y

x = np.array([8.09, 3.36])

调用算法

predict_y = kNN_classify(6, X_train, y_train, x)

运行结果:predict_y = 1

什么是机器学习

KNN是一个不需要训练的算法
KNN没有模型,或者说训练数据就是它的模型

使用scikit-learn中的kNN

错误写法

from sklearn.neighbors import KNeighborsClassifier

kNN_classifier.fit(X_train, y_train)
kNN_classifier.predict(x)

这样写会报错:

原因是,predict为了兼容多组测试数据的场景,要求参数是个矩阵

正确写法

from sklearn.neighbors import KNeighborsClassifier

kNN_classifier.fit(X_train, y_train)
X_predict = x.reshape(1, -1)
y_predict = kNN_classifier.predict(X_predict)

运行结果:predict_y[0] = 1

重新整理我们的kNN的代码

封装成sklearn风格的类

import numpy as np
from math import sqrt
from collections import Counter

class kNNClassifier:

    def __init__(self, k):
        """初始化kNN分类器"""
        assert k >= 1, "K must be valid!"
        self.k = k
        self._X_train = None
        self._y_train = None

    def fit(self, X_train, y_train):
        """根据训练数据集X_train和y_train训练kNN分类器"""
        assert X_train.shape[0] == y_train.shape[0], "the size of X_train must equal to the size of y_train"
        assert self.k <= X_train.shape[0], "the size of X_train must be at least k"

        self._X_train = X_train
        self._y_train = y_train
        return self

    def predict(self, X_predict):
        """给定待预测数据集X_predict, 返回表示X_predict的结果向量"""
        assert self._X_train is not None and self._X_train is not None, "must fit before predict"
        assert self._X_train.shape[1] == X_predict.shape[1], "the feature number of X_predict must be equal to X_train"

        y_predict = [self._predict(x) for x in X_predict]
        return np.array(y_predict)

    def _predict(self, x):
        """给定单个待测数据x,返回x的预测结果"""
        assert self._X_train.shape[1] == x.shape[0], "the feature number of x must be equal to X_train"

        distances = [sqrt(np.sum((x_train-x)**2)) for x_train in self._X_train]
        nearst = np.argsort(distances)

        topK_y = [self._y_train[i] for i in nearst[:self.k]]
        votes = Counter(topK_y)

        return votes.most_common(1)[0][0]

    def __repr__(self):
        return "KNN(k=%d)" % self.k

使用kNNClassifier

knn_clf = kNNClassifier(k=6)
knn_clf.fit(X_train, y_train)
y_predict = knn_clf.predict(X_predict)

运行结果:predict_y[0] = 1