问题 Tensorflow。将张量的未知维度大小转换为int


假设我们有

a = tf.placeholder(tf.float32, shape=(None, 3072))
b = a.get_shape()[0]

我该如何转换? b 这样我就可以在进一步的计算中使用它,例如对于给定的张量 Ť 我将能够创建一个新的,就像

newT = T / b

6011
2017-11-18 19:59


起源



答案:


您必须使用Graph操作:

a = tf.placeholder(tf.float32, shape=(None, 3072))
b = tf.shape(a)[0]

回报

<tf.Tensor 'strided_slice:0' shape=() dtype=int32>

b = a.get_shape()[0] 回报

Dimension(None)

14
2017-11-18 21:04





您当前的方式已经有效。我尝试使用以下代码,它工作正常:

x = [[1,2,3],[4,5,6], [7,8,9]]
x = tf.constant(x)
size = x.get_shape()[0]
x /= size

with googlelog.Capture():
  p_op = tf.Print(x, [x], "output: ", summarize=10)
  sess.run(p_op)

带输出:

output: [0 0 1 1 1 2 2 2 3]

-2
2017-11-18 20:12



这不是我的情况,因为你的x具有预先规定的尺寸。它也是一个列表,而不是Tensor
哦,我忘记了复制和粘贴,但是我在实例化之后就有了x = tf.constant(x)这样的行,所以它适用于张量。但是关于你的占位符问题,你能详细说明你有什么问题吗?我原本期望在运行时生成形状,所以上面应该有效。 - David Wong
哦,我想我知道你在打什么。使用tf.shape(x)[0](在运行时获取值)而不是x.get_shape()[0](在图形构造时) - David Wong


答案:


您必须使用Graph操作:

a = tf.placeholder(tf.float32, shape=(None, 3072))
b = tf.shape(a)[0]

回报

<tf.Tensor 'strided_slice:0' shape=() dtype=int32>

b = a.get_shape()[0] 回报

Dimension(None)

14
2017-11-18 21:04





您当前的方式已经有效。我尝试使用以下代码,它工作正常:

x = [[1,2,3],[4,5,6], [7,8,9]]
x = tf.constant(x)
size = x.get_shape()[0]
x /= size

with googlelog.Capture():
  p_op = tf.Print(x, [x], "output: ", summarize=10)
  sess.run(p_op)

带输出:

output: [0 0 1 1 1 2 2 2 3]

-2
2017-11-18 20:12



这不是我的情况,因为你的x具有预先规定的尺寸。它也是一个列表,而不是Tensor
哦,我忘记了复制和粘贴,但是我在实例化之后就有了x = tf.constant(x)这样的行,所以它适用于张量。但是关于你的占位符问题,你能详细说明你有什么问题吗?我原本期望在运行时生成形状,所以上面应该有效。 - David Wong
哦,我想我知道你在打什么。使用tf.shape(x)[0](在运行时获取值)而不是x.get_shape()[0](在图形构造时) - David Wong