Python 如何在使用Tensorflow数据集API时为标量提供设置

Python 如何在使用Tensorflow数据集API时为标量提供设置,python,tensorflow,Python,Tensorflow,我正在使用TF Dataset API和一个占位符作为文件名,我在初始化迭代器时会输入这些文件名(不同的文件取决于它是训练集还是验证集)。我还想使用额外的占位符来指示我们是在培训还是在验证(包括在退出层中)。但是,我无法使用数据集初始值设定项将值提供给此占位符(这是有意义的,因为它不是数据集的一部分)。那么,如何在使用Dataset API时提供额外的变量呢 关键代码块: filenames_placeholder = tf.placeholder(tf.string, shape = (Non

我正在使用TF Dataset API和一个占位符作为文件名,我在初始化迭代器时会输入这些文件名(不同的文件取决于它是训练集还是验证集)。我还想使用额外的占位符来指示我们是在培训还是在验证(包括在退出层中)。但是,我无法使用数据集初始值设定项将值提供给此占位符(这是有意义的,因为它不是数据集的一部分)。那么,如何在使用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

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

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

请注意,在训练时输入一个占位符,它提供了一个额外的
浮点值
并不会降低你的训练速度。

谢谢!我有点误解了文档,实际上我认为无论如何都应该避免使用feed_dict,因为它会减慢训练速度。但事实证明你是对的!输入一个值并不会降低训练速度。