Cet article provient de liuyubobobo « algorithmes classiques et des applications d'apprentissage machine python3 Mise en route »
k algorithme près de l'interprétation, par convention, ou devrait être donnée la définition officielle de l'algorithme k voisin, je copiais de Baidu Encyclopédie à venir
K-plus proche algorithme voisin: dans l'espace de représentation, si la majorité de l'échantillon k le plus proche voisinage de (c.-à-le plus d'espace caractéristique à côté de) l'échantillon appartient à une classe, l'échantillon entrent également dans cette catégorie.
L'étape suivante par étape pour atteindre k près de l'algorithme Jupyter Notebook
Dans mon github peut télécharger le fichier de bloc-notes
Code knn.py est la suivante:
# -*- coding: utf-8 -*-
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要大于等于1,小于等于数组X_train第一维大小"
assert X_train.shape[0] == y_train.shape[0], "数组X_train第一维大小要等于数组y_train第一维大小"
assert X_train.shape[1] == x.shape[0], "数组X_train第二维大小要等于预测点x第一维大小"
distances = [sqrt(np.sum((dot -x)**2)) for dot in X_train]
nearest = np.argsort(distances)
top_k_y = [y_train[i] for i in nearest[:k]]
votes = Counter(top_k_y)
return votes.most_common(1)[0][0]