我希望向代码中添加功能,这样,如果我希望在任何时候终止代码,它将安全地终止训练并保存变量。尽管我一直在尝试寻找更好的解决方案,但我认为捕获KeyboardInterrupt异常将是我的最佳选择。

但是,这会安全吗?更具体地说,以下代码是否可以工作:

with tf.Session() as sess
    try:
        for i in range(FLAGS.max_steps):
            sess.run(train_op, feed_dict=some_feed_dictionary)
            # Some other summary writing and evaluative operations
    except KeyboardInterrupt:
        print("Manual interrupt occurred.")

    print('Done training for {} steps'.format(global_steps))
    save_path = saver.save(sess, 'Standard CNN', global_step=global_steps, write_meta_graph=False)

还是它不安全并且考虑到在任何 tensorflow 操作的中间都可以自由发生键盘中断,会导致保存文件损坏?有足够的方法做到这一点吗?

最佳答案

我个人通过在训练过程中一直捕获KeyboardInterrupt来使用与此非常相似的东西,唯一的区别是,我在每个sess.run步骤(或其中每个步骤)之后都“保存”,从来没有遇到过问题。

我不知道“是否不安全”的答案,但我知道我的方法可以避免问这个问题。

在您的代码中,如下所示:

with tf.Session() as sess
    try:
        for i in range(FLAGS.max_steps):
            sess.run(train_op, feed_dict=some_feed_dictionary)
            # Some other summary writing and evaluative operations
            if i % save_steps == 0:
                save_path = saver.save(sess, 'Standard CNN', global_step=global_steps, write_meta_graph=False)
    except KeyboardInterrupt:
        print("Manual interrupt occurred.")
        print('Done training for {} steps'.format(global_steps))

为了明确起见,save_steps变量确定两次保存之间的步数。

关于python - TensorFlow如何安全地手动终止训练(KeyboardInterrupt),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/45033413/

10-12 16:36