机器学习入门KNN近邻算法(一) (2)

KNN近邻机器学习案例2

from sklearn.neighbors import KNeighborsClassifier import numpy as np #knn对象 neigh = KNeighborsClassifier(n_neighbors=3) #身高、体重、鞋的尺寸 X = np.array([[181,80,44],[177,70,43],[160,60,38],[154,54,37], [166,65,40],[190,90,47],[175,64,39],[177,70,40], [159,55,37],[171,75,42],[181,85,43]]) display(X) y = ['male','male','female','female','male','male','female','female','female','male','male'] # 第1步:训练数据 neigh.fit(X,y) # 第2步:预测数据 Z = neigh.predict(np.array([[190,70,43],[168,55,37]])) display(Z) #array(['male', 'female'], dtype='<U6') 识别出对应的性格

4 KNN用于分类

用于分类的numpy方法介绍

np.meshgrid 从坐标向量返回坐标矩阵

import numpy as np nx, ny = 3, 4 x = np.linspace(0, 1, nx) y = np.linspace(0, 1, ny) xv, yv = np.meshgrid(x, y) display(x,y,xv,yv)

输出:
array([ 0. , 0.5, 1. ])
array([ 0. , 0.33333333, 0.66666667, 1. ])
array([[ 0. , 0.5, 1. ],

[ 0. , 0.5, 1. ], [ 0. , 0.5, 1. ], [ 0. , 0.5, 1. ]])

array([[ 0. , 0. , 0. ],
[ 0.33333333, 0.33333333, 0.33333333],
[ 0.66666667, 0.66666667, 0.66666667],
[ 1. , 1. , 1. ]])
```

np.ravel 返回一个连续的平坦矩阵

x = np.array([[1, 2, 3], [4, 5, 6]]) display(x,x.ravel()) #输出: array([[1, 2, 3], [4, 5, 6]]) array([1, 2, 3, 4, 5, 6])

np.c_ 将切片对象按第二轴转换为串联

np.c_[np.array([1,2,3]), np.array([4,5,6])] #输出: array([[1, 4], [2, 5], [3, 6]])

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/zyyjwd.html