|
from transformers import AutoModelForSequenceClassification, AutoTokenizer, Trainer, TrainingArguments |
|
from datasets import load_dataset |
|
import os |
|
|
|
|
|
dataset = load_dataset("glue", "sst2") |
|
|
|
|
|
model_name = "bert-base-uncased" |
|
tokenizer = AutoTokenizer.from_pretrained(model_name) |
|
model = AutoModelForSequenceClassification.from_pretrained(model_name, num_labels=2) |
|
|
|
|
|
def preprocess_function(examples): |
|
return tokenizer(examples["sentence"], padding="max_length", truncation=True) |
|
|
|
encoded_dataset = dataset.map(preprocess_function, batched=True) |
|
|
|
|
|
training_args = TrainingArguments( |
|
per_device_train_batch_size=8, |
|
evaluation_strategy="epoch", |
|
logging_dir="./logs", |
|
output_dir="./results", |
|
num_train_epochs=3, |
|
) |
|
|
|
|
|
trainer = Trainer( |
|
model=model, |
|
args=training_args, |
|
train_dataset=encoded_dataset["train"], |
|
eval_dataset=encoded_dataset["validation"], |
|
) |
|
|
|
|
|
trainer.train() |
|
|
|
|
|
model.save_pretrained("./fine_tuned_model") |
|
tokenizer.save_pretrained("./fine_tuned_model") |
|
|