File size: 6,496 Bytes
01b54d8 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 | import numpy as np
import pandas as pd
import torch
from torch.utils.data import Dataset, DataLoader
from transformers import (
AutoTokenizer,
AutoModelForSequenceClassification,
Trainer,
TrainingArguments,
EvalPrediction
)
from sklearn.metrics import accuracy_score
from transformers import TrainerCallback
# GPU ์ฌ์ฉ ๊ฐ๋ฅ ํ์ธ ๋ฐ device ์ค์
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
# SentimentDataset ํด๋์ค ์ ์
class SentimentDataset(Dataset):
def __init__(self, encodings, labels):
self.encodings = encodings
self.labels = labels
def __getitem__(self, idx):
item = {key: torch.tensor(val[idx]) for key, val in self.encodings.items()}
item['labels'] = torch.tensor(self.labels[idx])
return item
def __len__(self):
return len(self.labels)
# CSV ํ์ผ ๋ก๋
df = pd.read_csv('path') # hr_data
# ๋ฐ์ดํฐ ์ ์ฒ๋ฆฌ
texts = df['person_corpus'].tolist()
labels = df['label'].tolist() # ๋ผ๋ฒจ ๋ฐ์ดํฐ๋ ์ ์๋ก ๋ณํ๋์ด ์์ด์ผ ํฉ๋๋ค.
# ํ ํฌ๋์ด์ ๋ก๋ฉ
tokenizer_roberta = AutoTokenizer.from_pretrained("klue/roberta-large")
tokenizer_electra = AutoTokenizer.from_pretrained("monologg/koelectra-base-v3-discriminator")
# ๋ฐ์ดํฐ์
ํ ํฐํ
encodings_roberta = tokenizer_roberta(texts, truncation=True, padding=True, max_length=128)
encodings_electra = tokenizer_electra(texts, truncation=True, padding=True, max_length=128)
# ๋ฐ์ดํฐ์
์์ฑ
dataset_roberta = SentimentDataset(encodings_roberta, labels)
dataset_electra = SentimentDataset(encodings_electra, labels)
# ๋ก๋ํ RoBERTa ๋ชจ๋ธ ๊ฒฝ๋ก
roberta_model_path = "path"
# ๋ก๋ํ Electra ๋ชจ๋ธ ๊ฒฝ๋ก
electra_model_path = "path"
# ์ ์ฅ๋ ๋ชจ๋ธ ๋ก๋
model_roberta = AutoModelForSequenceClassification.from_pretrained(roberta_model_path)
model_electra = AutoModelForSequenceClassification.from_pretrained(electra_model_path)
# CustomTrainer ํด๋์ค ์ ์
class CustomTrainer(Trainer):
def __init__(self, *args, label_weights=None, **kwargs):
super().__init__(*args, **kwargs)
self.label_weights = label_weights if label_weights is not None else {}
def compute_loss(self, model, inputs, return_outputs=False):
outputs = model(**inputs)
logits = outputs.get('logits')
labels = inputs.get('labels')
if self.label_weights:
weight = torch.tensor([self.label_weights.get(label.item(), 1.0) for label in labels]).to(labels.device)
loss_fct = CrossEntropyLoss(weight=weight)
else:
loss_fct = CrossEntropyLoss()
loss = loss_fct(logits.view(-1, self.model.config.num_labels), labels.view(-1))
return (loss, outputs) if return_outputs else loss
# TrainingArguments ์ค์
training_args = TrainingArguments(
output_dir='./results',
num_train_epochs=100,
per_device_train_batch_size=16,
warmup_steps=500,
weight_decay=0.01,
logging_dir='./logs',
logging_steps=10,
)
# ๋ผ๋ฒจ๋ณ ๊ฐ์ค์น ์ค์
label_weights = {0: 8.0, 1: 2.5, 2: 5.0, 3: 1.0}
# CustomTrainer ์ธ์คํด์ค ์์ฑ
trainer_roberta = CustomTrainer(
model=model_roberta,
args=training_args,
train_dataset=dataset_roberta, # dataset_roberta๋ ์ฌ์ฉ์๊ฐ ์ ์ํด์ผ ํจ
label_weights=label_weights,
)
trainer_electra = CustomTrainer(
model=model_electra,
args=training_args,
train_dataset=dataset_electra, # dataset_electra๋ ์ฌ์ฉ์๊ฐ ์ ์ํด์ผ ํจ
label_weights=label_weights,
)
# ๋ก์ง์ ํ๋ฅ ๋ก ๋ณํํ๋ ํจ์
def logits_to_probs(logits):
return torch.softmax(logits, dim=1)
def predict_with_ensemble_modified(texts, roberta_model, koelectra_model, tokenizer_roberta, tokenizer_koelectra, device):
encodings_roberta = tokenizer_roberta(texts, truncation=True, padding=True, max_length=128)
encodings_koelectra = tokenizer_koelectra(texts, truncation=True, padding=True, max_length=128)
roberta_dataset = SentimentDataset(encodings_roberta, [0]*len(texts)) # ๋ผ๋ฒจ์ ์์ธก์ ์ํด ์ฌ์ฉ๋์ง ์์ผ๋ฏ๋ก ์์ ๊ฐ์ผ๋ก ์ค์
koelectra_dataset = SentimentDataset(encodings_koelectra, [0]*len(texts))
roberta_dataloader = DataLoader(roberta_dataset, batch_size=32, shuffle=False)
koelectra_dataloader = DataLoader(koelectra_dataset, batch_size=32, shuffle=False)
roberta_model.to(device)
koelectra_model.to(device)
roberta_model.eval()
koelectra_model.eval()
final_labels = [] # ์ต์ข
๋ผ๋ฒจ์ ์ ์ฅํ ๋ฆฌ์คํธ๋ฅผ ๋ฃจํ ์ธ๋ถ์์ ์ด๊ธฐํ
with torch.no_grad():
for roberta_batch, koelectra_batch in zip(roberta_dataloader, koelectra_dataloader):
roberta_input_ids, roberta_attention_mask = roberta_batch['input_ids'].to(device), roberta_batch['attention_mask'].to(device)
koelectra_input_ids, koelectra_attention_mask = koelectra_batch['input_ids'].to(device), koelectra_batch['attention_mask'].to(device)
roberta_outputs = roberta_model(roberta_input_ids, roberta_attention_mask)
koelectra_outputs = koelectra_model(koelectra_input_ids, koelectra_attention_mask)
roberta_probs = logits_to_probs(roberta_outputs.logits).cpu().numpy()
koelectra_probs = logits_to_probs(koelectra_outputs.logits).cpu().numpy()
ensemble_probs = (roberta_probs + koelectra_probs) / 2
for probs in ensemble_probs:
pred_label = np.argmax(probs)
if pred_label == 1 and probs[pred_label] > 0.6: # ๊ธ์ ์ด๋ฉด์ ํ๋ฅ ์ด 0.5 ์ด์์ธ ๊ฒฝ์ฐ
pred_label = 3 # ๋งค์ฐ ๊ธ์ ์ผ๋ก ๋ณ๊ฒฝ
elif pred_label == 0 and probs[pred_label] > 0.7: # ๋ถ์ ์ด๋ฉด์ ํ๋ฅ ์ด 0.5 ์ด์์ธ ๊ฒฝ์ฐ
pred_label = 2 # ๋งค์ฐ ๋ถ์ ์ผ๋ก ๋ณ๊ฒฝ
final_labels.append(pred_label) # ์์ ๋ ๋ผ๋ฒจ์ ์ต์ข
๋ผ๋ฒจ ๋ฆฌ์คํธ์ ์ถ๊ฐ
return final_labels # ์์ : ์ต์ข
๋ผ๋ฒจ ๋ฆฌ์คํธ ๋ฐํ
# ํจ์ ํธ์ถ์ device ๋ณ์ ์ฌ์ฉ
final_labels = predict_with_ensemble_modified(texts, model_roberta, model_electra, tokenizer_roberta, tokenizer_electra, device)
# ๊ฒฐ๊ณผ ์ถ๋ ฅ
for text, label in zip(texts, final_labels):
print(f"Text: {text} - Prediction: {label}")
|