numpy通过向量减去矩阵的每一行 [英] numpy subtract every row of matrix by vector

查看:1095
本文介绍了numpy通过向量减去矩阵的每一行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

我目前有一个 for 循环,该循环迭代并减去矢量在矩阵中的第 i 行. 是否可以通过矢量简单地减去整个矩阵?

谢谢!

当前代码:

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

这是 X1 是矩阵的 i 行,而 X2 是矢量的地方.我可以做到这一点,这样就不需要 for 循环了吗?

This is where X1 is the matrix's i-th row and X2 is vector. Can I make it so that I don't need a for loop?

推荐答案

这在numpy中有效,但仅当拖尾轴具有相同尺寸时才有效.这是从矩阵成功减去向量的示例:

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

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]])

之所以可行,是因为两者的尾轴都具有相同的尺寸(3).

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

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

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

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.

这篇关于numpy通过向量减去矩阵的每一行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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