Python ValueError:形状不匹配:对象不能广播到单个形状

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16950074/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 00:04:14  来源:igfitidea点击:

ValueError: shape mismatch: objects cannot be broadcast to a single shape

pythonvalueerrorpearson

提问by Alex Brashear

I am using the SciPy's pearsonr(x,y)method and I cannot figure out why the following error is happening:

我正在使用 SciPy 的pearsonr(x,y)方法,但我无法弄清楚为什么会发生以下错误:

ValueError: shape mismatch: objects cannot be broadcast to a single shape

ValueError:形状不匹配:对象不能广播到单个形状

It computes the first two (I am running several thousand of these tests in a loop) and then dies. Does anyone have any ideas about what the problem might be?

它计算前两个(我在一个循环中运行数千个这样的测试)然后死亡。有没有人对可能出现的问题有任何想法?

r_num = n*(np.add.reduce(xm*ym))

this is the line in the pearsonr method that the error occurs on, any help would be much appreciated.

这是发生错误的 pearsonr 方法中的行,任何帮助将不胜感激。

采纳答案by AMacK

This particular error implies that one of the variables being used in the arithmetic on the line has a shape incompatible with another on the same line (i.e., both different and non-scalar). Since nand the output of np.add.reduce()are both scalars, this implies that the problem lies with xmand ym, the two of which are simply your xand yinputs minus their respective means.

这个特定的错误意味着在线算术中使用的一个变量的形状与同一行上的另一个变量不兼容(即,不同的和非标量的)。由于n和 的输出np.add.reduce()都是标量,这意味着问题出在xm和 上ym,这两个只是您的xy输入减去各自的平均值。

Based on this, my guess is that your xand yinputs have different shapes from one another, making them incompatible for element-wise multiplication.

基于此,我的猜测是您的xy输入的形状彼此不同,使它们与元素乘法不兼容。

** Technically, it's not that variables on the same line have incompatible shapes. The only problem is when two variables being added, multiplied, etc., have incompatible shapes, whether the variables are temporary (e.g., function output) or not. Two variables with different shapes on the same line are fine as long as something else corrects the issue before the mathematical expression is evaluated.

** 从技术上讲,并不是同一行上的变量具有不兼容的形状。唯一的问题是当两个变量相加、相乘等具有不兼容的形状时,无论变量是否是临时的(例如,函数输出)。在同一条线上具有不同形状的两个变量是可以的,只要在计算数学表达式之前有其他东西可以纠正问题。