Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/tensorflow/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 恢复使用迭代器的Tensorflow模型_Python_Tensorflow_Tensorflow Datasets - Fatal编程技术网

Python 恢复使用迭代器的Tensorflow模型

Python 恢复使用迭代器的Tensorflow模型,python,tensorflow,tensorflow-datasets,Python,Tensorflow,Tensorflow Datasets,我有一个使用迭代器训练网络的模型;遵循谷歌现在推荐的新的数据集API管道模型 我读取tfrecord文件,将数据馈送到网络,进行了良好的训练,一切都进行得很顺利,我在训练结束时保存了我的模型,以便以后可以对其进行推理。代码的简化版本如下所示: """ Training and saving """ training_dataset = tf.contrib.data.TFRecordDataset(training_record) training_dataset = training_dat

我有一个使用迭代器训练网络的模型;遵循谷歌现在推荐的新的数据集API管道模型

我读取tfrecord文件,将数据馈送到网络,进行了良好的训练,一切都进行得很顺利,我在训练结束时保存了我的模型,以便以后可以对其进行推理。代码的简化版本如下所示:

""" Training and saving """

training_dataset = tf.contrib.data.TFRecordDataset(training_record)
training_dataset = training_dataset.map(ds._path_records_parser)
training_dataset = training_dataset.batch(BATCH_SIZE)
with tf.name_scope("iterators"):
  training_iterator = Iterator.from_structure(training_dataset.output_types, training_dataset.output_shapes)
  next_training_element = training_iterator.get_next()
  training_init_op = training_iterator.make_initializer(training_dataset)

def train(num_epochs):
  # compute for the number of epochs
  for e in range(1, num_epochs+1):
    session.run(training_init_op) #initializing iterator here
    while True:
      try:
        images, labels = session.run(next_training_element)
        session.run(optimizer, feed_dict={x: images, y_true: labels})
      except tf.errors.OutOfRangeError:
        saver_name = './saved_models/ucf-model'
        print("Finished Training Epoch {}".format(e))
        break



    """ Restoring """
# restoring the saved model and its variables
session = tf.Session()
saver = tf.train.import_meta_graph(r'saved_models\ucf-model.meta')
saver.restore(session, tf.train.latest_checkpoint('.\saved_models'))
graph = tf.get_default_graph()

# restoring relevant tensors/ops
accuracy = graph.get_tensor_by_name("accuracy/Mean:0") #the tensor that when evaluated returns the mean accuracy of the batch
testing_iterator = graph.get_operation_by_name("iterators/Iterator") #my iterator used in testing.
next_testing_element = graph.get_operation_by_name("iterators/IteratorGetNext") #the GetNext operator for my iterator
# loading my testing set tfrecords
testing_dataset = tf.contrib.data.TFRecordDataset(testing_record_path)
testing_dataset = testing_dataset.map(ds._path_records_parser, num_threads=4, output_buffer_size=BATCH_SIZE*20)
testing_dataset = testing_dataset.batch(BATCH_SIZE)

testing_init_op = testing_iterator.make_initializer(testing_dataset) #to initialize the dataset

with tf.Session() as session:
  session.run(testing_init_op)
  while True:
    try:
      images, labels = session.run(next_testing_element)
      accuracy = session.run(accuracy, feed_dict={x: test_images, y_true: test_labels}) #error here, x, y_true not defined
    except tf.errors.OutOfRangeError:
      break
我的问题主要是当我恢复模型时。如何向网络提供测试数据

  • 当我使用
    testing\u Iterator=graph.get\u operation\u by\u name(“iterators/Iterator”)
    next\u testing\u element=graph.get\u operation\u by\u name(“iterators/IteratorGetNext”)
    还原迭代器时,我得到以下错误:
    GetNext()失败,因为迭代器尚未初始化。在获取下一个元素之前,请确保已为此迭代器运行初始化器操作。
  • 所以我尝试使用:
    testing\u init\u op=testing\u iterator.make\u initializer(testing\u dataset))
    初始化我的数据集。我遇到了这个错误:
    AttributeError:“Operation”对象没有属性“make\u initializer”
另一个问题是,由于使用了迭代器,因此不需要在training_模型中使用占位符,因为迭代器直接将数据提供给图形。但是这样,当我将数据输入到“准确性”操作时,如何恢复从第三行到最后一行的输入键


编辑:如果有人建议在迭代器和网络输入之间添加占位符,那么我可以尝试通过计算“准确性”张量来运行图形,同时将数据输入占位符并完全忽略迭代器。

