2019-10-10 kNN近邻算法

kNN近邻算法

算法原理

样本点的特性与该邻居点的特性类似,可以简单理解为“物以类聚”。因此可以使用目标点的多个邻近点的特性表示当前点的特性。

k近邻算法是非常特殊的,可以被认为是没有模型的算法,为了和其他算法统一,可以认为训练数据集就是模型本身。

KNN分类算法:“投票法”,选择这k 个样本中出现最多的类别标记作为预测结果。

KNN回归算法:“平均法”,将这k 个样本的实值输出标记的平均值作为预测结果。

欧拉距离公式

欧拉距离公式

化简公式

KNN算法的核心要素

1.K值的选择:K是超参(需要给定),K值过小容易导致过拟合(比如噪音点的数据会对结果造成影响),K值过大训练误差会增大,同时会使模型变得简单,容易导致欠拟合。

2.距离的度量:采用欧式距离。

3.决策规则:在分类模型中,主要使用多数表决法或者加权多数表决法;在回归模型中,主要使用平均值法或者加权平均值法。(基于距离远近进行加权,,距离越近的样本权重越大.)。

kNN算法源码

import numpy as np
from math import sqrt
from collections import Counter
from sklearn.metrics import accuracy_score

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 be 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._y_train is not None, \
                "must fit before predict!"
        assert X_predict.shape[1] == self._X_train.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 x.shape[0] == self._X_train.shape[1], \
            "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]
        nearest = np.argsort(distances)

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

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

    def score(self, X_test, y_test):
        """根据测试数据集 X_test 和 y_test 确定当前模型的准确度"""

        y_predict = self.predict(X_test)
        return accuracy_score(y_test, y_predict)

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

kNN原生代码

import numpy as np
from math import sqrt
import matplotlib.pyplot as plt
#数据处理
raw_data_X = [[3.393533211, 2.331273381],
              [3.110073483, 1.781539638],
              [1.343808831, 3.368360954],
              [3.582294042, 4.679179110],
              [2.280362439, 2.866990263],
              [7.423436942, 4.696522875],
              [5.745051997, 3.533989803],
              [9.172168622, 2.511101045],
              [7.792783481, 3.424088941],
              [7.939820817, 0.791637231]
             ]
raw_data_y = [0, 0, 0, 0, 0, 1, 1, 1, 1, 1]
x = np.array([8.093607318, 3.365731514])  #要判断的新的点归于属于0还是1
X_train = np.array(raw_data_X)
y_train = np.array(raw_data_y)
#近邻算法:计算距离
distances = []
for x_train in X_train:
    d = sqrt(np.sum((x_train-x)**2))  #求欧拉距离的公式
    distances.append(d)

print(distances)
nearest = np.argsort(distances)#按索引排序,默认从小到大
print(nearest)
k = 6  #knn算法:取6
num = [y_train[neighbors] for neighbors in nearest[:k]]
print(num)
from collections import Counter
votes = Counter(num)
print(votes.most_common(1)[0][0])

plt.scatter(X_train[y_train==0,0],X_train[y_train==0,1],color='g')
plt.scatter(X_train[y_train==1,0],X_train[y_train==1,1],color='r')
plt.scatter(x[0],x[1],color='b')
plt.show()

你可能感兴趣的:(2019-10-10 kNN近邻算法)