【问题标题】:How to adjust this code to also Return second and third "Nearest Neighbors"?如何调整此代码以返回第二个和第三个“最近的邻居”?
【发布时间】:2020-04-12 11:08:30
【问题描述】:

根据calculating average distance of nearest neighbours in pandas dataframe 中的这段代码,我该如何调整它以便将第二个和第三个最近邻居返回到新列中?

(或者创建一个可调整的参数来定义返回多少个邻居):

示例代码:

import numpy as np 
from sklearn.neighbors import NearestNeighbors
import pandas as pd

def nn(x):
    nbrs = NearestNeighbors(
        n_neighbors=2, 
        algorithm='auto', 
        metric='euclidean'
    ).fit(x)
    distances, indices = nbrs.kneighbors(x)
    return distances, indices

time = [0, 0, 0, 1, 1, 2, 2]
x = [216, 218, 217, 280, 290, 130, 132]
y = [13, 12, 12, 110, 109, 3, 56] 
car = [1, 2, 3, 1, 3, 4, 5]
df = pd.DataFrame({'time': time, 'x': x, 'y': y, 'car': car})

#This has the index of the nearest neighbor in the group, as well as the distance
nns = df.drop('car', 1).groupby('time').apply(lambda x: nn(x.as_matrix()))

groups = df.groupby('time')
nn_rows = []
for i, nn_set in enumerate(nns):
    group = groups.get_group(i)
    for j, tup in enumerate(zip(nn_set[0], nn_set[1])):
        nn_rows.append({'time': i,
                    'car': group.iloc[j]['car'],
                    'nearest_neighbour': group.iloc[tup[1][1]]['car'],
                    'euclidean_distance': tup[0][1]})

nn_df = pd.DataFrame(nn_rows).set_index('time')

结果数据框:

>>> nn_df
time car euclidean_distance nearest_neighbour           
0    1   1.414214           3
0    2   1.000000           3
0    3   1.000000           2
1    1   10.049876          3
1    3   10.049876          1
2    4   53.037722          5
2    5   53.037722          4

如何获得最近邻 2 和 3 以及 N 的输出并将它们插入新列?

【问题讨论】:

    标签: python pandas knn nearest-neighbor euclidean-distance


    【解决方案1】:

    这是NearestNeighbors 方法的文档。

    我认为您的问题可以使用n_neighbors 参数解决。该参数指定要返回的最近邻数的indices and distances

    通常使用的值是2,当我们的目标是找到除了点本身之外的单个最近邻。最近的邻居总是它自己,因为距离为 0。

    要找到第二个和第三个最近的邻居,n_neighbors 应该设置为 4。这将返回点本身,然后是下一个 N-1 个最近的邻居

    # Argument
    n_neighbor = 4
    
    # Indices
    [point_itself, neighbor_1, neighbor_2, neighbor_3]
    
    # Distances
    [ 0, distance_1, distance_2, distance_3]
    

    【讨论】:

    • 非常感谢!但是我需要在“'nearest_neighbour': group.iloc[tup[1][1]]['car']” 附近的某处调整代码,以获得邻居 2 和 3 的值,不是吗?我该怎么做?
    • 是的,您必须从结果中索引邻居。这只是group.iloc[tup[1][nth_neighbor]]['car']。您还需要记住,可能的邻居数量取决于样本大小,即对于 n 的样本大小,您最多可以有 n 个邻居。
    猜你喜欢
    • 2019-06-05
    • 2013-04-15
    • 1970-01-01
    • 1970-01-01
    • 2018-02-11
    • 2013-09-12
    • 2022-11-30
    • 2016-04-15
    • 1970-01-01
    相关资源
    最近更新 更多