[英]Why does numpy.copy of a numpy.matrix not act like the original matrix? Multiplication with the transpose of that copy does not work
我需要处理函数内的矩阵副本。 但是 (nx 1) 矩阵(向量)的副本不表现得像它应该的那样。
这里我举了一个例子:
x 乘以 y 的转置给了我一个正常的向量乘法,结果是一个 (1x1) 矩阵。
x 和 y 的副本 a 和 b 不会这样做。 他们返回一个维度为 (nxn) 的数组。 我在这里做错了什么? 我怎么能避免这种情况?
>>>import numpy as np
>>>x=np.matrix('1;2;3')
>>>y=np.matrix('1;1;-1')
>>>x.T*y
matrix([[0]])
>>>a=np.copy(x)
>>>b=np.copy(y)
>>>a.T*b
array([[ 1, 2, 3],
[ 1, 2, 3],
[-1, -2, -3]])
您的原始数组是子类matrix
。 副本是基本array
类。 使用x.copy()
,特定于矩阵类的复制方法来创建另一个矩阵。 然后矩阵乘法运算将像以前一样工作。
In [52]: x=np.matrix('1;3;3')
In [53]: x
Out[53]:
matrix([[1],
[3],
[3]])
In [54]: np.copy(x)
Out[54]:
array([[1],
[3],
[3]])
In [55]: x.copy()
Out[55]:
matrix([[1],
[3],
[3]])
另一个答案中提出的解决方案是将matrix
乘法替换为np.array
( np.dot
) 的等效乘法。
如果要复制,然后而是采用了矩阵, numpy.copy
,使用copy
的方法matrix
。
>>> x = np.matrix('1;3;3')
>>> x.copy()
matrix([[1],
[3],
[3]])
另一种选择是使用numpy.array(x, copy=True, subok=True)
。
请注意, numpy.copy
只是numpy.array(x, copy=True)
的别名,这会导致输入的向下转换。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.