KNN
# ==========k最近邻分类=========
import numpy as np # 快速操作结构数组的工具
from sklearn.neighbors import KNeighborsClassifier, KDTree # 导入knn分类器
# 数据集。4种属性,3种类别
data = [
[5.1, 3.5, 1.4, 0.2, 0],
[4.9, 3.0, 1.4, 0.2, 0],
[4.7, 3.2, 1.3, 0.2, 0],
[4.6, 3.1, 1.5, 0.2, 0],
[5.0, 3.6, 1.4, 0.2, 0],
[7.0, 3.2, 4.7, 1.4, 1],
[6.4, 3.2, 4.5, 1.5, 1],
[6.9, 3.1, 4.9, 1.5, 1],
[5.5, 2.3, 4.0, 1.3, 1],
[6.5, 2.8, 4.6, 1.5, 1],
[6.3, 3.3, 6.0, 2.5, 2],
[5.8, 2.7, 5.1, 1.9, 2],
[7.1, 3.0, 5.9, 2.1, 2],
[6.3, 2.9, 5.6, 1.8, 2],
[6.5, 3.0, 5.8, 2.2, 2],
]
# 构造数据集
dataMat = np.array(data)
X = dataMat[:, 0:4]
y = dataMat[:, 4]
knn = KNeighborsClassifier(n_neighbors=2,
weights='distance') # 初始化一个knn模型,设置k=2。weights='distance'样本权重等于距离的倒数。'uniform'为统一权重
knn.fit(X, y) # 根据样本集、结果集,对knn进行建模
result = knn.predict([[0, 10, 0, 10]]) # 使用knn对新对象进行预测
print(result)
posted on 2019-07-23 14:57 Indian_Mysore 阅读(110) 评论(0) 编辑 收藏 举报