2017-07-11 50 views
0

我希望爲我的代碼添加功能,以便如果我希望在任何時候終止代碼,它將安全地終止訓練並保存變量。儘管我已經嘗試尋找更好的解決方案,但我認爲捕獲KeyboardInterrupt例外是我的最佳選擇。TensorFlow如何手動安全地終止培訓(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操作過程中發生文件?有沒有足夠的方法來做到這一點?

回答

1

我個人在訓練過程中一直使用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變量確定保存之間的步數。