使用批量乘法在 tensorflow 的 tensordot 中遇到障碍

bj1*_*123 3 numpy tensorflow

我正在 tensorflow 中实现 RBM。

并且使用小批量实现参数更新存在障碍

有 2 个张量

第一个张量的形状是 [100,3,1] 第二张量的形状是 [100,1,4]

数字 100 是批次的大小。

所以我想乘以这些张量,得到 [100,3,4] 张量。

但是当我实现代码时

tf.tensordot(1st_tensor,2nd_tensor,[[2],[1]])

结果张量的形状是 [100,3,100,4]

我该如何解决这个问题?

pts*_*tsw 5

我不确定您是否仍然面临这个问题(因为已经一个月了),但我使用tf.tensordotand解决了同样的问题tf.map_fn,它接受嵌套的输入元素并在第一个(通常是批处理)维度上并行化一个函数。以下函数在任意等级的张量的最后两个维度上执行批量并行矩阵乘法(只要最后两个轴匹配矩阵乘法的目的):

def matmul_final_two_dims(tensor1, tensor2):
  # set this to the appropriate value, as map_fn seems to have
  # some dtype inference difficulties:
  _your_dtype_here = tf.float64
  return tf.map_fn(lambda xy: tf.tensordot(xy[0], xy[1], axes=[[-1], [-2]]),
                   elems=(tensor1, tensor2), dtype=_your_dtype_here)
Run Code Online (Sandbox Code Playgroud)

用法示例:

>> batchsize = 3
>> tensor1 = np.random.rand(batchsize,3,4,5,2) # final dims [5,2]
>> tensor2 = np.random.rand(batchsize,2,3,2,4) # final dims [2,4]
>> sess.run(tf.shape(matmul_final_two_dims(tensor1, tensor2)))
array([3, 3, 4, 5, 2, 3, 4], dtype=int32)
>> matmul_final_two_dims(tensor1,tensor2)
<tf.Tensor 'map_1/TensorArrayStack/TensorArrayGatherV3:0' shape=(3, 3, 4, 5, 2, 3, 4) dtype=float64>
Run Code Online (Sandbox Code Playgroud)

特别注意,输出的第一个维度是正确的批量大小,2形状中的最后一个维度是张量收缩的。但是,您必须执行某种tf.transpose操作才能5在正确的位置获得维度索引,因为输出矩阵的索引在输入张量中出现时是有序的。

我正在使用 TFv1.1。tf.map_fn可以并行化,但我不确定以上是否是最有效的实现。以供参考:

tf.tensordot API

tf.map_fn API

编辑:以上对我有用,但我认为您也可以使用einsum此处的文档)来完成您想要的:

>> tensor1 = tf.constant(np.random.rand(3,4,5))
>> tensor2 = tf.constant(np.random.rand(3,5,7))
>> tf.einsum('bij,bjk->bik', tensor1, tensor2)
<tf.Tensor 'transpose_2:0' shape=(3, 4, 7) dtype=float64>
Run Code Online (Sandbox Code Playgroud)