|
from datasets import load_dataset, DatasetDict |
|
from evaluate import load |
|
from transformers import AutoTokenizer, AutoModelForSequenceClassification, TrainingArguments, Trainer |
|
import torch |
|
import numpy as np |
|
|
|
labels = { |
|
'contradiction': 0, |
|
'neutral': 1, |
|
'entailment': 2, |
|
} |
|
|
|
datasets = load_dataset('seongs1024/DKK-nli') |
|
datasets = DatasetDict({ |
|
'train': datasets['train'].shard(num_shards=100, index=0), |
|
'validation': datasets['validation'].shard(num_shards=100, index=0), |
|
}) |
|
|
|
metric = load('glue', 'mnli') |
|
def compute_metrics(eval_pred): |
|
predictions, labels = eval_pred |
|
predictions = np.argmax(predictions, axis=1) |
|
return metric.compute(predictions=predictions, references=labels) |
|
|
|
check_point = 'klue/roberta-small' |
|
model = AutoModelForSequenceClassification.from_pretrained(check_point, num_labels=3) |
|
tokenizer = AutoTokenizer.from_pretrained(check_point) |
|
|
|
def preprocess_function(examples): |
|
return tokenizer( |
|
examples['premise'], |
|
examples['hypothesis'], |
|
truncation=True, |
|
return_token_type_ids=False, |
|
) |
|
encoded_datasets = datasets.map(preprocess_function, batched=True) |
|
|
|
batch_size = 8 |
|
args = TrainingArguments( |
|
"test-nli", |
|
evaluation_strategy="epoch", |
|
save_strategy='epoch', |
|
learning_rate=2e-5, |
|
per_device_train_batch_size=batch_size, |
|
per_device_eval_batch_size=batch_size, |
|
num_train_epochs=5, |
|
weight_decay=0.01, |
|
load_best_model_at_end=True, |
|
metric_for_best_model='accuracy', |
|
) |
|
|
|
trainer = Trainer( |
|
model, |
|
args, |
|
train_dataset=encoded_datasets["train"], |
|
eval_dataset=encoded_datasets["validation"], |
|
tokenizer=tokenizer, |
|
compute_metrics=compute_metrics, |
|
) |
|
|
|
trainer.train() |
|
trainer.evaluate() |
|
|
|
trainer.save_model('./model') |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|