1

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

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?

user1691278
  • 1,751
  • 1
  • 15
  • 20

1 Answers1

2

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

Thus replacing

with tf.Session() as sess:

with

sess = tf.Session()

should solve the issue.