| 438 | |
| 439 | |
| 440 | def decode_sequence(input_seq): |
| 441 | # Encode the input as state vectors. |
| 442 | enc_out = encoder_model.predict(input_seq) |
| 443 | |
| 444 | # Generate empty target sequence of length 1. |
| 445 | target_seq = np.zeros((1, 1)) |
| 446 | |
| 447 | # Populate the first character of target sequence with the start character. |
| 448 | # NOTE: tokenizer lower-cases all words |
| 449 | target_seq[0, 0] = word2idx_outputs['<sos>'] |
| 450 | |
| 451 | # if we get this we break |
| 452 | eos = word2idx_outputs['<eos>'] |
| 453 | |
| 454 | |
| 455 | # [s, c] will be updated in each loop iteration |
| 456 | s = np.zeros((1, LATENT_DIM_DECODER)) |
| 457 | c = np.zeros((1, LATENT_DIM_DECODER)) |
| 458 | |
| 459 | |
| 460 | # Create the translation |
| 461 | output_sentence = [] |
| 462 | for _ in range(max_len_target): |
| 463 | o, s, c = decoder_model.predict([target_seq, enc_out, s, c]) |
| 464 | |
| 465 | |
| 466 | # Get next word |
| 467 | idx = np.argmax(o.flatten()) |
| 468 | |
| 469 | # End sentence of EOS |
| 470 | if eos == idx: |
| 471 | break |
| 472 | |
| 473 | word = '' |
| 474 | if idx > 0: |
| 475 | word = idx2word_trans[idx] |
| 476 | output_sentence.append(word) |
| 477 | |
| 478 | # Update the decoder input |
| 479 | # which is just the word just generated |
| 480 | target_seq[0, 0] = idx |
| 481 | |
| 482 | return ' '.join(output_sentence) |
| 483 | |
| 484 | |
| 485 | |