有没有办法使用张量作为 tf.reshape 或 tf.constant 等函数的输入

Is there a way to use a tensor as an input to functions such as tf.reshape or tf.constant

我正在尝试使用张量作为另一个张量流函数的形状输入。有什么方法可以让它发挥作用吗?

例子

import tensorflow as tf

a = tf.constant([1,2,3,4,5])

b = tf.size(a)

c = tf.constant([b,1])

d = tf.reshape(a, [b,1])

sess = tf.Session()

print sess.run([b,c])

以上都不起作用,因为 tensorflow 将输入维度解释为张量列表并给出错误,其底线是:

TypeError: List of Tensors when single Tensor expected

我假设一个解决方法是打开一个会话,评估 'b' 以获得一个 numpy 浮点数,并将其转换为一个整数,但希望尽可能避免这种情况。

非常感谢任何帮助!

您需要使用 a.get_shape(),它可以在 会话之外获得结果(它将给出 推断的形状 ) :

a = tf.constant([1,2,3,4,5])
b = a. get_shape().as_list()[0]
d = tf.reshape(a, [b, 1])

您也可以将 -1tf.reshape 一起使用,这将使总大小保持不变。

d = tf.reshape(a, [-1, 1])