gpt4 book ai didi

python - 键盘中断tensorflow运行并在此时保存

转载 作者:太空狗 更新时间:2023-10-30 02:53:57 26 4
gpt4 key购买 nike

有没有办法通过键盘中断来中断 tensorflow session ,并可以选择在此时保存模型?我目前让 session 在一夜之间运行,但需要停止它,这样我就可以释放内存供白天使用的电脑使用。随着训练的进行,每个时期都会变慢,所以有时我可能不得不等待数小时才能在程序中进行下一次预定的保存。我想要能够随时中断运行并从那时起保存的功能。我什至找不到这是否可能。将不胜感激。

最佳答案

一个选择是子类化 tf.Session 对象并创建一个 __exit__ 函数,在键盘中断通过时保存当前状态。这仅在新对象作为 with block 的一部分被调用时才有效。

这是子类:

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。这是输出:

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']

关于python - 键盘中断tensorflow运行并在此时保存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47706467/

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