본문 바로가기
DNN with Keras/Transfer Learning

Transfer Learning for NLP with Keras

by goatlab 2024. 2. 13.
728x90
반응형
SMALL

Transfer Learning for NLP with Keras

 

 

일반적으로 자연어 처리 (NLP)는 전이 학습을 사용한다. 단어 임베딩은 네트워크 레이어가 단어를 벡터에 매핑하는 NLP에서 전이 학습의 일반적인 수단다. 이러한 임베딩을 학습하기 위해 대규모 텍스트 말뭉치에 대해 신경망을 훈련시킨다. 

 

단어 임베딩을 사용하여 감정 분석을 수행한다. 특히, 텍스트 샘플이 긍정적인 어조로 말하고 있는지 부정적인 어조로 말하고 있는지 분류해 본다.

 

미리 학습된 모델을 TensorFlow에 쉽게 로드할 수 있는 TensorFlow Hub를 사용한다. 다음 명령을 사용하여 TensorHub를 설치한다.

 

!pip install tensorflow_hub

 

또한, 다음 명령으로 설치할 수 있는 TensorFlow 데이터세트를 설치해야 한다.

 

!pip install tensorflow_datasets

 

영화 리뷰는 감정 분석을 위한 좋은 학습 데이터 소스이다. 이러한 리뷰는 텍스트로 작성되며, 사용자는 별점을 부여하여 시청자가 영화에 대해 긍정적인 경험을 했는지 부정적인 경험을 했는지를 나타낸다. 인터넷 영화 데이터베이스 (IMDB) 리뷰 데이터 세트를 로드한다.

 

import tensorflow as tf
import tensorflow_hub as hub
import tensorflow_datasets as tfds

train_data, test_data = tfds.load(name="imdb_reviews", split=["train", "test"], batch_size=-1, as_supervised=True)
train_examples, train_labels = tfds.as_numpy(train_data)
test_examples, test_labels = tfds.as_numpy(test_data)

 

미리 학습된 임베딩 모델인 gnews-swivel-20dim을 로드한다. Google은 이 네트워크를 GNEWS 데이터로 학습시켰으며 원시 텍스트를 벡터로 변환할 수 있다.

 

model = "https://tfhub.dev/google/tf2-preview/gnews-swivel-20dim/1"
hub_layer = hub.KerasLayer(model, output_shape=[20], input_shape=[], dtype=tf.string, trainable=True)

 

다음 코드는 세 개의 영화 리뷰를 표시한다. 이 디스플레이를 통해 실제 데이터를 볼 수 있다.

 

train_examples[:3]
array([b"This was an absolutely terrible movie. Don't be lured in by Christopher Walken or Michael Ironside. Both are great actors, but this must simply be their worst role in history. Even their great acting could not redeem this movie's ridiculous storyline. This movie is an early nineties US propaganda piece. The most pathetic scenes were those when the Columbian rebels were making their cases for revolutions. Maria Conchita Alonso appeared phony, and her pseudo-love affair with Walken was nothing but a pathetic emotional plug in a movie that was devoid of any real meaning. I am disappointed that there are movies like this, ruining actor's like Christopher Walken's good name. I could barely sit through it.",
       b'I have been known to fall asleep during films, but this is usually due to a combination of things including, really tired, being warm and comfortable on the sette and having just eaten a lot. However on this occasion I fell asleep because the film was rubbish. The plot development was constant. Constantly slow and boring. Things seemed to happen, but with no explanation of what was causing them or why. I admit, I may have missed part of the film, but i watched the majority of it and everything just seemed to happen of its own accord without any real concern for anything else. I cant recommend this film at all.',
       b'Mann photographs the Alberta Rocky Mountains in a superb fashion, and Jimmy Stewart and Walter Brennan give enjoyable performances as they always seem to do. <br /><br />But come on Hollywood - a Mountie telling the people of Dawson City, Yukon to elect themselves a marshal (yes a marshal!) and to enforce the law themselves, then gunfighters battling it out on the streets for control of the town? <br /><br />Nothing even remotely resembling that happened on the Canadian side of the border during the Klondike gold rush. Mr. Mann and company appear to have mistaken Dawson City for Deadwood, the Canadian North for the American Wild West.<br /><br />Canadian viewers be prepared for a Reefer Madness type of enjoyable howl with this ludicrous plot, or, to shake your head in disgust.'],
      dtype=object)

 

임베딩 레이어는 각각을 20개의 숫자 벡터로 변환하여 신경망이 실제 단어 대신 입력으로 받을 수 있다.

 

hub_layer(train_examples[:3])
<tf.Tensor: shape=(3, 20), dtype=float32, numpy=
array([[ 1.765786  , -3.882232  ,  3.9134233 , -1.5557289 , -3.3362343 ,
        -1.7357955 , -1.9954445 ,  1.2989551 ,  5.081598  , -1.1041286 ,
        -2.0503852 , -0.72675157, -0.65675956,  0.24436149, -3.7208383 ,
         2.0954835 ,  2.2969332 , -2.0689783 , -2.9489717 , -1.1315987 ],
       [ 1.8804485 , -2.5852382 ,  3.4066997 ,  1.0982676 , -4.056685  ,
        -4.891284  , -2.785554  ,  1.3874227 ,  3.8476458 , -0.9256538 ,
        -1.896706  ,  1.2113281 ,  0.11474707,  0.76209456, -4.8791065 ,
         2.906149  ,  4.7087674 , -2.3652055 , -3.5015898 , -1.6390051 ],
       [ 0.71152234, -0.6353217 ,  1.7385626 , -1.1168286 , -0.5451594 ,
        -1.1808156 ,  0.09504455,  1.4653089 ,  0.66059524,  0.79308075,
        -2.2268345 ,  0.07446612, -1.4075904 , -0.70645386, -1.907037  ,
         1.4419787 ,  1.9551861 , -0.42660055, -2.8022065 ,  0.43727064]],
      dtype=float32)>

 

영화 리뷰를 긍정 또는 부정으로 분류하기 위해 추가 레이어를 추가한다.

 

model = tf.keras.Sequential()
model.add(hub_layer)
model.add(tf.keras.layers.Dense(16, activation='relu'))
model.add(tf.keras.layers.Dense(1, activation='sigmoid'))
model.summary()

 

이제 신경망을 컴파일할 준비가 되었다. 이 어플리케이션에서는 이진 분류를 위해 아담 훈련 방법을 사용한다. 또한, 나중에 쉽게 다시 시작할 수 있도록 초기 무작위 가중치를 저장한다.

 

model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])
init_weights = model.get_weights()

 

피팅 전에 학습 데이터를 학습 세트와 검증 세트로 분할한다.

 

x_val = train_examples[:10000]
partial_x_train = train_examples[10000:]
y_val = train_labels[:10000]
partial_y_train = train_labels[10000:]

 

이제, 신경망을 맞출 수 있다. 이 피팅은 40회 동안 실행되며 훈련 세트에서 측정한 신경망의 효과를 평가할 수 있다.

 

history = model.fit(partial_x_train,
                    partial_y_train,
                    epochs=40,
                    batch_size=512,
                    validation_data=(x_val, y_val),
                    verbose=1)
728x90
반응형
LIST