python静默转置1级数组

问题描述 投票:-1回答:1
import numpy as np
x1 = np.arange(9.0).reshape((3, 3))
print("x1\n",x1,"\n")
x2 = np.arange(3.0)
print("x2\n",x2)
print(x2.shape,"\n")
print("Here, the shape of x2 is 3 rows by 1 column ")
print("x1@x2\n",x1@x2)
print("")
print("x2@x1  should not be possible\n",x2@x1,"\n"*3)

给予

x1
 [[0. 1. 2.]
 [3. 4. 5.]
 [6. 7. 8.]] 

x2
 [0. 1. 2.]
(3,) 

Here, the shape of x2 is 3 rows by 1 column 
x1@x2 =
 [ 5. 14. 23.]

x2@x1  should not be possible, BUT
 [15. 18. 21.] 

Python3似乎将x2静默转换为(1,3)数组,因此可以乘以x1。还是我缺少一些语法?

python arrays matrix-multiplication
1个回答
0
投票

数组被Numpy设为broadcasted

引用广播文档:

广播一词描述了numpy如何对待具有不同算术运算期间的形状。受某些限制,较小的阵列在较大的阵列上“广播”,因此它们具有兼容的形状。广播提供了一种矢量化方法数组操作,以便在C而不是Python中进行循环。它这样做无需复制不必要的数据,通常会导致高效的算法实现。但是,在某些情况下广播是一个坏主意,因为它会导致无效使用降低计算速度的内存。

将以下行添加到您的代码中,在该代码中您将x2的形状显式设置为(3,1),并且会出现如下错误:

import numpy as np
x1 = np.arange(9.0).reshape((3, 3))
print(x1.shape) # new line added
print("x1\n",x1,"\n")
x2 = np.arange(3.0)
x2 = x2.reshape(3, 1) # new line added
print("x2\n",x2)
print(x2.shape,"\n")
print("Here, the shape of x2 is 3 rows by 1 column ")
print("x1@x2\n",x1@x2)
print("")
print("x2@x1  should not be possible\n",x2@x1,"\n"*3)

输出

(3, 3)
x1
 [[0. 1. 2.]
 [3. 4. 5.]
 [6. 7. 8.]] 

x2
 [[0.]
 [1.]
 [2.]]
(3, 1) 

Here, the shape of x2 is 3 rows by 1 column 
x1@x2
 [[ 5.]
 [14.]
 [23.]]

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-12-c61849986c5c> in <module>
     12 print("x1@x2\n",x1@x2)
     13 print("")
---> 14 print("x2@x1  should not be possible\n",x2@x1,"\n"*3)

ValueError: matmul: Input operand 1 has a mismatch in its core dimension 0, with gufunc signature (n?,k),(k,m?)->(n?,m?) (size 3 is different from 1)
© www.soinside.com 2019 - 2024. All rights reserved.