Keras 전처리
Keras에서 두 번째로 중요한 모듈은 keras.preprocessing입니다. 이 모듈의 핵심 구성요소와 함수를 사용해 원시 데이터를 올바른 입력 형태로 준비하는 방법을 배워 봅니다. Keras는 앞에서 학습한 사전(dictionary) 방식의 대안을 제공해요.
keras.preprocessing.text.Tokenizer 모듈을 사용해 .fit_on_texts() 메서드로 단어 사전을 만들고, .texts_to_sequences() 메서드로 각 단어의 사전 내 인덱스를 나타내는 숫자 id 시퀀스로 텍스트를 변환하세요.
그다음 keras.preprocessing.sequence의 .pad_sequences() 함수를 사용해 짧은 텍스트에는 0을 추가하고 긴 텍스트는 잘라서 모든 시퀀스의 길이를 동일하게 맞추세요(모델에 필요).
이 연습은 강의의 일부입니다
Keras로 배우는 언어 모델링을 위한 순환 신경망(RNN)
연습 안내
- 관련 모듈에서
Tokenizer와pad_sequences를 임포트하세요. texts에 저장된 샘플 데이터로tokenizer객체를 학습(fit)하세요..texts_to_sequences()메서드를 사용해 텍스트를 숫자 인덱스 시퀀스로 변환하세요.- 패딩을 적용해 텍스트 길이를 동일하게 맞추세요.
실습형 인터랙티브 연습
이 예제를 이 샘플 코드를 완성하여 풀어보세요.
# Import relevant classes/functions
from tensorflow.keras.preprocessing.text import ____
from tensorflow.keras.preprocessing.sequence import ____
# Build the dictionary of indexes
tokenizer = Tokenizer()
tokenizer.fit_on_texts(____)
# Change texts into sequence of indexes
texts_numeric = tokenizer.____(texts)
print("Number of words in the sample texts: ({0}, {1})".format(len(texts_numeric[0]), len(texts_numeric[1])))
# Pad the sequences
texts_pad = ____(texts_numeric, 60)
print("Now the texts have fixed length: 60. Let's see the first one: \n{0}".format(texts_pad[0]))