[Tensorflow] 3. Natural Language Processing in TensorFlow (3 week Sequence models) : programming (2)

gunny·2024년 3월 20일
0
post-thumbnail

[Tensorflow] 3. Natural Language Processing in TensorFlow (3 week Sequence models) : programming (2)

Multiple LSTM

  • 여기서는 단일 LSTM이 아니라 여러 LSTM 레이어를 사용하여 모델을 구축해본다.
    데이터는 imdb_reviews/subwords8k 를 사용한다.

[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
  • BATCH_SIZE를 256로 늘려 학습 속도를 높였다.
    강의에서 사용한 값의 배치사이즈는 64 이다.

[2] Build and Compile the Model

  • Sequential 모델에 다른 LSTM 레이어를 추가하고 return_sequences 플래그를 True로 활성화하면 다중 레이어 LSTM 모델을 구축할 수 있다. 이는 LSTM 레이어가 시퀀스 입력을 예상하므로 이전 레이어도 LSTM인 경우 시퀀스도 출력해야 하기 때문이다.
  • return_sequences가 True이면 출력 차원이 3차원(batch_size, timesteps, features)로 나타난다.

먼저, 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")
profile
꿈꾸는 것도 개발처럼 깊게

0개의 댓글

관련 채용 정보