【问题标题】:Code for extracting 2nd and 3rd neighbor when there is, and ignore when they dont exist存在时提取第二和第三邻居的代码,不存在时忽略
【发布时间】:2019-12-20 23:05:27
【问题描述】:

我正在尝试使用此代码提取第二个和第三个 K 最近邻。当它们存在时,我能够得到它们。当它们不存在时,我会收到如下错误:IndexError: index 3 is out of bounds for axis 0 with size 3.

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

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

df = pd.DataFrame({'time': updated_df['upd_time_code'], 'x': updated_df['x'], 'y': updated_df['y'], 'id': updated_df['id']})

#This has the index of the nearest neighbor in the group, as well as the distance

nns = df.drop('id', 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)
    print("processing group at: ", group.time)
    for j, tup in enumerate(zip(nn_set[0], nn_set[1])):
        nn_rows.append({'time': i,
                    'id': group.iloc[j]['id'],
                    'nearest_neighbour1': group.iloc[tup[1][1]]['id'],
                    'nearest_neighbour2': group.iloc[tup[1][2]]['id'],
                    'nearest_neighbour3': group.iloc[tup[1][3]]['id']
                    'euclidean_distance1': tup[0][1],
                    'euclidean_distance2': tup[0][2],
                    'euclidean_distance3': tup[0][2]})

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

我如何处理有时有邻居而有时没有的问题,可以通过调整此代码来忽略它吗?

【问题讨论】:

  • 放入try...except块并处理IndexError(EAFP)或检查数字,然后仅索引该值是否有效(LBYL)

标签: python error-handling cluster-analysis knn nearest-neighbor


【解决方案1】:

您正在访问 第四个最近的邻居。

这是您代码中需要修复的经典数组索引错误。

【讨论】:

  • 对不起,我不明白。你能给我一个提示,这在代码中到底发生在哪里以及如何解决它?
  • 因为长度为 3 的数组仅在位置 0、1 和 2 处具有值。
猜你喜欢
  • 2020-04-12
  • 2011-06-14
  • 2013-04-15
  • 2020-07-20
  • 1970-01-01
  • 1970-01-01
  • 2014-07-11
  • 2017-06-27
  • 2017-08-23
相关资源
最近更新 更多