gpt4 book ai didi

python - TensorFlow 如何安全地手动终止训练 (KeyboardInterrupt)

转载 作者:行者123 更新时间:2023-12-01 15:28:19 44 4
gpt4 key购买 nike

我希望向我的代码添加功能,这样如果我想在任何时候终止代码,它都会安全地终止训练并保存变量。虽然我已经尝试寻找更好的解决方案,但我想捕获一个 KeyboardInterrupt异常(exception)将是我最好的选择。

然而,它会安全吗?更具体地说,以下代码是否有效:

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/

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