我无法解决与初始化迭代器相关的问题,但由于我使用方法预处理我的数据集,并且我应用了由用包装的Python操作定义的转换,这些转换无法序列化以用于存储\还原,所以在我仍然要还原数据集时,我必须初始化数据集


所以,剩下的问题是,当我恢复图形时,如何将数据馈送到图形中。我在迭代器输出和网络输入之间放置了一个tf.identity节点。恢复后,我将数据馈送到标识节点。我后来发现的一个更好的解决方案是使用
占位符\u和\u default()
,如中所述

还原保存的元图时,可以使用name还原初始化操作,然后再次使用它初始化输入管道进行推理

也就是说,在创建图形时,您可以

    dataset_init_op = iterator.make_initializer(dataset, name='dataset_init')
然后通过执行以下操作恢复此操作:

    dataset_init_op = graph.get_operation_by_name('dataset_init')
下面是一个自包含的代码片段,它比较了随机初始化的模型在恢复之前和之后的结果

保存迭代器 然后您可以恢复相同的模型进行推理,如下所示:

恢复保存的迭代器 我建议使用,它正是为此目的而设计的。它不那么冗长,并且不需要更改现有代码,特别是如何定义迭代器

工作示例,当我们在步骤5完成后保存所有内容时。请注意,我甚至不知道使用了什么种子

import tensorflow as tf

iterator = (
  tf.data.Dataset.range(100)
  .shuffle(10)
  .make_one_shot_iterator())
batch = iterator.get_next(name='batch')

saveable_obj = tf.contrib.data.make_saveable_from_iterator(iterator)
tf.add_to_collection(tf.GraphKeys.SAVEABLE_OBJECTS, saveable_obj)
saver = tf.train.Saver()

with tf.Session() as sess:
  tf.global_variables_initializer().run()
  for step in range(10):
    print('{}: {}'.format(step, sess.run(batch)))
    if step == 5:
      saver.save(sess, './foo', global_step=step)

# 0: 1
# 1: 6
# 2: 7
# 3: 3
# 4: 8
# 5: 10
# 6: 12
# 7: 14
# 8: 5
# 9: 17
然后,如果我们从步骤6继续,我们将得到相同的输出

import tensorflow as tf

saver = tf.train.import_meta_graph('./foo-5.meta')
with tf.Session() as sess:
  saver.restore(sess, './foo-5')
  for step in range(6, 10):
    print('{}: {}'.format(step, sess.run('batch:0')))
# 6: 12
# 7: 14
# 8: 5
# 9: 17

我建议您看看CheckpointInputPipelineHook,它实现了保存迭代器状态,以便使用tf.Estimator进行进一步培训。

这很有帮助。是否可以使用新数据集重新初始化迭代器?似乎我真正想做的是保存可重新初始化的迭代器本身(而不是
dataset\u init\u op
)。然后我想还原迭代器,并用新的数据集创建一个新的初始值设定项。但是当我试图保存迭代器op时,TF会抱怨。@masonk我不知道你想说什么。如果您正在谈论使用具有相同结构的不同数据(例如,训练集与测试集)初始化相同的
数据集
管道,那么只需运行
数据集_init_op
,并将新数据作为
提要_dict
的参数,如上所示。这是用新数据初始化可重新初始化的迭代器。如果输入数据是不同的结构,你需要看看。我今天在tensorflow/tensorflow上提交了这个bug,它描述了我的用例:最后我使用了一个可反馈迭代器。我认为,只有当您的数据集在内存中时,才能在您正在进行的操作中输入占位符变量。我想从一个新的数据集中重新初始化一个可重新初始化的迭代器。
import tensorflow as tf

iterator = (
  tf.data.Dataset.range(100)
  .shuffle(10)
  .make_one_shot_iterator())
batch = iterator.get_next(name='batch')

saveable_obj = tf.contrib.data.make_saveable_from_iterator(iterator)
tf.add_to_collection(tf.GraphKeys.SAVEABLE_OBJECTS, saveable_obj)
saver = tf.train.Saver()

with tf.Session() as sess:
  tf.global_variables_initializer().run()
  for step in range(10):
    print('{}: {}'.format(step, sess.run(batch)))
    if step == 5:
      saver.save(sess, './foo', global_step=step)

# 0: 1
# 1: 6
# 2: 7
# 3: 3
# 4: 8
# 5: 10
# 6: 12
# 7: 14
# 8: 5
# 9: 17
import tensorflow as tf

saver = tf.train.import_meta_graph('./foo-5.meta')
with tf.Session() as sess:
  saver.restore(sess, './foo-5')
  for step in range(6, 10):
    print('{}: {}'.format(step, sess.run('batch:0')))
# 6: 12
# 7: 14
# 8: 5
# 9: 17