我正在使用 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/