繁体   English   中英

列向量乘法 ValueError 中的错误:matmul:输入操作数 1 在其核心维度 0 中不匹配

[英]Error in colmn vector multiplication ValueError: matmul: Input operand 1 has a mismatch in its core dimension 0

我想通过以下方式将 5x1 矩阵与 1x1 矩阵相乘。 每次它都给出以下错误

ValueError: matmul: Input operand 1 has a mismatch in its core dimension 0, with gufunc signature (n?,k),(k,m?)->(n?,m?)

这是我正在尝试的方式。 请帮我调试这里的具体实例

>>> m = np.ones(5)
>>> x = np.ones(1)
>>> m.shape
(5,)
>>> x.shape
(1,)
>>> m@x
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: matmul: Input operand 1 has a mismatch in its core dimension 0, with gufunc signature (n?,k),(k,m?)->(n?,m?) (size 1 is different from 5)
>>> m.transpose()@x
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: matmul: Input operand 1 has a mismatch in its core dimension 0, with gufunc signature (n?,k),(k,m?)->(n?,m?) (size 1 is different from 5)

您的数组m不是 5 x 1 形状。 它就像一行一行。

左操作数的列数应与右操作数的行数匹配。 因此,当您执行m @ x时,根据矩阵乘法规则,它是无效的。

所以这样做:

>>> m.reshape(-1, 1) @ x

它使行向量m用作具有形状 (5, 1) 的列向量。 x 也有一行,因此是有效的矩阵乘法。

您有 2 个 1d arrays,打印的形状是 (5,) 和 (1,)。 这些不是column vectorsrow vectors

matmul文档对它如何处理 1d arrays 的描述可能有点令人困惑。 我更喜欢np.dot文档。 它将两个一维 arrays 视为矢量点/内积。 在任何一种情况下,arrays 都具有匹配的大小。

一些有效的形状组合:

In [90]: np.ones((5,1))@np.ones((1,1))                                                  
Out[90]: 
array([[1.],
       [1.],
       [1.],
       [1.],
       [1.]])
In [91]: _.shape                                                                        
Out[91]: (5, 1)

In [92]: np.ones((5,1))@np.ones((1))                                                    
Out[92]: array([1., 1., 1., 1., 1.])
In [93]: _.shape                                                                        
Out[93]: (5,)

In [95]: np.ones((1,5))@np.ones((5))                                                    
Out[95]: array([5.])
In [96]: _.shape                                                                        
Out[96]: (1,)

In [97]: np.ones((1,5))@np.ones((5,1))                                                  
Out[97]: array([[5.]])
In [98]: _.shape                                                                        
Out[98]: (1, 1)

对于 2d(及更高)arrays,A 的最后一个暗淡必须与 B 的第二个到最后一个相匹配。这是经典的手动扫描行和列规则。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM