You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

调用sklearn的euclidean_distances计算欧氏距离报2D数组错误如何解决

欧氏距离计算报错修复方案

报错原因

sklearn.metrics.pairwise.euclidean_distances要求输入的两个参数均为二维数组,你当前使用的middle_point维度为(4,)属于一维数组,因此触发参数校验报错。

修复方法

方法1:适配sklearn接口调整维度

按照报错提示,单个样本点使用reshape(1, -1)转换为二维数组即可:

from sklearn.metrics.pairwise import euclidean_distances
import numpy as np

# 转换middle_point为shape (1,4)的二维数组
center_distances = euclidean_distances(X, middle_point.reshape(1, -1))
# 输出默认是shape (150,1)的二维数组,如果需要一维结果可调用flatten()
center_distances = center_distances.flatten()

方法2:直接用Numpy广播计算(更简便)

不需要引入sklearn接口,直接利用Numpy的广播机制计算,无需主动调整维度,得到的结果直接是每个样本到中心点的距离一维数组:

import numpy as np

center_distances = np.sqrt(np.sum((X - middle_point) ** 2, axis=1))

内容的提问来源于stack exchange,提问作者Joseph_

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 05:45:03