首页 > 解决方案 > 组合任意形状的张量

问题描述

我想组合两个可变长度张量。

由于它们的形状不匹配,我不能使用 tf.concat 或 tf.stack。

所以我想我会把一个展平,然后将它附加到另一个的每个元素上——但我不知道该怎么做。

例如,

a = [ [1,2], [3,4] ]
flat_b = [5, 6]

combine(a, flat_b) would be [ [ [1,5,6], [2,5,6] ],
                              [ [3,5,6], [4,5,6] ] ]

有没有这样的方法?

标签: pythontensorflow

解决方案


使用tf.map_fnwith tf.concat,示例代码:

import tensorflow as tf

a = tf.constant([ [1,2], [3,4] ])
flat_b = [5, 6]
flat_a = tf.reshape(a, (tf.reduce_prod(a.shape).numpy(), ))[:, tf.newaxis]
print(flat_a)
c = tf.map_fn(fn=lambda t: tf.concat([t, flat_b], axis=0), elems=flat_a)
c = tf.reshape(c, (-1, a.shape[1], c.shape[1]))
print(c)

输出:

tf.Tensor(
[[1]
 [2]
 [3]
 [4]], shape=(4, 1), dtype=int32)
tf.Tensor(
[[[1 5 6]
  [2 5 6]]

 [[3 5 6]
  [4 5 6]]], shape=(2, 2, 3), dtype=int32)

推荐阅读