numpy矩阵减法混淆 [英] Numpy Matrix Subtraction Confusion

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

问题描述

我对用两个numpy矩阵意外执行的操作的结果有疑问(后来修复了).

I have a question about the result of an operation I accidentally performed with two numpy matrices (and later fixed).

假设我有一个列向量A = [1,2,3],而行向量B = [1,1,1].据我所知,没有正确的数学方法来减去"这两个向量,即这应该是一个未定义的运算.但是,当我这样做时,我会回来:

Let's say that I have a column vector, A = [1,2,3], and a row vector B = [1,1,1]. As far as I know there is no correct mathematical way to "subtract" these two vectors, i.e. this should be an undefined operation. And yet, when I do so, I get back:

>>> matrix([[0, 1, 2],
            [0, 1, 2],
            [0, 1, 2]])

我以为这可能是某种广播操作,但这仍然让我有些困扰. numpy.matrix对象不应该仅包含数学上有效的矩阵运算吗?

I thought that this might be some sort of broadcasting operation, but this still troubles me a bit. Shouldn't numpy.matrix objects only contain mathematically valid matrix operations?

感谢您的帮助!

谢谢!

推荐答案

A和B一起广播:

A = np.matrix([[1],[2],[3]])
#a 3x1 vector
#1
#2
#3

B = np.matrix([[1,1,1]])
#a 1x3 vector
#1 1 1

A-B
#a 3x3 vector
#0 0 0
#1 1 1
#2 2 2

A沿其尺寸1维(列)广播到

A gets broadcasted along its size 1 dimension(columns) into

#1 1 1
#2 2 2
#3 3 3

B沿其尺寸1维度(行)广播到

B get broadcasted along its size 1 dimension(rows) into

#1 1 1
#1 1 1
#1 1 1

然后像往常一样为两个3x3矩阵计算A-B.

Then A-B is computed as usual for two 3x3 matrices.

如果您想知道为什么这样做而不是报告错误,那是因为np.matrix继承自np.array. np.matrix会覆盖乘法,但不会覆盖加法和减法,因此它使用基于np.array的操作,该操作会在尺寸允许的情况下广播.

If you want to know why it does this instead of reporting an error it's because np.matrix inherits from np.array. np.matrix overrides multiplication, but not addition and subtraction, so it uses the operations based on the np.array, which broadcasts when the dimensions allow it.

这篇关于numpy矩阵减法混淆的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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