[英]Dot product along third axis
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. 我正试图使用tensordot
在numpy中使用张量点产品,但我不确定如何重塑我的数组以实现我的计算。 (I'm still new to the mathematics of tensors, in general.) (总的来说,我对张量的数学还很陌生。)
I have 我有
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]
And I want to take a dot product along axis=2
, such that I have the matrix 我想沿着axis=2
取一个点积,这样我就有了矩阵
array([[3, 0, 6],
[0, 12, 0]])
What's the proper numpy syntax for this? 什么是适当的numpy语法? np.tensordot(arr, [1, 1, 1], axes=2)
seems to raise a ValueError
. np.tensordot(arr, [1, 1, 1], axes=2)
似乎引发了一个ValueError
。
The reduction is along axis=2
for arr
and axis=0
for w
. 对于arr
,减小沿axis=2
,对于w
,减小沿axis=2
axis=0
。 Thus, with np.tensordot
, the solution would be - 因此,使用np.tensordot
,解决方案将是 -
np.tensordot(arr,w,axes=([2],[0]))
Alternatively, one can also use np.einsum
- 或者,也可以使用np.einsum
-
np.einsum('ijk,k->ij',arr,w)
np.matmul
also works np.matmul
也有效
np.matmul(arr, w)
Runtime test - 运行时测试 -
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 tested on Macbook Pro OS X El Capitan, numpy version 1.10.4. hlin117在Macbook Pro OS X El Capitan上测试,numpy版本1.10.4。
Using .dot
works just fine for me: 使用.dot
对我来说很好用:
>>> import numpy as np
>>> arr = np.array([[[1, 1, 1],
[0, 0, 0],
[2, 2, 2]],
[[0, 0, 0],
[4, 4, 4],
[0, 0, 0]]])
>>> arr.dot([1, 1, 1])
array([[ 3, 0, 6],
[ 0, 12, 0]])
Although interestingly is slower than all the other suggestions 虽然有趣的是比所有其他建议慢
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.