gpt4 book ai didi

python - 值错误: operands could not be broadcast together with shapes (3,)(6,)

转载 作者:太空宇宙 更新时间:2023-11-03 15:00:51 24 4
gpt4 key购买 nike

我正在尝试计算以下内容,但当数组大小不相似时会出现错误。我知道我可以针对不同大小的数组手动执行此操作,但是您能帮我更正此代码吗?

import scipy
from scipy.stats import pearsonr, spearmanr
from scipy.spatial import distance
x = [5,3,2.5]
y = [4,3,2,4,3.5,4]
pearsonr(x,y)
:Error
scipy.spatial.distance.euclidean(x, y)
:Error
spearmanr(x,y)
:Error
scipy.spatial.distance.jaccard(x, y)
:Error

最佳答案

对于距离,数组必须为 2 维,即使每个子数组仅包含一个元素,例如:

def make2d(lst):
return [[i] for i in lst]

>>> scipy.spatial.distance.cdist(make2d([5,3,2.5]), make2d([4,3,2,4,3.5,4]))
array([[ 1. , 2. , 3. , 1. , 1.5, 1. ],
[ 1. , 0. , 1. , 1. , 0.5, 1. ],
[ 1.5, 0.5, 0.5, 1.5, 1. , 1.5]])

您可以选择不同的指标(例如jaccard):

>>> scipy.spatial.distance.cdist(make2d([5,3,2.5]), make2d([4,3,2,4,3.5,4]), metric='jaccard')
array([[ 1., 1., 1., 1., 1., 1.],
[ 1., 0., 1., 1., 1., 1.],
[ 1., 1., 1., 1., 1., 1.]])

但是对于统计函数,我不知道你希望它如何工作,根据定义,这些排序需要相同长度的数组。您可能需要查阅这些文档。

关于python - 值错误: operands could not be broadcast together with shapes (3,)(6,),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45133770/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com