python - Tensorflow - 键盘中断是否关闭当前 session

标签 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),程序会停止,但 session 似乎也已关闭。例如,如果我传递 .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)`.

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

最佳答案

当您按下 ctrl-c 时,将生成一个中断,这将导致执行离开 with block 。这将导致 session 关闭,因为 with-block 的整个目的是自动拆卸,请参见例如this explanation (这只是我在谷歌上的第一次点击)。

因此替换

with tf.Session() as sess:

sess = tf.Session()

应该可以解决问题。

关于python - Tensorflow - 键盘中断是否关闭当前 session ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41689566/

相关文章:

php - 如何让php脚本并行运行?

java - SWF Flash Uploader 使 JSESSIONID 无效。有想法从服务器端或客户端恢复 session 吗?

machine-learning - 针对简单的一维场景推荐的异常检测技术?

Python:从父子值列表创建嵌套字典

从 facebook oauth 重定向时 django session 丢失

python - 值错误 : 'balanced_accuracy' is not a valid scoring value in scikit-learn

python - 如何在 sklearn 中使用带有自定义估算器的 GridSearchCV?

python - 转换具有不同格式转换的列表列表的项目

python - 使用对特定键值的理解从字典列表创建列表

python - 如何在 Python 中检查 ip 是否在网络中?