键盘中断tensorflow运行并在该点保存

5
有没有一种方法可以在键盘中断时打破tensorflow会话,并在那一点上有保存模型的选项?我现在让会话一夜之间保持运行状态,但需要停止它,以便在白天期间释放计算机内存。随着训练的进行,每个时期都会变得越来越慢,因此有时我可能必须等待几小时才能进行下一次预定的程序保存。我希望能够随时打入运行并从该点保存功能。我甚至找不到是否可能。感谢指点。
1个回答

5

一种选择是对tf.Session对象进行子类化,并创建一个__exit__函数,该函数在键盘中断通过时将当前状态保存出来。这只能在新对象作为with块的一部分调用时才起作用。

以下是此子类:

import tensorflow as tf

class SessionWithExitSave(tf.Session):
    def __init__(self, *args, saver=None, exit_save_path=None, **kwargs):
        self.saver = saver
        self.exit_save_path = exit_save_path
        super().__init__(*args, **kwargs)

    def __exit__(self, exc_type, exc_value, exc_tb):
        if exc_type is KeyboardInterrupt:
            if self.saver:
                self.saver.save(self, self.exit_save_path)
                print('Output saved to: "{}./*"'.format(self.exit_save_path))
        super().__exit__(exc_type, exc_value, exc_tb)

以下是来自 TensorFlow mnist 操作指南的实例用法。

import tensorflow as tf
import datetime as dt
from tensorflow.examples.tutorials.mnist import input_data

mnist = input_data.read_data_sets('U:/mnist/', one_hot=True)
x = tf.placeholder(tf.float32, [None, 784])
W = tf.Variable(tf.zeros([784, 10]))
b = tf.Variable(tf.zeros([10]))
y = tf.matmul(x, W) + b
# Define loss and optimizer
y_ = tf.placeholder(tf.float32, [None, 10])
cross_entropy = tf.reduce_mean(
    tf.nn.softmax_cross_entropy_with_logits(labels=y_, logits=y))
train_step = tf.train.GradientDescentOptimizer(0.2).minimize(cross_entropy)

saver = tf.train.Saver()

with SessionWithExitSave(
        saver=saver, 
        exit_save_path='./tf-saves/_lastest.ckpt') as sess:
    sess.run(tf.global_variables_initializer())
    total_epochs = 50
    for epoch in range(1, total_epochs+1):
        for _ in range(1000):
            batch_xs, batch_ys = mnist.train.next_batch(100)
            sess.run(train_step, feed_dict={x: batch_xs, y_: batch_ys})
        # Test trained model
        correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1))
        accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))

        print(f'Epoch {epoch} of {total_epochs} :: accuracy = ', end='')
        print(sess.run(accuracy, feed_dict={x: mnist.test.images, y_: mnist.test.labels}))
        save_time = dt.datetime.now().strftime('%Y%m%d-%H.%M.%S')
        saver.save(sess, f'./tf-saves/mnist-{save_time}.ckpt')

我让这个程序运行了10次迭代,然后从键盘发送了一个中断信号。下面是输出结果:

Epoch 1 of 50 :: accuracy = 0.9169
Epoch 2 of 50 :: accuracy = 0.919
Epoch 3 of 50 :: accuracy = 0.9205
Epoch 4 of 50 :: accuracy = 0.9221
Epoch 5 of 50 :: accuracy = 0.92
Epoch 6 of 50 :: accuracy = 0.9229
Epoch 7 of 50 :: accuracy = 0.9234
Epoch 8 of 50 :: accuracy = 0.9234
Epoch 9 of 50 :: accuracy = 0.9252
Epoch 10 of 50 :: accuracy = 0.9248
Output saved to: "./tf-saves/_lastest.ckpt./*"
---------------------------------------------------------------------------
KeyboardInterrupt                         Traceback (most recent call last)
...
--> 768   elif item[0].cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:
    769     return item[1]._is_present_in_parent
    770   else:
KeyboardInterrupt:

实际上,我拥有所有保存的文件,包括发送给系统的键盘中断的保存。

import os

os.listdir('./tf-saves/')
# returns:
['checkpoint',
 'mnist-20171207-23.05.18.ckpt.data-00000-of-00001',
 'mnist-20171207-23.05.18.ckpt.index',
 'mnist-20171207-23.05.18.ckpt.meta',
 'mnist-20171207-23.05.22.ckpt.data-00000-of-00001',
 'mnist-20171207-23.05.22.ckpt.index',
 'mnist-20171207-23.05.22.ckpt.meta',
 'mnist-20171207-23.05.26.ckpt.data-00000-of-00001',
 'mnist-20171207-23.05.26.ckpt.index',
 'mnist-20171207-23.05.26.ckpt.meta',
 'mnist-20171207-23.05.31.ckpt.data-00000-of-00001',
 'mnist-20171207-23.05.31.ckpt.index',
 '_lastest.ckpt.data-00000-of-00001',
 '_lastest.ckpt.index',
 '_lastest.ckpt.meta']

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接