KNeighborsClassifier():
'''
KNeighborsClassifier(n_neighbors=5, weights='uniform',
algorithm='auto', leaf_size=30,
p=2, metric='minkowski',
metric_params=None, n_jobs=1, **kwargs)
n_neighbors: 默认值为5,表示查询k个最近邻的数目
algorithm: {‘auto’, ‘ball_tree’, ‘kd_tree’, ‘brute’},指定用于计算最近邻的算法,auto表示试图采用最适合的算法计算最近邻
leaf_size: 传递给‘ball_tree’或‘kd_tree’的叶子大小
metric: 用于树的距离度量。默认'minkowski与P = 2(即欧氏度量)
n_jobs: 并行工作的数量,如果设为-1,则作业的数量被设置为CPU内核的数量
查看官方api:http://scikit-learn.org/dev/modules/generated/sklearn.neighbors.KNeighborsClassifier.html#sklearn.neighbors.KNeighborsClassifier
'''
示例:
# -*- coding: utf-8 -*-
"""
Created on Fri Feb 15 18:01:45 2019
@author: Administrator
"""
import numpy as np
from sklearn import neighbors
import warnings
warnings.filterwarnings('ignore') # warning信息不打印,可有可无
knn = neighbors.KNeighborsClassifier() # 取得knn分类器
data = np.array([[1, 1, 1, 1],
[0.5, 1, 1, 1],
[0.1, 0.1, 0.1, 0.1],
[0.5, 0.5, 0.5, 0.5],
[1, 0.8, 0.3, 1],
[0.6, 0.5, 0.7, 0.5],
[1, 1, 0.9, 0.5],
[1, 0.6, 0.5, 0.8],
[0.5, 0.5, 1, 1],
[0.9, 1, 1, 1],
[0.6, 0.6, 1, 0.1],
[1, 0.8, 0.5, 0.5],
[1, 0.1, 0.1, 1],
[1, 1, 0.7, 0.3],
[0.2, 0.3, 0.4, 0.5],
[0.5, 1, 0.6, 0.6]
])
labels = np.array(['美女',
'淑女',
'丑女',
'一般型',
'淑女',
'一般型',
'美女',
'一般型',
'淑女',
'美女',
'丑女',
'可爱型',
'可爱型',
'淑女',
'丑女',
'可爱型'
])
knn.fit(data, labels) # 导入数据进行训练
print('预测类型为:', knn.predict([[0.8, 1, 1, 1]]))
结果: