如何根据形状为 [5,4,3] 的张量生成 [1,1,1]?

How to generate a [1,1,1] according to a tensor of shape [5,4,3]?

我想应用操作 tf.tile,例如tf.tile(A, [1, 1, b]) 其中 A 的形状为 [5,4,3]。如何根据A生成[1, 1, 1]?然后我将 [1, 1, 1] 的第三个元素设置为 b,其中 b 是占位符。 这是我的代码,但它不起作用,如何解决?

d = tf.shape(A)
for i in range(tf.rank(A)):   #wrong, tf.rank(A) as a tensor can't be here
    d[i] = 1
d[2] = b
result = tf.tile(A, d)

最简单的解决方案可能是使用 tf.one_hot 直接构建 multiples 张量。

>>> b = 2
>>> tf.one_hot(indices=[b], depth=tf.rank(A), on_value=b, off_value=1)
<tf.Tensor: shape=(3,), dtype=int32, numpy=array([1, 1, 2], dtype=int32)>

或者,您可以使用 tf.ones_like 生成一个张量 1,其形状与作为参数传递的张量相同。

>>> A = tf.random.uniform((5,4,3))
>>> tf.shape(A)
<tf.Tensor: shape=(3,), dtype=int32, numpy=array([5, 4, 3], dtype=int32)>
>>> tf.ones_like(tf.shape(A))
<tf.Tensor: shape=(3,), dtype=int32, numpy=array([1, 1, 1], dtype=int32)>

请注意,在 tensorflow 中,您不能对张量进行项目分配(例如 d[2] = b 将不起作用)。要生成张量 [1,1,b],您可以使用 tf.concat:

>>> b = 2
>>> tf.concat([tf.ones_like(tf.shape(A)[:-1]),[b]],axis=0)
<tf.Tensor: shape=(3,), dtype=int32, numpy=array([1, 1, 2], dtype=int32)>