Project 0) Naver Sentimental Classification_baseline

Jacob Kim·2024년 2월 1일
0

Naver Project Week4

목록 보기
15/16

Sentiment Classification

Task

  • 네이버에서 영화평을 가지고 positive/negative인지 구분해보자.
  • 데이터 불러오기를 제외한 딥러닝 트레이닝 과정을 직접 구현해보는 것이 목표 입니다.

Dataset

  • Naver sentiment movie corpus v1.0

Base code

  • Dataset: train, val, test로 split
  • Input data shape: (batch_size, max_sequence_length)
  • Output data shape: (batch_size, 1)
  • Training
  • Evaluation

Try some techniques

  • Training-epochs 조절
  • Change model architectures (Custom model)
    • Use another cells (LSTM, GRU, etc.)
    • Use dropout layers
  • Embedding size 조절
    • 또는 one-hot vector로 학습
  • Number of words in the vocabulary 변화
  • pad 옵션 변화
  • Data augmentation (if possible)

Import modules

from google.colab import drive
drive.mount('/content/drive')
#Drive already mounted at /content/drive; to attempt to forcibly remount, call drive.mount("/content/drive", force_remount=True).
!pip install sentencepiece
#Requirement already satisfied: sentencepiece in /usr/local/lib/python3.10/dist-packages (0.1.99)
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals

import os
import time
import shutil
import tarfile

import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
from IPython.display import clear_output
import urllib.request

import pandas as pd

import tensorflow as tf
from tensorflow.keras.preprocessing.sequence import pad_sequences

import sentencepiece as spm

from collections import Counter, defaultdict

Load Data

  • ratings_train.txt: 훈련용으로 사용되는 15만 개의 리뷰
  • ratings_test.txt: 테스트용으로 보류된 5만 개의 리뷰
  • 모든 리뷰는 140자 이내입니다
  • 각 감정 클래스는 동등하게 샘플링되었습니다 (즉, 무작위 추측은 50%의 정확도를 보입니다)
  • 10만 개의 부정적 리뷰 (원래 1-4점의 리뷰)
  • 10만 개의 긍정적 리뷰 (원래 9-10점의 리뷰)
  • 중립적 리뷰 (원래 5-8점의 리뷰)는 제외되었습니다
urllib.request.urlretrieve("https://raw.githubusercontent.com/e9t/nsmc/master/ratings_train.txt", filename="ratings_train.txt")
urllib.request.urlretrieve("https://raw.githubusercontent.com/e9t/nsmc/master/ratings_test.txt", filename="ratings_test.txt")
#('ratings_test.txt', <http.client.HTTPMessage at 0x7e3df66e6260>)
train_data = pd.read_table('ratings_train.txt')
train_data = train_data.dropna()
test_data = pd.read_table('ratings_test.txt')
test_data = test_data.dropna()
train_data.head()

test_data.head()

Tokenizing

sp = spm.SentencePieceProcessor()
sp.load('/content/drive/MyDrive/dataset/naver_review/naver_review.model')  # 모델 경로 설정

