Python numpy 用向量减去矩阵的每一行

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26333005/
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:22:18  来源:igfitidea点击:

numpy subtract every row of matrix by vector

pythonnumpymatrix

提问by thehandyman

So I have a n x dmatrix and an n x 1vector. I'm trying to write a code to subtract every row in the matrix by the vector.

所以我有一个n x d矩阵和一个n x 1向量。我正在尝试编写一个代码,用向量减去矩阵中的每一行。

I currently have a forloop that iterates through and subtracts the i-th row in the matrix by the vector. Is there a way to simply subtract an entire matrix by the vector?

我目前有一个for循环,它迭代并i通过向量减去矩阵中的第 -th 行。有没有办法简单地用向量减去整个矩阵?

Thanks!

谢谢!

Current code:

当前代码:

for i in xrange( len( X1 ) ):
    X[i,:] = X1[i,:] - X2

This is where X1is the matrix's i-th row and X2is vector. Can I make it so that I don't need a forloop?

这是X1矩阵的i第 -th 行并且X2是向量。我可以让它不需要for循环吗?

采纳答案by John1024

That works in numpybut only if the trailing axes have the same dimension. Here is an example of successfully subtracting a vector from a matrix:

这适用于numpy仅当尾随轴具有相同的维度时。下面是一个从矩阵中成功减去向量的例子:

In [27]: print m; m.shape
[[ 0  1  2]
 [ 3  4  5]
 [ 6  7  8]
 [ 9 10 11]]
Out[27]: (4, 3)

In [28]: print v; v.shape
[0 1 2]
Out[28]: (3,)

In [29]: m  - v
Out[29]: 
array([[0, 0, 0],
       [3, 3, 3],
       [6, 6, 6],
       [9, 9, 9]])

This worked because the trailing axis of both had the same dimension (3).

这是有效的,因为两者的尾随轴具有相同的尺寸 (3)。

In your case, the leading axes had the same dimension. Here is an example, using the same vas above, of how that can be fixed:

在您的情况下,引导轴具有相同的尺寸。这是一个使用与v上述相同的示例,说明如何解决此问题:

In [35]: print m; m.shape
[[ 0  1  2  3]
 [ 4  5  6  7]
 [ 8  9 10 11]]
Out[35]: (3, 4)

In [36]: (m.transpose() - v).transpose()
Out[36]: 
array([[0, 1, 2, 3],
       [3, 4, 5, 6],
       [6, 7, 8, 9]])

The rules for broadcasting axes are explained in depth here.

此处对广播轴的规则进行了深入解释。

回答by Nagasaki45

In addition to @John1024 answer, "transposing" a one-dimensional vector in numpy can be done like this:

除了@John1024 的回答,在 numpy 中“转置”一个一维向量可以这样完成:

In [1]: v = np.arange(3)

In [2]: v
Out[2]: array([0, 1, 2])

In [3]: v = v[:, np.newaxis]

In [4]: v
Out[4]:
array([[0],
       [1],
       [2]])

From here, subtracting vfrom every column of mis trivial using broadcasting:

从这里开始,使用广播v从每一列中减去m是微不足道的:

In [5]: print(m)
[[ 0  1  2  3]
 [ 4  5  6  7]
 [ 8  9 10 11]]

In [6]: m - v
Out[6]:
array([[0, 1, 2, 3],
       [3, 4, 5, 6],
       [6, 7, 8, 9]])