用广播减去numpy中每一行的平均值 [英] subtracting the mean of each row in numpy with broadcasting

查看:111
本文介绍了用广播减去numpy中每一行的平均值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试使用广播减去numpy中矩阵的每一行的平均值,但出现错误.知道为什么吗?

I try to subtract the mean of each row of a matrix in numpy using broadcasting but I get an error. Any idea why?

这是代码:

from numpy import *
X = random.rand(5, 10)
Y = X - X.mean(axis = 1)

错误:

ValueError: operands could not be broadcast together with shapes (5,10) (5,) 

谢谢!

推荐答案

mean方法是 reduction 操作,这意味着它将一维数字集转换为单个数字.当您沿轴对n维数组应用归约时,numpy将该维折叠为归约值,从而生成(n-1)维数组.在您的情况下,由于X具有形状(5,10),并且沿轴1进行了归约,因此最终得到形状为(5,)的数组:

The mean method is a reduction operation, meaning it converts a 1-d collection of numbers to a single number. When you apply a reduction to an n-dimensional array along an axis, numpy collapses that dimension to the reduced value, resulting in an (n-1)-dimensional array. In your case, since X has shape (5, 10), and you performed a reduction along axis 1, you end up with an array with shape (5,):

In [8]: m = X.mean(axis=1)

In [9]: m.shape
Out[9]: (5,)

当您尝试从X减去此结果时,您试图从形状为(5,10)的数组中减去形状为(5,)的数组.这些形状与广播不兼容. (请参阅《用户指南》中的广播说明 )

When you try to subtract this result from X, you are trying to subtract an array with shape (5,) from an array with shape (5, 10). These shapes are not compatible for broadcasting. (Take a look at the description of broadcasting in the User Guide.)

为使广播按您希望的方式工作,mean操作的结果应为形状为(5,1)的数组(与形状(5,10)兼容).在最新版本的numpy中,约简操作(包括mean)具有名为keepdims的参数,该参数告诉函数不要折叠缩减的维.而是保留长度为1的平凡尺寸:

For broadcasting to work the way you want, the result of the mean operation should be an array with shape (5, 1) (to be compatible with the shape (5, 10)). In recent versions of numpy, the reduction operations, including mean, have an argument called keepdims that tells the function to not collapse the reduced dimension. Instead, a trivial dimension with length 1 is kept:

In [10]: m = X.mean(axis=1, keepdims=True)

In [11]: m.shape
Out[11]: (5, 1)

对于较旧版本的numpy,您可以使用reshape还原折叠后的尺寸:

With older versions of numpy, you can use reshape to restore the collapsed dimension:

In [12]: m = X.mean(axis=1).reshape(-1, 1)

In [13]: m.shape
Out[13]: (5, 1)

因此,根据您的numpy版本,您可以执行以下操作:

So, depending on your version of numpy, you can do this:

Y = X - X.mean(axis=1, keepdims=True)

或者这个:

Y = X - X.mean(axis=1).reshape(-1, 1)

这篇关于用广播减去numpy中每一行的平均值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