【问题标题】:How do I pass a scalar via a TensorFlow feed dictionary如何通过 TensorFlow 提要字典传递标量
【发布时间】:2016-12-30 22:21:45
【问题描述】:

我的 TensorFlow 模型使用 tf.random_uniform 来初始化变量。我想在开始训练时指定范围,所以我为初始化值创建了一个占位符。

init = tf.placeholder(tf.float32, name="init")
v = tf.Variable(tf.random_uniform((100, 300), -init, init), dtype=tf.float32)
initialize = tf.initialize_all_variables()

我在训练开始时像这样初始化变量。

session.run(initialize, feed_dict={init: 0.5})

这给了我以下错误:

ValueError: initial_value must have a shape specified: Tensor("Embedding/random_uniform:0", dtype=float32)

我无法确定要传递给tf.placeholder 的正确shape 参数。我认为对于标量我应该做init = tf.placeholder(tf.float32, shape=0, name="init") 但这会产生以下错误:

ValueError: Incompatible shapes for broadcasting: (100, 300) and (0,)

如果我在对tf.random_uniform 的调用中将init 替换为文字值0.5,它会起作用。

如何通过提要字典传递这个标量初始值?

【问题讨论】:

    标签: python machine-learning tensorflow


    【解决方案1】:

    TL;DR: 使用标量形状定义init,如下所示:

    init = tf.placeholder(tf.float32, shape=(), name="init")
    

    这看起来像是 tf.random_uniform() 的一个不幸的实现细节:它目前使用 tf.add()tf.multiply() 将随机值从 [-1, +1] 重新调整为 [minval, maxval],但是如果minvalmaxval 的形状未知,则tf.add()tf.multiply() 无法推断出正确的形状,因为可能涉及到广播。

    通过使用已知形状定义init(其中标量是()[],而不是0),TensorFlow 可以得出关于tf.random_uniform() 结果形状的正确推断,并且您的程序应该按预期工作。

    【讨论】:

    【解决方案2】:

    您不需要占位符来传递标量,因为任何张量、稀疏张量或张量或稀疏张量的下一个元组都可以。 doc 写道:

    The optional `feed_dict` argument allows the caller to override
    the value of tensors in the graph. Each key in `feed_dict` can be
    one of the following types:
    * If the key is a `tf.Tensor`, the
      value may be a Python scalar, string, list, or numpy ndarray
      that can be converted to the same `dtype` as that
      tensor. Additionally, if the key is a
      `tf.placeholder`, the shape of
      the value will be checked for compatibility with the placeholder.
    * If the key is a
      `tf.SparseTensor`,
      the value should be a
      `tf.SparseTensorValue`.
    * If the key is a nested tuple of `Tensor`s or `SparseTensor`s, the value
      should be a nested tuple with the same structure that maps to their
      corresponding values as above.
    

    在您的场景中,任何张量,如常量或变量或占位符,都可能是合适的。

    init = tf.constant(0)
    init_1 = tf.Variable(0)
    v = tf.Variable(tf.random_uniform((100, 300), -init, init), dtype=tf.float32)
    initialize = tf.global_variables_initializer()
    sess.run(intialize, feed_dict={init: 0.5})
    sess.run(intialize, feed_dict={init_1: 0.5})
    

    您可以将 float 或 int 传递给它,因为只有占位符检查数据类型,如上所述。

    【讨论】:

      猜你喜欢
      • 2012-05-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-07
      • 2020-11-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多