numpy 中两个 3D 数组的最后两个轴的点积
Dot product with last two axises of two 3D arrays in numpy
我尝试计算两个 3D numpy 数组的点积。
假设我有一个数组x,形状为(2,3,2),其值如下:
array([[[0, 0],
[1, 1],
[1, 1]],
[[1, 0],
[0, 1],
[1, 1]]])
我还有另一个 3D 数组 y ,形状是 (2, 2, 3),值为 :
array([[[0, 0, 0],
[1, 0, 1]],
[[0, 1, 1],
[1, 1, 1]]])
现在我想在最后两个轴上做 x 和 y 的点积。
我的意思是我想生成
的结果
x[0].dot(y[0])
x[1].dot(y[1])
有什么简单的方法可以做到这一点吗?我已经尝试使用 x.dot(y),但是它没有用。
谢谢!
在 NumPy 1.10 及更高版本上,这是
np.matmul(x, y)
如果您至少使用 NumPy 1.10 和 Python 3.5,这也可以写成
x @ y
我用 tensordot
的次数还不如 einsum
。我的第一次尝试计算了太多值,但我可以过滤掉这些值:
In [388]: np.tensordot(x,y,(2,1))[[0,1],:,[0,1]]
Out[388]:
array([[[0, 0, 0],
[1, 0, 1],
[1, 0, 1]],
[[0, 1, 1],
[1, 1, 1],
[1, 2, 2]]])
想一想,tensordot
与 np.dot(x,y)
相同,生成 (2,3,2,3) 数组。
In [389]: np.einsum('ijk,ikm->ijm',x,y)
Out[389]:
array([[[0, 0, 0],
[1, 0, 1],
[1, 0, 1]],
[[0, 1, 1],
[1, 1, 1],
[1, 2, 2]]])
In [394]: x@y
Out[394]:
array([[[0, 0, 0],
[1, 0, 1],
[1, 0, 1]],
[[0, 1, 1],
[1, 1, 1],
[1, 2, 2]]])
在 einsum
条件下 dot
产生:
np.einsum('ijk,okm->ijom',x,y)
然后我们必须删除案例i!=o
。
如果你想使用 Theano:
import theano
x = np.array([[[0,0],[1,1],[1,1]], [[1,0],[0,1],[1,1]]])
y = np.array([[[0,0,0], [1,0,1]], [[0,1,1], [1,1,1]]])
res1 = theano.tensor.dot(x[0], y[0])
res2 = theano.tensor.dot(x[1], y[1])
输出:
In [36]: res1.eval()
Out[36]:
array([[0, 0, 0],
[1, 0, 1],
[1, 0, 1]])
In [37]: res2.eval()
Out[37]:
array([[0, 1, 1],
[1, 1, 1],
[1, 2, 2]])
我尝试计算两个 3D numpy 数组的点积。 假设我有一个数组x,形状为(2,3,2),其值如下:
array([[[0, 0],
[1, 1],
[1, 1]],
[[1, 0],
[0, 1],
[1, 1]]])
我还有另一个 3D 数组 y ,形状是 (2, 2, 3),值为 :
array([[[0, 0, 0],
[1, 0, 1]],
[[0, 1, 1],
[1, 1, 1]]])
现在我想在最后两个轴上做 x 和 y 的点积。 我的意思是我想生成
的结果x[0].dot(y[0])
x[1].dot(y[1])
有什么简单的方法可以做到这一点吗?我已经尝试使用 x.dot(y),但是它没有用。 谢谢!
在 NumPy 1.10 及更高版本上,这是
np.matmul(x, y)
如果您至少使用 NumPy 1.10 和 Python 3.5,这也可以写成
x @ y
我用 tensordot
的次数还不如 einsum
。我的第一次尝试计算了太多值,但我可以过滤掉这些值:
In [388]: np.tensordot(x,y,(2,1))[[0,1],:,[0,1]]
Out[388]:
array([[[0, 0, 0],
[1, 0, 1],
[1, 0, 1]],
[[0, 1, 1],
[1, 1, 1],
[1, 2, 2]]])
想一想,tensordot
与 np.dot(x,y)
相同,生成 (2,3,2,3) 数组。
In [389]: np.einsum('ijk,ikm->ijm',x,y)
Out[389]:
array([[[0, 0, 0],
[1, 0, 1],
[1, 0, 1]],
[[0, 1, 1],
[1, 1, 1],
[1, 2, 2]]])
In [394]: x@y
Out[394]:
array([[[0, 0, 0],
[1, 0, 1],
[1, 0, 1]],
[[0, 1, 1],
[1, 1, 1],
[1, 2, 2]]])
在 einsum
条件下 dot
产生:
np.einsum('ijk,okm->ijom',x,y)
然后我们必须删除案例i!=o
。
如果你想使用 Theano:
import theano
x = np.array([[[0,0],[1,1],[1,1]], [[1,0],[0,1],[1,1]]])
y = np.array([[[0,0,0], [1,0,1]], [[0,1,1], [1,1,1]]])
res1 = theano.tensor.dot(x[0], y[0])
res2 = theano.tensor.dot(x[1], y[1])
输出:
In [36]: res1.eval()
Out[36]:
array([[0, 0, 0],
[1, 0, 1],
[1, 0, 1]])
In [37]: res2.eval()
Out[37]:
array([[0, 1, 1],
[1, 1, 1],
[1, 2, 2]])