我使用 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
相关分类