[1] Download and prepare the dataset
import tensorflow_datasets as tfds
# Download the subword encoded pretokenized dataset
dataset, info = tfds.load('imdb_reviews/subwords8k', with_info=True, as_supervised=True)
# Get the tokenizer
tokenizer = info.features['text'].encoder
[2] Build and Compile the Model
먼저, Bidirctional LSTM의 return_sequences=True 에 대한 차이를 비교해보자.
import tensorflow as tf
import numpy as np
random_input = np.random.rand(1, 20, 16)
print(random_input.shape)
# output
(1, 20, 16)
random 라이브러리를 사용해서 (1,20,16) 의 형태를 갖는 random_input 변수를 초기화하였다.
그리고, 단일 lstm 레이어에 해당 random_input을 넣어봤다.
lstm = tf.keras.layers.LSTM(8)
result = lstm(random_input)
print(result)
print(result.shape)
# output
tf.Tensor(
[[-0.49086204 0.27177894 0.22378732 0.00281961 -0.3560892 0.34316784
0.04769999 -0.22337544]], shape=(1, 8), dtype=float32)
(1, 8)
레이어 아웃풋 형태가 (1,8) 로 나온 것을 볼 수 있다.
반면에 lstm에 return_sequences=True를 둔다면,
lstm_rs = tf.keras.layers.LSTM(8, return_sequences=True)
result = lstm_rs(random_input)
print(result.shape)
# output
(1,20,8)
LSTM의 unit수인 8과 함께 넣어줬던 (배치사이즈, 타임스텝, 피처) 의 형태로 (1,20,8)로 리턴된 것을 볼 수 있다.
이를 기반으로 아래 모델을 구축해본다.
model = tf.keras.models.Sequential([
tf.keras.layers.Embedding(tokenizer.vocab_size, 64),
tf.keras.layers.Bidirectional(tf.keras.layers.LSTM(64, return_sequences=True)),
tf.keras.layers.Bidirectional(tf.keras.layers.LSTM(32)),
tf.keras.layers.Dense(64, activation='relu'),
tf.keras.layers.Dense(1, activation='sigmoid')
])
model.compile(loss='binary_crossentropy',
optimizer='adam',
metrics=['accuracy'])
model.summary()
다음으로 모델을 epochs=10을 주어 학습한다.
history = model.fit(train_dataset,
epochs=10,
validation_data = test_dataset)
학습 한 결과를 플로팅해본다.
import matplotlib.pyplot as plt
# Plot utility
def plot_graphs(history, string):
plt.plot(history.history[string])
plt.plot(history.history['val_'+string])
plt.xlabel("Epochs")
plt.ylabel(string)
plt.legend([string, 'val_'+string])
plt.show()
# Plot the accuracy and results
plot_graphs(history, "accuracy")
plot_graphs(history, "loss")