KNN簡單實現

2021-09-01 06:24:59 字數 2319 閱讀 2209

knn算是機器學習入門演算法中比較容易理解的了,要注意和k-means的一些區別

knn

k-means

1.knn是分類演算法  2.監督學習 

3.餵給它的資料集是帶label的資料,已經是完全正確的資料

1.k-means是聚類演算法  2.非監督學習 

3.餵給它的資料集是無label的資料,是雜亂無章的,經過聚類後才變得有點順序,先無序,後有序

沒有明顯的前期訓練過程,屬於memory-based learning

有明顯的前期訓練過程

k的含義:來了乙個樣本x,要給它分類,即求出它的y,就從資料集中,在x附近找離它最近的k個資料點,這k個資料點,類別c佔的個數最多,就把x的label設為c

k的含義:k是人工固定好的數字,假設資料集合可以分為k個簇,由於是依靠人工定好,需要一點先驗知識

python簡單實現

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"

distance = [sqrt(np.sum((x_train - x)**2))

for x_train in self._x_train]

nearest = np.argsort(distance)

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(一) 簡單KNN原理及實現

原文 1.knn演算法介紹 鄰近演算法,或者說k最近鄰 knn,k nearestneighbor 分類演算法可以說是整個資料探勘分類技術中最簡單的方法了。所謂k最近鄰,就是k個最近的鄰居的意思,說的是每個樣本都可以用她最接近的k個鄰居來代表。knn演算法的核心思想是如果乙個樣本在特徵空間中的k個最...

KNN(一) 簡單KNN原理及實現

原文 1.knn演算法介紹 鄰近演算法,或者說k最近鄰 knn,k nearestneighbor 分類演算法可以說是整個資料探勘分類技術中最簡單的方法了。所謂k最近鄰,就是k個最近的鄰居的意思,說的是每個樣本都可以用她最接近的k個鄰居來代表。knn演算法的核心思想是如果乙個樣本在特徵空間中的k個最...

KNN應用及演算法簡單實現

鳶尾 yu n w i 學名 iris tectorum maxim.iris 資料集,統計學常用資料集 fromsklearn importneighbors fromsklearn importdatasets knn neighbors.kneighborsclassifier iris da...