本文實例講述了python機器學習之scikit-learn庫中knn算法的封裝與使用方法。分享給大家供大家參考,具體如下:
1、工具準備,python環境,pycharm
2、在機器學習中,knn是不需要訓練過程的算法,也就是說,輸入樣例可以直接調用predict預測結果,訓練數據集就是模型。當然這里必須將訓練數據和訓練標簽進行擬合才能形成模型。
3、在pycharm中創建新的項目工程,并在項目下新建knn.py文件。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
|
import numpy as np from math import sqrt from collections import counter class knnclassifier: def __init__( self ,k): """初始化knn分類器""" assert k > = 1 """斷言判斷k的值是否合法""" 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 ] """數據和標簽的大小必須一樣 assert self.k <= x_train.shape[0] """ k的值不能超過數據的大小 """ self._x_train = x_train self._y_train = y_train return self def predict(self,x_predict): """ 必須將訓練數據集和標簽擬合為模型才能進行預測的過程 """ assert self._x_train is not none and self._y_train is not none """ 訓練數據和標簽不可以是空的 """ assert x_predict.shape[1]== self._x_train.shape[1] """ 待預測數據和訓練數據的列(特征個數)必須相同 """ 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] """ x表示一行數據,即一個數組,那么它的特征數據個數,必須和訓練數據相同 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 ] |
4、新建test.py文件,引入knnclassifier對象。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
|
from knn.py import knnclassifier raw_data_x = [[ 3.393 , 2.331 ], [ 3.110 , 1.781 ], [ 1.343 , 3.368 ], [ 3.582 , 4.679 ], [ 2.280 , 2.866 ], [ 7.423 , 4.696 ], [ 5.745 , 3.533 ], [ 9.172 , 2.511 ], [ 7.792 , 3.424 ], [ 7.939 , 0.791 ]] raw_data_y = [ 0 , 0 , 0 , 0 , 0 , 1 , 1 , 1 , 1 , 1 ] x_train = np.array(raw_data_x) y_train = np.array(raw_data_y) x = np.array([ 9.880 , 3.555 ]) # 要將x這個矩陣轉換成2維的矩陣,一行兩列的矩陣 x_predict = x.reshape( 1 , - 1 ) """1,創建一個對象,設置k的值為6""" knn_clf = knnclassifier( 6 ) """2,將訓練數據和訓練標簽融合""" knn_clf.fit(x_train,y_train) """3,經過2才能跳到這里,傳入待預測的數據""" y_predict = knn_clf.predict(x_predict) print (y_predict) |
希望本文所述對大家python程序設計有所幫助。
原文鏈接:https://blog.csdn.net/qq_33531400/article/details/83036380