gpt4 book ai didi

numpy - numpy.dot 函数如何工作?

转载 作者:行者123 更新时间:2023-12-01 13:35:45 24 4
gpt4 key购买 nike

import numpy as np
a = np.array([[1,2],[3,4]])
b = np.array([5, 6])
a.dot(b)
b.dot(a)

a.dot(b)b.dot(a) 会怎样?对于矩阵乘法,a.dot(b) 应该是非法的。

最佳答案

在此设置中,b.dot(a) 等同于 b.T.dot(a);事实上,bb.T 恰好具有相同的形状,所以尽管符号使它看起来像 b 是一个行向量,但它实际上不是。但是,我们可以将其重新定义为明确地表现为行向量,在这种情况下操作会按预期失败:

In [25]: b.dot(a)
Out[25]: array([23, 34])

In [26]: b.T.dot(a)
Out[26]: array([23, 34])

In [30]: b.shape
Out[30]: (2,)

In [31]: b.T.shape
Out[31]: (2,)

In [27]: c = b.reshape((1, 2))

In [28]: c.dot(a)
Out[28]: array([[23, 34]])

In [29]: a.dot(c)
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-29-5d91888f8066> in <module>()
----> 1 a.dot(c)

ValueError: shapes (2,2) and (1,2) not aligned: 2 (dim 1) != 1 (dim 0)

关于numpy - numpy.dot 函数如何工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43451249/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com