Python 3-dim x 2-dim上的tensordot
我有形状为Python 3-dim x 2-dim上的tensordot,python,numpy,tensorflow,Python,Numpy,Tensorflow,我有形状为的张量A(批量大小,x\u 1,x\u 2)和形状为的张量B(x\u 2,x\u 3)。我想将张量A的每个元素与张量B进行点乘。不使用tensordot的示例如下: product_tensor = np.zeros((batch_size, x_1, x_3)) for i in range(batch_size): product_tensor[i] = np.dot(tensor_A[i], tensor_B) 我很难弄清楚轴参数的参数应该是什么。根据我所读的,axes
的张量A
(批量大小,x\u 1,x\u 2)
和形状为的张量B
(x\u 2,x\u 3)
。我想将张量A
的每个元素与张量B
进行点乘。不使用tensordot的示例如下:
product_tensor = np.zeros((batch_size, x_1, x_3))
for i in range(batch_size):
product_tensor[i] = np.dot(tensor_A[i], tensor_B)
我很难弄清楚轴
参数的参数应该是什么。根据我所读的,axes=1
表示点积,但我无法判断它是将A的前两个轴与B相乘,还是将A的最后两个轴与B相乘
我尝试了tf.tensordot(tensor_A,tensor_B[None,:,:,:,:],axes=1)
,但没有成功,因为它似乎将tensor_A
重塑为形状(batch_size*x_1,x_2)
和tensor B
重塑为形状(1,x_2*x_3
非常感谢您的帮助!这将为您提供所需的结果:
import numpy as np
a = np.array([
[[1, 2, 3], [4, 5, 6]],
[[1, 2, 3], [4, 5, 6]],
[[1, 2, 3], [4, 5, 6]],
[[1, 2, 3], [4, 5, 6]],
[[1, 2, 3], [4, 5, 6]],
[[1, 2, 3], [4, 5, 6]],
])
b = np.array([[1,2,3,4], [5,6,7,8], [9,10,11,12]])
print('a.shape = ', a.shape)
print('b.shape = ', b.shape)
# tensordot
c_tensordot = np.tensordot(a, b, axes=(1))
# loop method with dot
c_loop = np.empty([a.shape[0], a.shape[1], b.shape[1]])
for i in range(0,a.shape[0]):
c_loop[i] = np.dot(a[i], b)
print('c_tensordot = ', c_tensordot)
print('c_loop = ', c_loop)
print('c_tensordot.shape = ', c_tensordot.shape)
print('c_loop.shape = ', c_loop.shape)
print('\nAre arrays equal: ', np.array_equal(c_tensordot, c_loop))
matmul/@
能够很好地处理批处理。A@B
np.einsum
还可以很好地控制轴组合。