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

2024-06-02 08:47:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我为一个自制的knn分类器创建了一个函数,用于查找点的最近邻点

我做了以下工作:

  1. 定义了一个函数euclid_dist(x,y),用于查找二维平面上两点之间的距离
  2. 定义了一个函数nearest_neigh(p, points, k=3),用于在列表point中查找距离点p最近的k

查找邻居的功能:

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

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

预期输出:

函数返回k最近邻

我希望我没有把这个问题复杂化。

Tags: 函数距离return定义distnppointspoint
2条回答

正如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))

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

相关问题 更多 >