【问题标题】:Tensorflow. Converting unknown dimension size of a tensor to int张量流。将张量的未知尺寸大小转换为 int
【发布时间】:2016-11-19 05:04:27
【问题描述】:

假设我们有

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

如何转换 b 以便在进一步计算中使用它,例如对于给定的张量 T 我将能够创建一个新的张量,比如

newT = T / b

【问题讨论】:

    标签: python tensorflow


    【解决方案1】:

    你必须使用 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)
    

    【讨论】:

    • 我正在尝试这种方法,但我不断收到:“ValueError:尝试将'x'转换为张量并失败。错误:无法将未知维度转换为张量”这个问题的任何解决方案?
    【解决方案2】:

    你目前的方式已经奏效了。我用下面的代码试了一下,效果很好:

    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]
    

    【讨论】:

    • 这不是我的情况,因为您的 x 具有预先指定的尺寸大小。而且它是一个列表,而不是张量
    • 哦,我忘记复制和粘贴了,但是我在实例化之后就有了 x = tf.constant(x) 行,所以它适用于张量。但是关于你的占位符问题,你能详细说明你有什么问题吗?我本来希望在运行时生成形状,所以上面应该可以工作。
    • 哦,我想我知道你在打什么。使用 tf.shape(x)[0] (在运行时获取值)而不是 x.get_shape()[0] (在图形构建时)
    猜你喜欢
    • 1970-01-01
    • 2021-12-08
    • 2019-10-07
    • 2017-01-20
    • 2022-09-29
    • 1970-01-01
    • 2015-09-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多