通过KNN查找离样本最近的邻居

通过KNN查找离样本最近的邻居

# 寻找离样本最近的邻居
from sklearn import datasets
from sklearn.neighbors import NearestNeighbors
from sklearn.preprocessing import StandardScaler
# 加载数据
iris = datasets.load_iris()
features = iris.data
# 标准化数据
standardizer = StandardScaler()
# features  特征标准化
features_standardized = standardizer.fit_transform(features)
​
nearest_neighbors = NearestNeighbors(n_neighbors=2).fit(features_standardized)
#nearest_neighbors_euclidian = NearestNeighbors(n_neighbors=2, metric='euclidian').fit(features_standardized)
# 创建测试数据
new_observation = [1, 1, 1, 1]# 获取最近两个点的索引,距离
distances, indices = nearest_neighbors.kneighbors([new_observation])# features_standardized[indices]  距离最近的两个值
indices
# 距离
distances
features_standardized[indices] 
array([[[1.03800476, 0.55861082, 1.10378283, 1.18556721],
        [0.79566902, 0.32841405, 0.76275827, 1.05393502]]])
# metric  设定距离指标
nearestneighbors_euclidean = NearestNeighbors(
    n_neighbors=2, metric='euclidean').fit(features_standardized)
# 查看距离
distances
array([[0.49140089, 0.74294782]])
# 寻找最近的3个点
nearestneighbors_euclidean = NearestNeighbors(
n_neighbors=3, metric="euclidean").fit(features_standardized)
​
nearestneighbors_euclidean
# kneighbors_graph  创建一个矩阵,表示离每个观察值最近的点
# 包含每个观察值和离他最近的3个邻居
nearest_neighbors_with_self = nearestneighbors_euclidean.kneighbors_graph(
    features_standardized).toarray()# type(nearest_neighbors_with_self)
​
nearest_neighbors_with_self
list(enumerate(nearest_neighbors_with_self))
# 从最近邻居的列表移自己
for i, x in enumerate(nearest_neighbors_with_self):
    x[i] = 0
​
nearest_neighbors_with_self
# 查看里第一个样本最近的两个邻居
nearest_neighbors_with_self[0]
array([0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,
       1., 0., 0., 0., 0., 0., 0., 0., 0., 0., 1., 0., 0., 0., 0., 0., 0.,
       0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,
       0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,
       0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,
       0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,
       0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,
       0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,
       0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.])

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值