kNN - k proche de l'algorithme

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

https://github.com/CodingSoldier/python-learn/blob/master/%E6%9C%BA%E5%99%A8%E5%AD%A6%E4%B9%A0/notebook/04-knn-k % E8% BF% 91% E9% 82% BB% E7% AE% 97% E6% B3% 95/01-KNN% E5% AE% 9E% E7% 8E% B0-% E6% 95% 99% E7% A8% 8B.ipynb

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]

 

 

 

Publié 51 articles originaux · a gagné les éloges 14 · vues 40000 +

Je suppose que tu aimes

Origine blog.csdn.net/u010606397/article/details/102917733
conseillé
Classement