sklearn K邻近

sklearn.neighbors.KNeighborsClassifier

官方:link
例子:

import numpy as np
from sklearn.neighbors import KNeighborsClassifier
from matplotlib import pyplot as plt

X = np.random.randint(0, 6, (20, 2))
y = np.random.randint(0, 2, (20,))

knn = KNeighborsClassifier(n_neighbors=1)
knn.fit(X, y)

x_new = np.array([3, 3])
y_pre = knn.predict(x_new[np.newaxis, :])
labels = ['class 1', 'class 2']
colors = 'rb'
n_class = 2
for i, color in zip(range(n_class), colors):
    idx = np.where(y == i)
    plt.scatter(X[idx, 0], X[idx, 1], c=color, label=labels[i])
plt.legend()
plt.scatter(3, 3, c=colors[y_pre[0]], edgecolors='y', s=100)

print(y_pre)
plt.show()

在这里插入图片描述
例子二:

from sklearn.neighbors import KNeighborsClassifier
from sklearn.datasets import make_classification
import numpy as np
from matplotlib import pyplot as plt
from matplotlib.colors import ListedColormap

X, y = make_classification(n_samples=1000, n_features=2, n_classes=4, n_redundant=0, n_clusters_per_class=1)
knn = KNeighborsClassifier(n_neighbors=5)
# 画散点图
ax = plt.gca()

knn.fit(X, y)
# 画出决策边界
x1_min, x1_max = X[:, 0].min(), X[:, 0].max() + 1
x2_min, x2_max = X[:, 1].min(), X[:, 1].max() + 1
xx, yy = np.meshgrid(np.arange(x1_min, x1_max, 0.1), np.arange(x2_min, x2_max, 0.1))
cmap_light = ListedColormap(['#FFAAAA', '#AAFFAA', '#AAAAFF','#FFAAFF'])
cmap_bold = ListedColormap(['#FF0000', '#00FF00', '#0000FF','#FF00FF'])
# 预测网格数据
y_pre = knn.predict(np.c_[xx.ravel(), yy.ravel()])
y_pre = y_pre.reshape(xx.shape)
plt.contourf(xx, yy, y_pre, cmap=cmap_light)
colors = 'rgby'
ax.scatter(X[:, 0], X[:, 1], c=y, cmap=cmap_bold, s=10, edgecolor='black')
plt.show()

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值