์ผ๋ง์ ์ koBERT๋ก colab์์ ํ์ตํ์๋๋ฐ ์ด๋ป๊ฒ ๋ก์ปฌ์์ ์ฎ๊ฒจ์ผ ํ ์ง ๊ฐ์ด ์์กํ๋ค.
mxnet, glounnlp๋ฅผ ์ง์ ๋ค์ด๋ก๋ํ์ฌ ๋ผ์ด๋ธ๋ฌ๋ฆฌ์ ๋ฃ์ด์ฃผ์๋๋ฐ๋ ์๋๊ณ
vmware๋ฅผ ๊น์์ ๋ฆฌ๋ ์คํ๊ฒฝ์์ ํด๋ณด์๋๋ฐ๋ ์ ์๋์๋ค.
๊ทธ๋์ koBERT๋ ์์ฝ์ง๋ง ์ ์ ๋ชจ๋ธ๋ง ๋จ๊ฒจ๋๊ณ ๋ค๋ฅธ ๋ฐฉ๋ฒ์ผ๋ก ๋ก์ปฌ๋ก ํ์ต์ ์ํค๋ ค๊ณ ํ๋ค.
koBERT ๋ชจ๋ธ ํ์ตํ๊ธฐ์์ txtํ์ผ์ ๋ง๋ค์๋๋ฐ ๊ทธ๊ฒ์ ์ฌ์ฉํ๊ฒ ๋ค.
์ธ๊ณต์ง๋ฅ koBERT ๋ชจ๋ธ ํ์ต
์ถ์ฒ์์คํ ์ ์ฐ์ผ 'ํ๊ทธ'๋ฅผ ๋ฌ๊ธฐ ์ํด ๋ชจ๋ธ์ ํ๋ ์ ์ํ๊ณ ์๋ค. ๋ค๋ฅธ ๋ชจ๋ธ๋ค๋ ๋ง์ง๋ง koELECTRA์ ๊ธฐํ ๋ชจ๋ธ์ ๋ฐ์ดํฐ ์ ์ฒ๋ฆฌ๋ฅผ ๋ชจ๋ธ์ ๋ง๊ฒ ํด์ฃผ์ง ์์์ ๊ทธ๋ฐ๊ฐ ์ ํ๋๊ฐ ๋์ง ์์๋ค. ๊ทธ
beomcoder.tistory.com
0. ๋ฐ์ดํฐ ์ฒ๋ฆฌํ๊ธฐ
koBERT ๋ชจ๋ธ ํ์ตํ๊ธฐ์์ ํ๋ ๋ฐ์ดํฐ๋ฅผ ์ฒ๋ฆฌํ๋ ์ฝ๋์ด๋ค.
AIHUB์์ '์ฃผ์ ๋ณ ํ ์คํธ ์ผ์ ๋ํ ๋ฐ์ดํฐ'๋ฅผ ๋ค์ด๋ก๋ ๋ฐ์๋ค.
๊ทธ ์ค์์ ๋๋ jsonํ์์ผ๋ก ๋ ํ์ผ๋ง ์ฌ์ฉํ๋ค. ๋ณธ์ธ์ด ์ธ ๋ถ๋ถ์ ๊ฐ์ง๊ณ ์ฒ๋ฆฌํ๋ฉด ๋๋ค. ๋๋ ํด๋๋ฅผ vscode์ ๋ฃ์๋ค.
# aihub์ ๋ฐ์ดํฐ ์ค ์นดํ
๊ณ ๋ฆฌ๊ฐ '์๊ฑฐ๋์ ๋ฐ'์์ ๋์ด์ฐ๊ธฐ๋ฅผ ํ๊ฒ๊ณผ ์ํ๊ฒ์ด ๊ณต์กดํ์ฌ ์ฒ๋ฆฌํด์ค
category = { '์์๋ฃ': 0, '์ฃผ๊ฑฐ์ ์ํ': 1, '๊ตํต': 2, 'ํ์ฌ/์๋ฅด๋ฐ์ดํธ': 3, '๊ตฐ๋': 4, '๊ต์ก': 5, '๊ฐ์กฑ': 6, '์ฐ์ /๊ฒฐํผ': 7, '๋ฐ๋ ค๋๋ฌผ': 8, '์คํฌ์ธ /๋ ์ ': 9,
'๊ฒ์': 10, '์ฌํ': 11, '๊ณ์ /๋ ์จ': 12, '์ฌํ์ด์': 13, 'ํ ๊ตญ๊ฐ ์ด์': 14, '๋ฏธ์ฉ': 15, '๊ฑด๊ฐ': 16, '์๊ฑฐ๋์ ๋ฐ': 17, '์๊ฑฐ๋ ์ ๋ฐ': 17, '๋ฐฉ์ก/์ฐ์': 18,
'์ํ/๋งํ': 19 }
์นดํ ๊ณ ๋ฆฌ๋ aihub์์ ์นดํ ๊ณ ๋ฆฌ๋ฅผ ๊ทธ๋๋ก ๊ฐ์ง๊ณ ์๋๋ฐ ์ค๊ฐ์ ๋์ด์ฐ๊ธฐ๋ก ์ ํ์๋ ๋ถ๋ถ์ด ์์ด์
๊ทธ ๋ถ๋ถ์ ๋ฐ๋ก ๊ฐ์ ๋ฒํธ๋ก ์ฒ๋ฆฌํด์ฃผ์๋ค.
# AIHUB์์ ๊ฐ์ง๊ณ ์จ jsonํ์ผ์ text file๋ก ๋ณํํ๊ธฐ ์ํด txt file ์์ฑ
txt_file_names = ['train_data', 'valid_data']
for name in txt_file_names:
f = open(name+'.txt', 'w')
f.write('id\ttext\tlabel\n')
f.close()
train data์ valid data๋ฅผ ๋ค๋ฅด๊ฒ ์ฒ๋ฆฌํ๋ ค๊ณ 2๊ฐ๋ฅผ ๋ง๋ค์๋ค. ๋์ค์ pandas dataframe์ผ๋ก
์ปฌ๋ผ๊ฐ์ผ๋ก id, text, label์ผ๋ก ์ค์ ํด์ฃผ๋ ค๊ณ ํ ์คํธ ์ ์ผ ์์ค์ ์ ์ด์ฃผ์๋ค.
# txt๋ก ๋ง๋ ์ด์ ๋ ๋ค๋ฅธ ๊ณณ์์๋ ๋ฐ์ดํฐ๋ฅผ ์ฌ์ฉํ ์๋ ์๊ธฐ ๋๋ฌธ์ txtํ์ผ๋ก ๋ง๋ค์๋ค.
import os, json
dirs = ['dataset\\1.Training\\๋ผ๋ฒจ๋ง๋ฐ์ดํฐ', 'dataset\\2.Validation\\๋ผ๋ฒจ๋ง๋ฐ์ดํฐ']
for txt_file_name, dir_name in zip(txt_file_names, dirs):
f = open(txt_file_name+'.txt', 'a', encoding='UTF-8')
id_count = 0
for root, dir, filenames in os.walk(dir_name):
for filename in filenames:
path = os.path.join(root, filename)
with open(path, 'r', encoding='UTF-8') as file:
try:
json_data = json.load(file)
except:
print(path)
continue
for info in json_data['info']:
label = category[info['annotations']['subject']]
for line in info['annotations']['lines']:
text = line['norm_text']
f.write(f'{id_count}\t{text}\t{label}\n')
print(f'\r{id_count} ', end='')
id_count += 1
file.close()
f.close()
์ฒ์์ ์์ธ์ฒ๋ฆฌ๋ฅผ ์ํด์ฃผ์๋๋ฐ, ์ค๊ฐ์ ํ์ผ ๋ช๊ฐ๊ฐ ์ฝ์ด์ง์ง ์์์ try ~ except ๊ตฌ๋ฌธ์ผ๋ก ์ฒ๋ฆฌํด์ฃผ์๋ค.
!pip install transformers
import tensorflow as tf
import torch
from transformers import BertTokenizer
from transformers import BertForSequenceClassification, AdamW, BertConfig
from transformers import get_linear_schedule_with_warmup
from torch.utils.data import TensorDataset, DataLoader, RandomSampler, SequentialSampler
# from keras.preprocessing.sequence import pad_sequences # ๋ก์ปฌํ๊ฒฝ์์ ์๋ฌ๊ฐ ๋๋ค.
from keras_preprocessing.sequence import pad_sequences
from sklearn.model_selection import train_test_split
import pandas as pd
import numpy as np
import random
import time
import datetime
import csv
import pandas as pd
train_data = pd.read_csv('train_data.txt', encoding='utf-8', sep='\t').dropna(axis=0)
pandas csvํ์ผ์ ์ฝ์ด์ค๋ ๋ฐฉ์์ธ๋ฐ txtํ์ผ๋ ์๊ด์๋ค. ๊ตฌ๋ถ์๋ tabํค๋ก ํด๋์๊ธฐ ๋๋ฌธ์ sep='\t'๋ก ํด์ฃผ์๋ค.
๋์ด์ฐ๊ธฐ๋ก ๊ตฌ๋ถํ๋ฉด ์ฑํ ๋์ด์ฐ๊ธฐ์ ๊ตฌ๋ถํ ์ ์๊ธฐ ๋๋ฌธ์ด๋ค. ๊ทธ๋ฆฌ๊ณ nan ํ์ด ์์ ์ค ์์๋๋ฐ
๋์ค์ ํ์ต์ ํด์ฃผ๋ nanํ์ด ๋ฐ๊ฒฌ๋์ด dropna๋ก nanํ์ ์์ ์ฃผ์๋ค.
train_data['label'] = train_data['label'].astype(np.int32)
label์ 0~19๋ก ์ ์ด์ฃผ์๋๋ฐ train.head()๋ก ํ์ธํด๋ณด๋ floatํ์ผ๋ก ๋์์์ด์ intํ์ผ๋ก ๋ฐ๊พธ์ด์ฃผ์๋ค.
floatํ์ผ๋ก๋ ๋๋์ง๋ ์ ๋ชจ๋ฅด์ง๋ง ๋ณดํต ๋ด๊ฐ ๋ณด๊ธฐ์ label์ intํ์ผ๋ก ๋ง์ด ์ ํ์์ด์ ๊ทธ๋ ๊ฒ ์ฒ๋ฆฌํด์ฃผ์๋ค.
sentences = ["[CLS] " + str(s) + " [SEP]" for s in train_data['text']]
labels = train_data['label'].values
BERT๋ชจ๋ธ์ ๊ฒฝ์ฐ ๋ฌธ์ฅ์ ์๋ง๋ค [CLS]๋ฅผ ๋ถ์ฌ ์ธ์ํ๊ณ , [SEP]ํ์๋ก ๋ฌธ์ฅ์ ์ข ๋ฃ๋ฅผ ์ธ์ํ๋ค.
๊ทธ๋์ ๋ฌธ์ฅ์ ์๊ฐ ๋ค์ ํ์๋ฅผ ํด์ฃผ์๋ค.
from transformers import BertTokenizer
tokenizer = BertTokenizer.from_pretrained("bert-base-multilingual-cased", do_lower_case=False)
tokenized_texts = [tokenizer.tokenize(s) for s in sentences]
print(sentences[0])
print(tokenized_texts[0])
# [CLS] ์ ๋์ ๋ ๋๋ฌด ๋ฐฐ๋ถ๋ฌ์ ๋ฐฐ ์ํ [SEP]
# ['[CLS]', '์ ', '##๋', '##์', '๋', '๋', '##๋ฌด', '๋ฐฐ', '##๋ถ', '##๋ฌ', '##์', '๋ฐฐ', '์', '##ํ', '[SEP]']
tokenizer๋ฅผ ๊ฐ์ง๊ณ ์์ ์ฐ๋ฆฌ ๋ฌธ์ฅ์ ํ ํฌ๋์ด์ง์ ํ๋ค. ํ ํฌ๋์ด์ง์ ๋จ์ด์งํฉ์ ์๋ ๋จ์ด๋
ํ ๋ฌถ์์ผ๋ก ๋ฌถ์ด์ฃผ๊ณ , ๋จ์ด ์งํฉ์ ์๋ ๋จ์ด๋ค์ ์ชผ๊ฐ์ค๋ค. ์งํฉ์ ์๋ ๋จ์ด๋ ์ชผ๊ฐค๋ ##๋ฅผ ๋ถ์ฌ์
๋ค๋ฅธ ๋จ์ด์์ ์ชผ๊ฐ์ ธ ๋์์์ ์๋ ค์ฃผ๋ ๊ฒ์ด๋ค.
# ๋ฌธ์ฅ์ ์ต๋ ์ํ์ค๋ฅผ ์ค์ ํ์ฌ ์ ์ ์ธ์ฝ๋ฉ๊ณผ ์ ๋ก ํจ๋ฉ์ ์ํ
MAX_LEN = 128 #์ต๋ ์ํ์ค ๊ธธ์ด ์ค์
input_ids = [tokenizer.convert_tokens_to_ids(x) for x in tokenized_texts]
input_ids = pad_sequences(input_ids, maxlen=MAX_LEN, dtype="long", truncating="post", padding="post")
attention_masks = []
for seq in input_ids:
seq_mask = [float(i>0) for i in seq]
attention_masks.append(seq_mask)
์ดํ ์ ๋ง์คํฌ๋ 0 ๊ฐ์ ๊ฐ์ง๋ ํจ๋ฉ ํ ํฐ์ ๋ํด์ ์ดํ ์ ์ฐ์ฐ์ ๋ถํ์ํ๊ฒ ์ํํ์ง ์๋๋ก
๋จ์ด์ ํจ๋ฉ ํ ํฐ์ ๊ตฌ๋ถํ ์ ์๊ฒ ์๋ ค์ฃผ๋ ๊ฒ์ ๋งํ๋ค.
๋ฐ๋ผ์ [40311, 9435, 102, 0, 0]์ ๊ฐ์ ํจ๋ฉ๋ ๋ฐ์ดํฐ๊ฐ ์์ ๋,
ํจ๋ฉ๋ ๊ฐ์ '0', ํจ๋ฉ๋์ง ์์ ๋จ์ด๋ '1'์ ๊ฐ์ ๊ฐ๋๋ก ์๋ฆฌ์ผ ๋ฐ์ดํฐ๋ฅผ ๋ง๋ค์ด ์ฃผ์ด์ผ ํ๋ค.
train_inputs, validation_inputs, train_labels, validation_labels = train_test_split(input_ids, labels, random_state=2000, test_size=0.1)
train_masks, validation_masks, _, _ = train_test_split(attention_masks, input_ids, random_state=2000, test_size=0.1)
train_inputs = torch.tensor(train_inputs)
train_labels = torch.tensor(train_labels)
train_masks = torch.tensor(train_masks)
validation_inputs = torch.tensor(validation_inputs)
validation_labels = torch.tensor(validation_labels)
validation_masks = torch.tensor(validation_masks)
train๊ณผ valid๋ฅผ ๋๋์ด์ค๋ค. test์ ์ ์ฒ์์ ๋ง๋ค์๋๋ฐ, ๋ฐ์ดํฐ๊ฐ ๋๋ฌด ๋ง์
์ด ๊ธ์ ์ ๊ณ ์๋ ์ค์๋ ํ์ต์ด ์งํ์ค์ด๋ค. ๊ทธ๋์ test์ ์ ํ์ง ์์ผ๋ ค๊ณ ๋ง๋ค์ด์ฃผ์ง ์์๋ค.
๋ฐ์ดํฐ๊ฐ ์ ๊ฑฐ๋ ์๊ฐ์ด ๋ง์ ๋ถ๋ค์ test ์ ๋ ์ด๋ ๊ฒ ๋ง๋ค์ด ์ฃผ๋ฉด ๋๋ค.
batch_size = 1
train_data = TensorDataset(train_inputs, train_masks, train_labels)
train_sampler = RandomSampler(train_data)
train_dataloader = DataLoader(train_data, sampler=train_sampler, batch_size=batch_size)
validation_data = TensorDataset(validation_inputs, validation_masks, validation_labels)
validation_sampler = SequentialSampler(validation_data)
validation_dataloader = DataLoader(validation_data, sampler=validation_sampler, batch_size=batch_size)
๋ง์ฐฌ๊ฐ์ง๋ก ๋ฐ์ดํฐ๊ฐ ๋๋ฌด ๋ง์์ batch_size๋ฅผ 64๋ก ํ๋๊น
์ฉ๋๋ฌธ์ ๋ก ์งํ์ด ๋์ง ์์์ batch_size๋ฅผ 1๋ก ๋ง์ถ์๋ค.
1. BERT๋ชจ๋ธ ๋ถ๋ฌ์ค๊ธฐ
n_devices = torch.cuda.device_count()
print(n_devices)
for i in range(n_devices):
print(torch.cuda.get_device_name(i))
if torch.cuda.is_available():
device = torch.device("cuda")
print('There are %d GPU(s) available.' % torch.cuda.device_count())
print('We will use the GPU:', torch.cuda.get_device_name(0))
else:
device = torch.device("cpu")
print('No GPU available, using the CPU instead.')
์ปดํจํฐ์์ GPU๋ฅผ ์ฌ์ฉํ ์ ์๋์ง ํ์ธํ๋ค.
model = BertForSequenceClassification.from_pretrained("bert-base-multilingual-cased", num_labels=20)
model.cuda()
"""
...
)
)
(dropout): Dropout(p=0.1, inplace=False)
(classifier): Linear(in_features=768, out_features=20, bias=True)
"""
num_labels์์ ๋ณธ์ธ์ ์นดํ ๊ณ ๋ฆฌ ๊ฐฏ์๋ฅผ ์ ์ด์ค๋ค. ์ ์ผ ๋ฐ๋จ out_features์์ ๋์ฌ ๊ฐฏ์์ด๋ค.
๋๋ ์นดํ ๊ณ ๋ฆฌ๋ฅผ 20๊ฐ๋ก ๋ถ๋ฅํด์ 20๊ฐ๋ก ์ ์ด์ฃผ์๋ค.
์ด์ง ๋ถ๋ฅ๋ฉด num_labels์์ 2๋ก ์ ์ด์ฃผ๋ฉด ๋๋ค.
# ์ตํฐ๋ง์ด์
optimizer = AdamW(model.parameters(), lr = 2e-5, eps = 1e-8)
# ์ํญ์
epochs = 5
# ์ด ํ๋ จ ์คํ
: ๋ฐฐ์น๋ฐ๋ณต ํ์ * ์ํญ
total_steps = len(train_dataloader) * epochs
# ์ค์ผ์ค๋ฌ ์์ฑ
scheduler = get_linear_schedule_with_warmup(optimizer, num_warmup_steps = 0, num_training_steps = total_steps)
# ์ ํ๋ ๊ณ์ฐ ํจ์
def flat_accuracy(preds, labels):
pred_flat = np.argmax(preds, axis=1).flatten()
labels_flat = labels.flatten()
return np.sum(pred_flat == labels_flat) / len(labels_flat)
# ์๊ฐ ํ์ ํจ์
def format_time(elapsed):
# ๋ฐ์ฌ๋ฆผ
elapsed_rounded = int(round((elapsed)))
# hh:mm:ss์ผ๋ก ํํ ๋ณ๊ฒฝ
return str(datetime.timedelta(seconds=elapsed_rounded))
import gc
# Your code with pytorch using GPU
gc.collect()
์๊พธ cuda out of mememory๊ฐ ๋์์ collect๋ฅผ ํตํด ์ฒ๋ฆฌํด์ฃผ์๋ค.
2. ๋ชจ๋ธ ํ์ตํ๊ธฐ
#๋๋ค์๋ ๊ณ ์
seed_val = 42
random.seed(seed_val)
np.random.seed(seed_val)
torch.manual_seed(seed_val)
torch.cuda.manual_seed_all(seed_val)
#๊ทธ๋๋์ธํธ ์ด๊ธฐํ
model.zero_grad()
# ํ์ต
for epoch_i in range(0, epochs):
# ========================================
# Training
# ========================================
print("")
print('======== Epoch {:} / {:} ========'.format(epoch_i + 1, epochs))
print('Training...')
# ์์ ์๊ฐ ์ค์
t0 = time.time()
# ๋ก์ค ์ด๊ธฐํ
total_loss = 0
# ํ๋ จ๋ชจ๋๋ก ๋ณ๊ฒฝ
model.train()
# ๋ฐ์ดํฐ๋ก๋์์ ๋ฐฐ์น๋งํผ ๋ฐ๋ณตํ์ฌ ๊ฐ์ ธ์ด
for step, batch in enumerate(train_dataloader):
# ๊ฒฝ๊ณผ ์ ๋ณด ํ์
if step % 500 == 0 and not step == 0:
elapsed = format_time(time.time() - t0)
print(' Batch {:>5,} of {:>5,}. Elapsed: {:}.'.format(step, len(train_dataloader), elapsed))
# ๋ฐฐ์น๋ฅผ GPU์ ๋ฃ์
batch = tuple(t.to(device) for t in batch)
# ๋ฐฐ์น์์ ๋ฐ์ดํฐ ์ถ์ถ
b_input_ids, b_input_mask, b_labels = batch
b_input_ids = b_input_ids.long().to(device)
b_input_mask = b_input_mask.long().to(device)
b_labels = b_labels.type(torch.LongTensor).to(device)
# Forward ์ํ
outputs = model(input_ids=b_input_ids, token_type_ids=None, attention_mask=b_input_mask, labels=b_labels)
# ๋ก์ค ๊ตฌํจ
loss = outputs[0]
# ์ด ๋ก์ค ๊ณ์ฐ
total_loss += loss.item()
# Backward ์ํ์ผ๋ก ๊ทธ๋๋์ธํธ ๊ณ์ฐ
loss.backward()
# ๊ทธ๋๋์ธํธ ํด๋ฆฌํ
torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)
# ๊ทธ๋๋์ธํธ๋ฅผ ํตํด ๊ฐ์ค์น ํ๋ผ๋ฏธํฐ ์
๋ฐ์ดํธ
optimizer.step()
# ์ค์ผ์ค๋ฌ๋ก ํ์ต๋ฅ ๊ฐ์
scheduler.step()
# ๊ทธ๋๋์ธํธ ์ด๊ธฐํ
model.zero_grad()
# ํ๊ท ๋ก์ค ๊ณ์ฐ
avg_train_loss = total_loss / len(train_dataloader)
print("")
print(" Average training loss: {0:.2f}".format(avg_train_loss))
print(" Training epcoh took: {:}".format(format_time(time.time() - t0)))
# ========================================
# Validation
# ========================================
print("")
print("Running Validation...")
#์์ ์๊ฐ ์ค์
t0 = time.time()
# ํ๊ฐ๋ชจ๋๋ก ๋ณ๊ฒฝ
model.eval()
# ๋ณ์ ์ด๊ธฐํ
eval_loss, eval_accuracy = 0, 0
nb_eval_steps, nb_eval_examples = 0, 0
# ๋ฐ์ดํฐ๋ก๋์์ ๋ฐฐ์น๋งํผ ๋ฐ๋ณตํ์ฌ ๊ฐ์ ธ์ด
for batch in validation_dataloader:
# ๋ฐฐ์น๋ฅผ GPU์ ๋ฃ์
batch = tuple(t.to(device) for t in batch)
# ๋ฐฐ์น์์ ๋ฐ์ดํฐ ์ถ์ถ
b_input_ids, b_input_mask, b_labels = batch
# ๊ทธ๋๋์ธํธ ๊ณ์ฐ ์ํจ
with torch.no_grad():
# Forward ์ํ
outputs = model(b_input_ids,
token_type_ids=None,
attention_mask=b_input_mask)
# ๋ก์ค ๊ตฌํจ
logits = outputs[0]
# CPU๋ก ๋ฐ์ดํฐ ์ด๋
logits = logits.detach().cpu().numpy()
label_ids = b_labels.to('cpu').numpy()
# ์ถ๋ ฅ ๋ก์ง๊ณผ ๋ผ๋ฒจ์ ๋น๊ตํ์ฌ ์ ํ๋ ๊ณ์ฐ
tmp_eval_accuracy = flat_accuracy(logits, label_ids)
eval_accuracy += tmp_eval_accuracy
nb_eval_steps += 1
print(" Accuracy: {0:.2f}".format(eval_accuracy/nb_eval_steps))
print(" Validation took: {:}".format(format_time(time.time() - t0)))
print("")
print("Training complete!")
# # ๋ฐฐ์น์์ ๋ฐ์ดํฐ ์ถ์ถ
# b_input_ids, b_input_mask, b_labels = batch
#
# b_input_ids = b_input_ids.long().to(device)
# b_input_mask = b_input_mask.long().to(device)
# b_labels = b_labels.type(torch.LongTensor).to(device)
#
# # Forward ์ํ
# outputs = model(input_ids=b_input_ids, token_type_ids=None, attention_mask=b_input_mask, labels=b_labels)
# nll_loss forward_reduce_cuda_kernel_2d index not implemented for 'Int'
์ฐธ๊ณ ํ๋ ์ฝ๋์์๋ b_input_ids, b_input_mask, b_labels๋ฅผ ๊ทธ๋ฅ ๋ฃ์๋๋ฐ ๋๋ ์๋ฌ๊ฐ ๋ฐ์ํ๋ค.
๊ทธ๋์ .long().to(device)๋ก ์ฒ๋ฆฌํ์ฌ ํด๊ฒฐํ์๋ค.
์์ง๋ ์งํ์ค์ธ๋ฐ epoch๋ฅผ 5๋ฒ์ด๋ ๋๋ฆฐ๊ฑธ ํํํ๋ค.
3. ๋ชจ๋ธ ํ ์คํธํ๊ธฐ
# ์
๋ ฅ ๋ฐ์ดํฐ ๋ณํ
def convert_input_data(sentences):
# BERT์ ํ ํฌ๋์ด์ ๋ก ๋ฌธ์ฅ์ ํ ํฐ์ผ๋ก ๋ถ๋ฆฌ
tokenized_texts = [tokenizer.tokenize(sent) for sent in sentences]
# ์
๋ ฅ ํ ํฐ์ ์ต๋ ์ํ์ค ๊ธธ์ด
MAX_LEN = 128
# ํ ํฐ์ ์ซ์ ์ธ๋ฑ์ค๋ก ๋ณํ
input_ids = [tokenizer.convert_tokens_to_ids(x) for x in tokenized_texts]
# ๋ฌธ์ฅ์ MAX_LEN ๊ธธ์ด์ ๋ง๊ฒ ์๋ฅด๊ณ , ๋ชจ์๋ ๋ถ๋ถ์ ํจ๋ฉ 0์ผ๋ก ์ฑ์
input_ids = pad_sequences(input_ids, maxlen=MAX_LEN, dtype="long", truncating="post", padding="post")
# ์ดํ
์
๋ง์คํฌ ์ด๊ธฐํ
attention_masks = []
# ์ดํ
์
๋ง์คํฌ๋ฅผ ํจ๋ฉ์ด ์๋๋ฉด 1, ํจ๋ฉ์ด๋ฉด 0์ผ๋ก ์ค์
# ํจ๋ฉ ๋ถ๋ถ์ BERT ๋ชจ๋ธ์์ ์ดํ
์
์ ์ํํ์ง ์์ ์๋ ํฅ์
for seq in input_ids:
seq_mask = [float(i>0) for i in seq]
attention_masks.append(seq_mask)
# ๋ฐ์ดํฐ๋ฅผ ํ์ดํ ์น์ ํ
์๋ก ๋ณํ
inputs = torch.tensor(input_ids)
masks = torch.tensor(attention_masks)
return inputs, masks
# ๋ฌธ์ฅ ํ
์คํธ
def test_sentences(sentences):
# ํ๊ฐ๋ชจ๋๋ก ๋ณ๊ฒฝ
model.eval()
# ๋ฌธ์ฅ์ ์
๋ ฅ ๋ฐ์ดํฐ๋ก ๋ณํ
inputs, masks = convert_input_data(sentences)
# ๋ฐ์ดํฐ๋ฅผ GPU์ ๋ฃ์
b_input_ids = inputs.to(device)
b_input_mask = masks.to(device)
# ๊ทธ๋๋์ธํธ ๊ณ์ฐ ์ํจ
with torch.no_grad():
# Forward ์ํ
outputs = model(b_input_ids,
token_type_ids=None,
attention_mask=b_input_mask)
# ๋ก์ค ๊ตฌํจ
logits = outputs[0]
# CPU๋ก ๋ฐ์ดํฐ ์ด๋
logits = logits.detach().cpu().numpy()
return logits
logits = test_sentences(['๋ ๋์ ํ๊ต์ํ ํ๊ณ ์ถ์ด'])
print(logits)
์ฐธ๊ณ : https://velog.io/@seolini43
'๐ผ๐ > ๐พ๐ค๐๐' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
YOLO V8 detection ๊ฐ๋จํ๊ฒ ์ฌ์ฉํ๊ธฐ (0) | 2023.07.06 |
---|---|
์ธ๊ณต์ง๋ฅ koBERT ๋ชจ๋ธ ํ์ต (3) | 2023.02.11 |
๋๊ธ