Tensorflow-键盘中断会关闭当前会话吗 [英] Tensorflow - does keyboard interrupt close the current session

查看:44
本文介绍了Tensorflow-键盘中断会关闭当前会话吗的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Tensorflow测试神经网络.这是我的代码的摘录:

I am using Tensorflow to test a neural network. This is an excerpt of my code:

with tf.Session() as sess:
# Initialize variables
sess.run(init)

# Training cycle
for epoch in range(150):
    avg_cost = 0.
    total_batch = int(X_train.shape[0]/batch_size)
    batch_range = list(range(batch_size, int(X_train.shape[0]),batch_size))
    # Loop over all batches
    i = 0
    while i < total_batch - 1:
        start_idx = batch_range[i]
        end_idx = batch_range[i+1]
        batch_x, batch_y = X_train.iloc[start_idx:end_idx,:], y_train.iloc[start_idx:end_idx,:]
        # Run optimization op (backprop) and cost op (to get loss value)
        _, c = sess.run([optimizer, cost], feed_dict={x: batch_x,
                                                      y: batch_y})
        # Compute average loss
        avg_cost += c / total_batch
        i = i + 1

如果我使用键盘中断(例如 control + c ),该程序将停止,但似乎会话也已关闭.例如,如果我传递 .eval(),我将收到以下错误:

If I use keyboard interrupt (such as control + c), the program stops but it seems like the session is closed as well. For example, if I pass .eval(), I would receive the following error:

ValueError: Cannot use the default session to evaluate tensor: the tensor's graph is different from the session's graph. Pass an explicit session to `eval(session=sess)`.

我想这意味着我的会话已关闭?如何在不关闭会话的情况下中断程序?

I suppose that means my session is closed? How can I interrupt the program without closing the session?

推荐答案

当您按ctrl-c时,将产生一个中断,这将导致执行离开with块.这将导致会话关闭,因为with块的整个目的是进行自动拆除,请参见例如此解释(对我来说,这对Google来说只是第一击).

When you press ctrl-c an interrupt will be generated, which will cause execution to leave the with-block. This will cause the session to be closed, since the whole purpose of the with-block is to do automatic tear-down, see e.g. this explanation (just the first hit on google for me).

因此替换

with tf.Session() as sess:

使用

sess = tf.Session()

应该解决问题.

这篇关于Tensorflow-键盘中断会关闭当前会话吗的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