번역 생성하기
이제 Teacher Forcing으로 학습한 추론 모델을 사용해 프랑스어 번역을 생성해 보겠습니다.
이 모델(nmt_tf)은 10만 개 문장으로 50 epoch 동안 학습되었으며, 3만 5천 개 이상의 검증 세트에서 약 98% 정확도를 달성했습니다. 학습된 모델을 불러와야 하므로 이 연습 문제의 초기화에 시간이 조금 더 걸릴 수 있어요. sents2seqs() 함수가 제공됩니다. 또한 다음의 두 가지 새 함수도 제공됩니다:
word2onehot(tokenizer, word, vocab_size)는 다음을 인자로 받습니다:
- tokenizer - Keras의
Tokenizer객체 - word - 어휘에 있는 단어를 나타내는 문자열(예:
'apple') - vocab_size - 어휘 크기
probs2word(probs, tok)는 다음을 인자로 받습니다:
- probs - 모델 출력으로, 형태는
[1,<French Vocab Size>] - tok - Keras의
Tokenizer객체
이 함수들의 소스 코드는 콘솔에서 print(inspect.getsource(word2onehot)) 및 print(inspect.getsource(probs2word))를 입력해 확인할 수 있습니다.
이 연습은 강의의 일부입니다
Keras로 배우는 Machine Translation
연습 안내
- 인코더로 초기 디코더 상태(
de_s_t)를 예측하세요. - 이전 예측값(출력)과 이전 상태를 입력으로 사용해 디코더에서 출력과 새 상태를 예측하세요. 재귀적으로 새 상태를 생성해야 함을 기억하세요.
probs2word()함수를 사용해 확률 출력에서 단어 문자열을 얻으세요.word2onehot()함수를 사용해 그 단어 문자열을 원-핫 시퀀스로 변환하세요.
실습형 인터랙티브 연습
이 예제를 이 샘플 코드를 완성하여 풀어보세요.
en_sent = ['the united states is sometimes chilly during december , but it is sometimes freezing in june .']
print('English: {}'.format(en_sent))
en_seq = sents2seqs('source', en_sent, onehot=True, reverse=True)
# Predict the initial decoder state with the encoder
de_s_t = ____.predict(____)
de_seq = word2onehot(fr_tok, 'sos', fr_vocab)
fr_sent = ''
for i in range(fr_len):
# Predict from the decoder and recursively assign the new state to de_s_t
de_prob, ____ = ____.predict([____,____])
# Get the word from the probability output using probs2word
de_w = probs2word(____, fr_tok)
# Convert the word to a onehot sequence using word2onehot
de_seq = word2onehot(fr_tok, ____, fr_vocab)
if de_w == 'eos': break
fr_sent += de_w + ' '
print("French (Ours): {}".format(fr_sent))
print("French (Google Translate): les etats-unis sont parfois froids en décembre, mais parfois gelés en juin")