0

I have a for loop with excerpts of try-except blocks referring to https://machinetalk.org/2019/03/29/neural-machine-translation-with-attention-mechanism/?unapproved=67&moderation-hash=ea8e5dcb97c8236f68291788fbd746a7#comment-67:-

for e in range(NUM_EPOCHS):
    en_initial_states = encoder.init_states(BATCH_SIZE)

    for batch, (source_seq, target_seq_in, target_seq_out) in enumerate(dataset.take(-1)):
        loss = train_step(source_seq, target_seq_in,
                          target_seq_out, en_initial_states)

        if batch % 100 == 0:
                print('Epoch {} Batch {} Loss {:.4f}'.format(
                    e + 1, batch, loss.numpy()))


    try:
        test_target_text,net_words = predict()
    except Exception:
      continue

    if loss <=0.0001:
       break

I want to come out of the loop and not execute the try block and leave everything and simply come out of both, the inner and outer loops as well as the entire try-except block. I don't know what is going wrong, as using the if condition in the inner/outer loop blocks doesn't work.

JChat
  • 784
  • 2
  • 13
  • 33
  • see [this answer](https://stackoverflow.com/a/3979024/10417531) –  Jun 28 '19 at 10:43
  • Have you confirmed that your loss is actually less than or equal to .0001? It looks like you are only printing four digits of the loss in your print statement, so maybe your loss is .00012 and the condition is not met – Novice Jun 28 '19 at 11:14
  • @Novice yes, I checked it is <= 0.0001 but still the break statement doesn't work, – JChat Jun 28 '19 at 22:41

1 Answers1

1

It may be a problem with nested loops, as covered by this answer. They suggest using return, but then your loop would need to be written as a function. If that doesn't appeal you could try using various levels of break statements as shown in some of the answers. Using the for, else construction (explained here), I think your code would look like the following

for e in range(NUM_EPOCHS):
    en_initial_states = encoder.init_states(BATCH_SIZE)

    for batch, (source_seq, target_seq_in, target_seq_out) in enumerate(dataset.take(-1)):
        loss = train_step(source_seq, target_seq_in,
                          target_seq_out, en_initial_states)

        if batch % 100 == 0:
                print('Epoch {} Batch {} Loss {:.4f}'.format(
                    e + 1, batch, loss.numpy()))


    try:
        test_target_text,net_words = predict()
    except Exception:
      continue

    if loss <=0.0001:
       break
else:
    continue ###executed if inner loop did NOT break
break  ###executed if inner loop DID break
Novice
  • 855
  • 8
  • 17