查找最近的邻居=,TypeError:只能将整数标量数组转换为标量索引

问题描述 投票:0回答:2

我创建了一个函数,以查找自制knn分类器的点附近。

我做了以下事情:

  1. [定义函数euclid_dist(x,y)以查找二维平面上两点之间的距离。
  2. 定义了函数nearest_neigh(p, points, k=3),以查找列表k中最接近点ppoint

寻找邻居的功能:

def neares_neigh(p, points, k=3):
    """Return the nearest neighbour of a point"""
    distances = []
    for point in points:
        dist = euclid_dist(p, point)
        distances.append(dist)

    distances = np.array(distances)
    ind = np.argsort(distances)
    return points[ind[0:k]]

[最后一行return points[ind[0:k]]返回错误:TypeError: only integer scalar arrays can be converted to a scalar index

我在ind中对points数组进行了切片,以返回k最近的邻居。

预期输出:

该函数返回k最近的邻居。

我希望我不会使这个问题过于复杂。
python python-3.x numpy knn numpy-slicing
2个回答
0
投票

我很确定会发生这种情况,因为points是列表而不是numpy array。列表不支持这种索引。将points强制转换为数组应该可以解决问题。


0
投票

Ralvi提到的问题是,因为points很可能是Python列表,而不是numpy数组。以下代码不会产生错误:

import numpy as np
import math
from random import randint


def euclidean_distance(point1, point2):
    return math.sqrt(sum(math.pow(a - b, 2) for a, b in zip(point1, point2)))


def nearest_neighbor(p, points, k=3):
    """Return the nearest neighbour of a point"""
    distances = []
    for point in points:
        dist = euclidean_distance(p, point)
        distances.append(dist)

    distances = np.array(distances)
    ind = np.argsort(distances)

    print(p)
    return points[ind[0:k]]

# generate an array of random points
points = 0 + np.random.rand(100, 2) * 50

print(nearest_neighbor(points[randint(0, len(points))], points, k=3))
© www.soinside.com 2019 - 2024. All rights reserved.