# 토크나이저 함수 정의
def tokenizer(text):
    return sp.encode_as_pieces(#TODO)
for i, (line) in enumerate(#TODO):
    print(#TODO)
    print(sp.encode_as_pieces(#TODO))
    print(sp.encode_as_ids(#TODO))
    if i == 5:
        break
아 더빙.. 진짜 짜증나네요 목소리
['▁아', '▁더빙', '..', '▁진짜', '▁짜증나', '네요', '▁목소리']
[14, 1226, 7, 88, 2990, 55, 2393]...포스터보고 초딩영화줄....오버연기조차 가볍지 않구나
['▁흠', '...', '포스터', '보고', '▁초딩', '영화', '줄', '....', '오', '버', '연기', '조차', '▁가볍', '지', '▁않', '구나']
[1949, 16, 5829, 233, 1469, 10, 6601, 47, 6454, 6564, 355, 2103, 2338, 6387, 108, 508]
너무재밓었다그래서보는것을추천한다
['▁너무', '재', '밓', '었다', '그래서', '보는', '것을', '추천', '한다']
[39, 6416, 1, 164, 4556, 515, 1409, 2176, 367]
교도소 이야기구먼 ..솔직히 재미는 없다..평점 조정
['▁교', '도', '소', '▁이야기', '구', '먼', '▁..', '솔직히', '▁재미는', '▁없다', '..', '평점', '▁조', '정']
[729, 6392, 6487, 372, 6478, 6879, 516, 5346, 1686, 309, 7, 1187, 188, 6424]
사이몬페그의 익살스런 연기가 돋보였던 영화!스파이더맨에서 늙어보이기만 했던 커스틴 던스트가 너무나도 이뻐보였다
['▁사이', '몬', '페', '그', '의', '▁익', '살', '스런', '▁연기가', '▁돋보', '였던', '▁영화', '!', '스', '파이', '더', '맨', '에서', '▁늙', '어', '보이', '기만', '▁했던', '▁커', '스', '틴', '▁던', '스트', '가', '▁너무나도', '▁이뻐', '보', '였다']
[2855, 7223, 6958, 6415, 6400, 3665, 6598, 2275, 776, 1967, 2639, 11, 6409, 6418, 2182, 6470, 6720, 62, 2895, 6399, 2780, 1375, 3042, 1299, 6418, 7124, 3527, 692, 6391, 2677, 3827, 6398, 475]
막 걸음마 뗀 3세부터 초등학교 1학년생인 8살용영화.ㅋㅋㅋ...별반개도 아까움.
['▁막', '▁걸', '음', '마', '▁', '뗀', '▁3', '세', '부터', '▁초등', '학교', '▁1', '학년', '생', '인', '▁8', '살', '용', '영화', '.', 'ᄏᄏᄏ', '...', '별', '반', '개도', '▁아까움', '.']
[419, 519, 6436, 6427, 6371, 1, 34, 6512, 340, 2325, 979, 8, 3847, 6460, 6414, 15, 6598, 6510, 10, 6372, 472, 16, 6551, 6534, 1521, 2060, 6372]
eos_token = '[SEP]'
eos_id = sp.piece_to_id(eos_token)

print(f"토큰 '{eos_token}'의 ID: {eos_id}")
# 토큰 '[SEP]'의 ID: 4
sp.encode_as_ids(['[EOS]'])
[[4379, 7127, 6566, 6866, 7344]]
train_text = []
for i, line in enumerate(#TODO):
    # sp.encode_as_ids(line)의 결과를 TensorFlow 텐서로 변환
    train_text.append(tf.convert_to_tensor(sp.encode_as_ids(line), dtype=tf.int32))

test_text = []
for i, line in enumerate(#TODO):
    test_text.append(tf.convert_to_tensor(sp.encode_as_ids(line), dtype=tf.int32))
print(len(train_text), len(test_text))
# 149995 49997

Padding and truncating data using pad sequences

  • 전부 길이가 다른 리뷰들의 길이를 통일해주자
batch_size = 32
max_seq_length = 256
train_data_pad = pad_sequences(#TODO)
test_data_pad = pad_sequences(#TODO)

print(train_data_pad.shape, test_data_pad.shape)
# (149995, 140) (49997, 140)

Dataset 구성

batch_size = 32

# for train
train_dataset = tf.data.Dataset.from_tensor_slices((#TODO))
train_dataset = train_dataset.shuffle(10000).repeat().batch(batch_size=batch_size)
print(train_dataset)

# for test
test_dataset = tf.data.Dataset.from_tensor_slices((#TODO))
test_dataset = test_dataset.batch(batch_size=batch_size)
print(test_dataset)
#<_BatchDataset element_spec=(TensorSpec(shape=(None, 140), dtype=tf.int32, name=None), TensorSpec(shape=(None,), dtype=tf.int64, name=None))>
#<_BatchDataset element_spec=(TensorSpec(shape=(None, 140), dtype=tf.int32, name=None), TensorSpec(shape=(None,), dtype=tf.int64, name=None))>

Build the model

Setup hyper-parameters

kargs = {'model_name': 'BERT',
         'num_layers': #TODO,
         'd_model': #TODO,
         'num_heads': #TODO,
         'dff': #TODO,
         'input_vocab_size': sp.get_piece_size(),
         'target_vocab_size': sp.get_piece_size(),
         'maximum_position_encoding': #TODO,
         'segment_encoding': 2,
         'end_token_idx': sp.piece_to_id('[EOS]'),
         'rate': 0.1
        }
def get_angles(pos, i, d_model):
    angle_rates = 1 / np.power(10000, (2 * i//2) / np.float32(d_model))
    return pos * angle_rates
def positional_encoding(position, d_model):
    angle_rads = get_angles(np.arange(position)[:, np.newaxis],
                          np.arange(d_model)[np.newaxis, :],
                          d_model)

    print(angle_rads)

    # apply sin to even indices in the array; 2i
    angle_rads[:, 0::2] = np.sin(angle_rads[:, 0::2])

    # apply cos to odd indices in the array; 2i+1
    angle_rads[:, 1::2] = np.cos(angle_rads[:, 1::2])

    pos_encoding = angle_rads[np.newaxis, ...]

    return tf.cast(pos_encoding, dtype=tf.float32)
def scaled_dot_product_attention(q, k, v, mask):
    """Calculate the attention weights.
    q, k, v must have matching leading dimensions.
    k, v must have matching penultimate dimension, i.e.: seq_len_k = seq_len_v.
    The mask has different shapes depending on its type(padding or look ahead)
    but it must be broadcastable for addition.

    Args:
    q: query shape == (..., seq_len_q, depth)
    k: key shape == (..., seq_len_k, depth)
    v: value shape == (..., seq_len_v, depth_v)
    mask: Float tensor with shape broadcastable
          to (..., seq_len_q, seq_len_k). Defaults to None.

    Returns:
    output, attention_weights
    """

    matmul_qk = tf.matmul(q, k, transpose_b=True)  # (..., seq_len_q, seq_len_k)

    # scale matmul_qk
    dk = tf.cast(tf.shape(k)[-1], tf.float32)
    scaled_attention_logits = matmul_qk / tf.math.sqrt(dk)

    # add the mask to the scaled tensor.
    if mask is not None:
        scaled_attention_logits += (mask * -1e9)

    # softmax is normalized on the last axis (seq_len_k) so that the scores
    # add up to 1.
    attention_weights = tf.nn.softmax(scaled_attention_logits, axis=-1)  # (..., seq_len_q, seq_len_k)

    output = tf.matmul(attention_weights, v)  # (..., seq_len_q, depth_v)

    return output, attention_weights
class MultiHeadAttention(tf.keras.layers.Layer):
    def __init__(self, **kargs):
        super(MultiHeadAttention, self).__init__()
        self.num_heads = kargs['num_heads']
        self.d_model = kargs['d_model']

        assert self.d_model % self.num_heads == 0

        self.depth = self.d_model // self.num_heads

        self.wq = tf.keras.layers.Dense(kargs['d_model'])
        self.wk = tf.keras.layers.Dense(kargs['d_model'])
        self.wv = tf.keras.layers.Dense(kargs['d_model'])

        self.dense = tf.keras.layers.Dense(kargs['d_model'])

    def split_heads(self, x, batch_size):
        """Split the last dimension into (num_heads, depth).
        Transpose the result such that the shape is (batch_size, num_heads, seq_len, depth)
        """
        x = tf.reshape(x, (batch_size, -1, self.num_heads, self.depth))
        return tf.transpose(x, perm=[0, 2, 1, 3])

    def call(self, v, k, q, mask):
        batch_size = tf.shape(q)[0]

        q = self.wq(q)  # (batch_size, seq_len, d_model)
        k = self.wk(k)  # (batch_size, seq_len, d_model)
        v = self.wv(v)  # (batch_size, seq_len, d_model)

        q = self.split_heads(q, batch_size)  # (batch_size, num_heads, seq_len_q, depth)
        k = self.split_heads(k, batch_size)  # (batch_size, num_heads, seq_len_k, depth)
        v = self.split_heads(v, batch_size)  # (batch_size, num_heads, seq_len_v, depth)

        # scaled_attention.shape == (batch_size, num_heads, seq_len_q, depth)
        # attention_weights.shape == (batch_size, num_heads, seq_len_q, seq_len_k)
        scaled_attention, attention_weights = scaled_dot_product_attention(
            q, k, v, mask)

        scaled_attention = tf.transpose(scaled_attention, perm=[0, 2, 1, 3])  # (batch_size, seq_len_q, num_heads, depth)

        concat_attention = tf.reshape(scaled_attention,
                                      (batch_size, -1, self.d_model))  # (batch_size, seq_len_q, d_model)

        output = self.dense(concat_attention)  # (batch_size, seq_len_q, d_model)

        return output, attention_weights

def point_wise_feed_forward_network(**kargs):
    return tf.keras.Sequential([
            tf.keras.layers.Conv1D(kargs['dff'], 1, activation='relu'),  # (batch_size, seq_len, dff)
            tf.keras.layers.Conv1D(kargs['d_model'], 1)  # (batch_size, seq_len, d_model)
        ])
class EncoderLayer(tf.keras.layers.Layer):
    def __init__(self, **kargs):
        super(EncoderLayer, self).__init__()

        self.mha = MultiHeadAttention(**kargs)

        self.ffn = point_wise_feed_forward_network(**kargs)
        self.layernorm1 = tf.keras.layers.LayerNormalization(epsilon=1e-6)
        self.layernorm2 = tf.keras.layers.LayerNormalization(epsilon=1e-6)

        self.dropout1 = tf.keras.layers.Dropout(kargs['rate'])
        self.dropout2 = tf.keras.layers.Dropout(kargs['rate'])

    @tf.function
    def call(self, x, mask):
        attn_output, _ = self.mha(x, x, x, mask)  # (batch_size, input_seq_len, d_model)
        attn_output = self.dropout1(attn_output)
        out1 = self.layernorm1(x + attn_output)  # (batch_size, input_seq_len, d_model)

        ffn_output = self.ffn(out1)  # (batch_size, input_seq_len, d_model)
        ffn_output = self.dropout2(ffn_output)
        out2 = self.layernorm2(out1 + ffn_output)  # (batch_size, input_seq_len, d_model)

        return out2, attn_output
class Encoder(tf.keras.layers.Layer):
    def __init__(self, **kargs):
        super(Encoder, self).__init__()

        self.d_model = kargs['d_model']
        self.num_layers = kargs['num_layers']

        self.embedding = tf.keras.layers.Embedding(kargs['input_vocab_size'],
                                                   self.d_model)
        self.seg_encoding = tf.keras.layers.Embedding(kargs['segment_encoding'],
                                                   self.d_model)
        self.pos_encoding = positional_encoding(kargs['maximum_position_encoding'],
                                                     self.d_model)

        self.enc_layers = [EncoderLayer(**kargs)
                           for _ in range(self.num_layers)]

        self.dropout = tf.keras.layers.Dropout(kargs['rate'])

    def get_seg_data(self, data, token_id=4):
        token_found = tf.cumsum(tf.cast(data == token_id, tf.int32), axis=1)
        modified_data = tf.cast(token_found >= 1, tf.int32)

        return modified_data

    def call(self, x, mask):
        attn = None
        seq_len = tf.shape(x)[1]
        seg_data = self.get_seg_data(x)

        # adding embedding and position encoding.
        x = self.embedding(x)  # (batch_size, input_seq_len, d_model)
        x *= tf.math.sqrt(tf.cast(self.d_model, tf.float32))
        x += self.pos_encoding[:, :seq_len, :]

        x += self.seg_encoding(seg_data)

        x = self.dropout(x)

        for i in range(self.num_layers):
            x, attn = self.enc_layers[i](x, mask)

        return x, attn  # (batch_size, input_seq_len, d_model)
class BERT(tf.keras.Model):
    def __init__(self, **kargs):
        super(BERT, self).__init__(name=kargs['model_name'])
        self.end_token_idx = kargs['end_token_idx']
        self.encoder = Encoder(**kargs)
        self.outputs_layer = tf.keras.layers.Dense(kargs['d_model'],
                                                   activation='gelu')

        self.final_layer = tf.keras.layers.Dense(2)

    def create_padding_mask(self, seq):
        seq = tf.cast(tf.math.equal(seq, 0), tf.float32)

        # add extra dimensions to add the padding
        # to the attention logits.
        return seq[:, tf.newaxis, tf.newaxis, :]  # (batch_size, 1, 1, seq_len)

    def call(self, x):
        inp = x
        mask = self.create_padding_mask(inp)

        enc_output, attn = self.encoder(inp, mask)  # (batch_size, inp_seq_len, d_model)
        enc_output = self.outputs_layer(enc_output)  # (batch_size, inp_seq_len, d_model)
        enc_output = tf.keras.layers.Flatten()(enc_output)  # (batch_size, inp_seq_len * d_model)
        final_output = self.final_layer(enc_output)  # (batch_size, 1)

        return final_output
model = BERT(**kargs)

Train the model

loss_object = tf.keras.losses.SparseCategoricalCrossentropy(
    from_logits=True, reduction='none')

train_accuracy = tf.keras.metrics.SparseCategoricalAccuracy(name='accuracy')

def loss(real, pred):
    mask = tf.math.logical_not(tf.math.equal(real, 0))
    loss_ = loss_object(real, pred)

    mask = tf.cast(mask, dtype=loss_.dtype)
    loss_ *= mask

    return tf.reduce_mean(loss_)

def accuracy(real, pred):
    mask = tf.math.logical_not(tf.math.equal(real, 0))
    mask = tf.expand_dims(tf.cast(mask, dtype=pred.dtype), axis=-1)
    pred *= mask
    acc = train_accuracy(real, pred)

    return tf.reduce_mean(acc)
model.compile(optimizer=tf.keras.optimizers.Adam(1e-4),
              loss=loss,
              metrics=[accuracy])
early_stopping_cb = tf.keras.callbacks.EarlyStopping(patience=10,
                                                     monitor='val_loss',
                                                     restore_best_weights=True,
                                                     verbose=1)
history = model.fit(train_dataset,
                    epochs=100,
                    validation_data=test_dataset,
                    steps_per_epoch=len(train_data_pad) // batch_size,
                    validation_steps=len(test_data_pad) // batch_size,
                    callbacks=[early_stopping_cb]
                    )
Epoch 1/100
4687/4687 [==============================] - 1636s 339ms/step - loss: 0.3489 - accuracy: 0.8337 - val_loss: 0.3489 - val_accuracy: 0.9038
Epoch 2/100
4687/4687 [==============================] - 1599s 341ms/step - loss: 0.3457 - accuracy: 0.9247 - val_loss: 0.3487 - val_accuracy: 0.9436
Epoch 3/100
4687/4687 [==============================] - 1597s 341ms/step - loss: 0.3456 - accuracy: 0.9546 - val_loss: 0.3487 - val_accuracy: 0.9623
Epoch 4/100
4687/4687 [==============================] - 1607s 343ms/step - loss: 0.3456 - accuracy: 0.9671 - val_loss: 0.3487 - val_accuracy: 0.9712
Epoch 5/100
4687/4687 [==============================] - 1577s 337ms/step - loss: 0.3456 - accuracy: 0.9743 - val_loss: 0.3487 - val_accuracy: 0.9769
Epoch 6/100
4687/4687 [==============================] - 1612s 344ms/step - loss: 0.3456 - accuracy: 0.9790 - val_loss: 0.3487 - val_accuracy: 0.9807
Epoch 7/100
4687/4687 [==============================] - 1607s 343ms/step - loss: 0.3456 - accuracy: 0.9822 - val_loss: 0.3486 - val_accuracy: 0.9835
Epoch 8/100
4687/4687 [==============================] - 1570s 335ms/step - loss: 0.3456 - accuracy: 0.9846 - val_loss: 0.3486 - val_accuracy: 0.9855
Epoch 9/100
4687/4687 [==============================] - 1602s 342ms/step - loss: 0.3456 - accuracy: 0.9863 - val_loss: 0.3487 - val_accuracy: 0.9871
Epoch 10/100
4687/4687 [==============================] - 1570s 335ms/step - loss: 0.3456 - accuracy: 0.9878 - val_loss: 0.3486 - val_accuracy: 0.9884
Epoch 11/100
4687/4687 [==============================] - 1600s 341ms/step - loss: 0.3456 - accuracy: 0.9890 - val_loss: 0.3486 - val_accuracy: 0.9895
Epoch 12/100
4687/4687 [==============================] - 1605s 342ms/step - loss: 0.3455 - accuracy: 0.9899 - val_loss: 0.3487 - val_accuracy: 0.9903
Epoch 13/100
4687/4687 [==============================] - 1569s 335ms/step - loss: 0.3456 - accuracy: 0.9907 - val_loss: 0.3487 - val_accuracy: 0.9911
Epoch 14/100
4687/4687 [==============================] - 1601s 341ms/step - loss: 0.3456 - accuracy: 0.9914 - val_loss: 0.3487 - val_accuracy: 0.9917
Epoch 15/100
4687/4687 [==============================] - 1577s 336ms/step - loss: 0.3456 - accuracy: 0.9920 - val_loss: 0.3487 - val_accuracy: 0.9923
Epoch 16/100
4358/4687 [==========================>...] - ETA: 1:38 - loss: 0.3457 - accuracy: 0.9925

Test the model

results = model.evaluate(test_dataset)
# loss
print("loss value: {:.3f}".format(results[0]))
# accuracy
print("accuracy value: {:.3f}".format(results[1]))
profile
AI, Information and Communication, Electronics, Computer Science, Bio, Algorithms

0개의 댓글

관련 채용 정보