沿第三轴的点积 [英] Dot product along third axis
问题描述
我正在尝试使用 tensordot
在 numpy 中获取张量点积,但我不确定我应该如何重塑我的数组以实现我的计算.(总的来说,我对张量数学还是个新手.)
I'm trying to take a tensor dot product in numpy using tensordot
, but I'm not sure how I should reshape my arrays to achieve my computation. (I'm still new to the mathematics of tensors, in general.)
我有
arr = np.array([[[1, 1, 1],
[0, 0, 0],
[2, 2, 2]],
[[0, 0, 0],
[4, 4, 4],
[0, 0, 0]]])
w = [1, 1, 1]
我想沿 axis=2
取点积,这样我就有了矩阵
And I want to take a dot product along axis=2
, such that I have the matrix
array([[3, 0, 6],
[0, 12, 0]])
什么是正确的 numpy 语法?np.tensordot(arr, [1, 1, 1], axes=2)
似乎引发了 ValueError
.
What's the proper numpy syntax for this? np.tensordot(arr, [1, 1, 1], axes=2)
seems to raise a ValueError
.
推荐答案
对于 arr
和 axis=0
减少沿 axis=2
> 为 w
.因此,使用 np.tensordot代码>
,解决方案是-
The reduction is along axis=2
for arr
and axis=0
for w
. Thus, with np.tensordot
, the solution would be -
np.tensordot(arr,w,axes=([2],[0]))
或者,也可以使用 np.einsum
-
Alternatively, one can also use np.einsum
-
np.einsum('ijk,k->ij',arr,w)
np.matmul代码>
也有效
np.matmul(arr, w)
运行时测试 -
In [52]: arr = np.random.rand(200,300,300)
In [53]: w = np.random.rand(300)
In [54]: %timeit np.tensordot(arr,w,axes=([2],[0]))
100 loops, best of 3: 8.75 ms per loop
In [55]: %timeit np.einsum('ijk,k->ij',arr,w)
100 loops, best of 3: 9.78 ms per loop
In [56]: %timeit np.matmul(arr, w)
100 loops, best of 3: 9.72 ms per loop
hlin117 在 Macbook Pro OS X El Capitan 上测试,numpy 版本 1.10.4.
hlin117 tested on Macbook Pro OS X El Capitan, numpy version 1.10.4.
这篇关于沿第三轴的点积的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!