1: 내 친구들은 영화를 좋아하지만 나는 그렇지 않아요. --> 부정적인 리뷰
2: 내 친구들은 영화를 좋아하지 않지만 나는 좋아해요. --> 긍정적인 리뷰
가장 먼저 살펴볼 계층은 LSTM 이다. 간단히 말해서, 현재 시간 단계의 상태를 계산하고 이 상태도 업데이트되는 다음 시간 단계로 전달한다.
이 프로세스는 출력 계산이 모든 이전 상태의 영향을 받는 최종 시간 단계까지 반복된다. 뿐만 아니라, 양방향으로 구성할 수 있으므로 이후 단어와 이전 단어의 관계를 얻을 수 있다.
이러한 레이어의 복잡성을 구현하는 Tensorflow의 API를 활용할 수 있다. 이렇게 하면 모델에 연결하기만 하면 된다.
[1] Download the dataset & 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
그런 다음 학습 및 테스트 분할을 가져오고 패딩된 배치를 생성한다.
여기서는 학습 속도를 높이기 위해 배치 크기를 늘렸고, 256개를 사용하게 되며 에포크당 훈련하는 데 대략 1분 정도 소요된다.
강의에서는 에포크당 약 4분이 소요되는 16개를 사용했다.
BUFFER_SIZE = 10000
BATCH_SIZE = 256
train_data, test_data = dataset['train'], dataset['test']
train_dataset = train_data.shuffle(BUFFER_SIZE)
train_dataset = train_dataset.padded_batch(BATCH_SIZE)
test_datset = test_data.padded_batch(BATCH_SIZE)
print(train_dataset)
print(test_datset)
# output
<_PaddedBatchDataset element_spec=(TensorSpec(shape=(None, None), dtype=tf.int64, name=None), TensorSpec(shape=(None,), dtype=tf.int64, name=None))>
<_PaddedBatchDataset element_spec=(TensorSpec(shape=(None, None), dtype=tf.int64, name=None), TensorSpec(shape=(None,), dtype=tf.int64, name=None))>
[2] Build and compile the model
import tensorflow as tf
model = tf.keras.models.Sequential([
tf.keras.layers.Embedding(tokenizer.vocab_size, 64),
tf.keras.layers.Bidirectional(tf.keras.layers.LSTM(64)),
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()
history = model.fit(train_dataset, epochs=10, validation_data=test_dataset)
[3] Visualization
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")
여기서는 LSTM 레이어를 사용하여 순환 신경망을 구축하는 방법을 살펴봤다.
단일 LSTM 레이어만 사용했지만 이를 쌓아서 더 깊은 네트워크를 구축할 수도 있다.