本文实例讲述了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