python - 寻找最近邻=,TypeError:只有整数标量数组可以转换为标量索引
问题描述
我做了一个函数来为自制的 knn 分类器找到一个点的最近邻居。
我做了以下事情:
- 定义了一个函数
euclid_dist(x,y)
来查找二维平面上两点之间的距离。 - 定义了一个函数来在列表
nearest_neigh(p, points, k=3)
中找到k
离该点最近的点。p
point
寻找邻居的功能:
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
最近的邻居。
解决方案
我很确定会发生这种情况,因为points
它是一个列表而不是一个numpy array
. 列表不支持这种索引。转换points
为数组应该可以解决问题。
推荐阅读
- ruby-on-rails - 如何修复未捕获的错误:无法使用来自另一个模块或领域的 e“__Schema”
- c# - WPF:用户干预后获取滑块值
- javascript - 响应 Post 请求时出现 400 错误
- javascript - 按 ID 比较 2 个不同的数组并计算差异
- javascript - 如何从特定 x 和 y 位置的数组中返回一个数字?
- javascript - 在 v-for (select) 中访问嵌套索引
- sql - 如何根据条件获取列名
- javascript - 自定义光标的交错移动和另一个问题
- python - 在 foo 循环中为数据集创建新列 - Pandas Python
- javascript - 如何使用复选框减少数值?