【问题标题】:How to feed scalar with settings while using Tensorflow Dataset API如何在使用 Tensorflow 数据集 API 时使用设置提供标量
【发布时间】:2019-02-01 13:02:00
【问题描述】:

我正在使用带有占位符的 TF 数据集 API,用于在初始化迭代器时提供的文件名(不同的文件取决于它是训练集还是验证集)。我还想使用额外的占位符来指示我们是在训练还是在验证(包括在 dropout 层中)。但是,我无法使用数据集初始化程序将值提供给这个占位符(这是有道理的,因为这不是数据集的一部分)。那么如何在使用 Dataset API 的同时提供额外的变量呢?

关键代码片段:

filenames_placeholder = tf.placeholder(tf.string, shape = (None))
is_training = tf.placeholder(tf.bool, shape = ()) # Error: You must feed a value for placeholder tensor 'Placeholder_1' with dtype bool
dataset = tf.data.TFRecordDataset(filenames_placeholder)
# (...) Many other dataset operations
iterator = dataset.make_initializable_iterator()
next_element = iterator.get_next()

# Model code using "next_element"  as inputs including the dropout layer at some point 
# where I would like to let the model know if we're training or validating

tf.layers.dropout(x, training = is_training)

# Model execution
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
sess.run(iterator.initializer, feed_dict = {filenames_placeholder: training_files, is_training: True})
# (...) Performing training
sess.run(iterator.initializer, feed_dict = {filenames_placeholder: training_files, is_training: False})
# (...) Performing validadtion

【问题讨论】:

    标签: python tensorflow


    【解决方案1】:

    在这种情况下我要做的是添加一个带有默认值的额外占位符:

    keep_prob = tf.placeholder_with_default(1.0, shape=())
    

    在图中:

    tf.layers.dropout(inputs, rate=1-keep_prob)
    

    然后在训练时:

    sess.run(...,feed_dict={keep_prob:0.5})
    

    评估时:

    sess.run(...) # No feed_dict here since the keep_prob placeholder has a default value of 1
    

    请注意,在训练时提供一个占位符,提供额外的 float 值不会减慢您的训练速度。

    【讨论】:

    • 谢谢!我有点误解了文档,并且确实认为在任何情况下都应该避免使用 feed_dict,因为它会减慢训练速度。但事实证明你是对的!输入单个值根本不会减慢训练速度。
    猜你喜欢
    • 1970-01-01
    • 2020-06-27
    • 2019-02-25
    • 1970-01-01
    • 2016-05-04
    • 1970-01-01
    • 2012-09-26
    • 2019-02-03
    • 1970-01-01
    相关资源
    最近更新 更多