시작하기무료로 시작하기

문장 패딩하기

이제 sents2seqs()라는 함수를 구현해 보겠습니다. 이 함수는 이후 신경 기계 번역(NMT) 모델이 허용하는 형식으로 데이터를 편리하게 변환하는 데 사용돼요. sents2seqs()는 문장 문자열의 리스트를 받아서,

  • 문장을 ID 시퀀스 리스트로 변환하고,
  • 모든 문장의 길이가 같도록 패딩하며,
  • 선택적으로 ID를 원-핫 벡터로 변환합니다.

이미 학습된 Tokenizeren_tok가 제공되어 있습니다. 또 하나 참고할 점은 sents2seqs() 함수를 구현할 때 사용되지 않는 인수 input_type이 보인다는 것입니다. 이후에 이 input_type은 시퀀스 길이와 어휘 크기처럼 언어에 따라 달라지는 매개변수를 변경하는 데 사용됩니다.

이 연습은 강의의 일부입니다

Keras로 배우는 Machine Translation

강의 보기

연습 안내

  • en_tok Tokenizer를 사용해 sentences를 시퀀스로 변환하세요.
  • 시퀀스를 지정된 패딩 유형 pad_type으로 고정 길이 en_len에 맞춰 패딩하고, 잘림은 post로 사용하세요.
  • to_categorical() 함수를 사용해 preproc_text 단어 ID를 길이 en_vocab의 원-핫 벡터로 변환하세요.
  • sents2seqs() 메서드를 사용해 sentencepre 패딩으로 패딩된 시퀀스로 변환하세요.

실습형 인터랙티브 연습

이 예제를 이 샘플 코드를 완성하여 풀어보세요.

from tensorflow.keras.preprocessing.sequence import pad_sequences
from tensorflow.keras.utils import to_categorical

def sents2seqs(input_type, sentences, onehot=False, pad_type='post'):
	# Convert sentences to sequences      
    encoded_text = ____.____(sentences)
    # Pad sentences to en_len
    preproc_text = ____(____, padding=____, truncating=____, maxlen=____)
    if onehot:
		# Convert the word IDs to onehot vectors
        preproc_text = ____(____, num_classes=____)
    return preproc_text
sentence = 'she likes grapefruit , peaches , and lemons .'  
# Convert a sentence to sequence by pre-padding the sentence
pad_seq = sents2seqs('source', [____], pad_type=____)
코드 편집 및 실행