gpt4 book ai didi

python - make_initializable_iterator 和 make_one_shot_iterator 之间的 tensorflow 数据集 API 差异

转载 作者:太空狗 更新时间:2023-10-29 17:47:36 30 4
gpt4 key购买 nike

我想知道make_initializable_iteratormake_one_shot_iterator的区别。
1. Tensorflow 文档说“一次性”迭代器目前不支持重新初始化。这到底是什么意思?
2. 下面两个片段是等价的吗?
使用 make_initializable_iterator

iterator = data_ds.make_initializable_iterator()
data_iter = iterator.get_next()
sess = tf.Session()
sess.run(tf.global_variables_initializer())
for e in range(1, epoch+1):
sess.run(iterator.initializer)
while True:
try:
x_train, y_train = sess.run([data_iter])
_, cost = sess.run([train_op, loss_op], feed_dict={X: x_train,
Y: y_train})
except tf.errors.OutOfRangeError:
break
sess.close()

使用make_one_shot_iterator

iterator = data_ds.make_one_shot_iterator()
data_iter = iterator.get_next()
sess = tf.Session()
sess.run(tf.global_variables_initializer())
for e in range(1, epoch+1):
while True:
try:
x_train, y_train = sess.run([data_iter])
_, cost = sess.run([train_op, loss_op], feed_dict={X: x_train,
Y: y_train})
except tf.errors.OutOfRangeError:
break
sess.close()

最佳答案

假设您想使用相同的代码进行训练和验证。您可能喜欢使用相同的迭代器,但初始化为指向不同的数据集;类似于以下内容:

def _make_batch_iterator(filenames):
dataset = tf.data.TFRecordDataset(filenames)
...
return dataset.make_initializable_iterator()


filenames = tf.placeholder(tf.string, shape=[None])
iterator = _make_batch_iterator(filenames)

with tf.Session() as sess:
for epoch in range(num_epochs):

# Initialize iterator with training data
sess.run(iterator.initializer,
feed_dict={filenames: ['training.tfrecord']})

_train_model(...)

# Re-initialize iterator with validation data
sess.run(iterator.initializer,
feed_dict={filenames: ['validation.tfrecord']})

_validate_model(...)

对于一次性迭代器,您不能像这样重新初始化它。

关于python - make_initializable_iterator 和 make_one_shot_iterator 之间的 tensorflow 数据集 API 差异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48091693/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com