Tensorflow - 键盘中断关闭当前会话

时间:2017-01-17 05:22:59

标签: python session machine-learning tensorflow

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

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(),我会收到以下错误:

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)`.

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

1 个答案:

答案 0 :(得分:2)

当你按下ctrl-c时,将产生一个中断,这将导致执行离开with-block。这将导致会话关闭,因为with-block的整个目的是进行自动拆除,例如, this explanation(对我来说只是Google上的第一个热门广告)。

因此取代

with tf.Session() as sess:

sess = tf.Session()

应该解决问题。