【问题标题】:ValueError: operands could not be broadcast together with shapes (3,) (6,)ValueError: 操作数不能与形状 (3,) (6,) 一起广播
【发布时间】:2017-07-16 22:18:43
【问题描述】:

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

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

【问题讨论】:

  • 在这些情况下,xy 是什么?
  • x = [5,3,2.5] y = [4,3,2,4,3.5,4]

标签: python arrays numpy scipy


【解决方案1】:

对于距离,数组必须为 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.]])

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-11
    相关资源
    最近更新 更多