|
|
|
|
|
|
|
|
import torch |
|
|
from datasets import load_dataset |
|
|
from transformers import ( |
|
|
AutoModelForSequenceClassification, |
|
|
AutoTokenizer, |
|
|
TrainingArguments, |
|
|
Trainer, |
|
|
DataCollatorWithPadding |
|
|
) |
|
|
from sklearn.metrics import accuracy_score, precision_recall_fscore_support |
|
|
|
|
|
|
|
|
def compute_metrics(pred): |
|
|
""" |
|
|
Calculate accuracy, precision, recall, and F1 score |
|
|
Args: |
|
|
pred: predictions from the model |
|
|
Returns: |
|
|
dict: containing all metrics |
|
|
""" |
|
|
labels = pred.label_ids |
|
|
preds = pred.predictions.argmax(-1) |
|
|
|
|
|
|
|
|
precision, recall, f1, _ = precision_recall_fscore_support( |
|
|
labels, |
|
|
preds, |
|
|
average='binary' |
|
|
) |
|
|
acc = accuracy_score(labels, preds) |
|
|
|
|
|
return { |
|
|
'accuracy': acc, |
|
|
'f1': f1, |
|
|
'precision': precision, |
|
|
'recall': recall |
|
|
} |
|
|
|
|
|
def train_model(): |
|
|
|
|
|
|
|
|
print("Loading dataset...") |
|
|
dataset = load_dataset("imdb") |
|
|
|
|
|
|
|
|
|
|
|
print("Loading tokenizer and model...") |
|
|
model_name = "distilbert-base-uncased" |
|
|
tokenizer = AutoTokenizer.from_pretrained(model_name) |
|
|
model = AutoModelForSequenceClassification.from_pretrained( |
|
|
model_name, |
|
|
num_labels=2 |
|
|
) |
|
|
|
|
|
|
|
|
def tokenize_function(examples): |
|
|
""" |
|
|
Tokenize the input text data |
|
|
Args: |
|
|
examples: batch of examples from dataset |
|
|
Returns: |
|
|
tokenized examples |
|
|
""" |
|
|
return tokenizer( |
|
|
examples["text"], |
|
|
truncation=True, |
|
|
padding="max_length", |
|
|
max_length=512 |
|
|
) |
|
|
|
|
|
|
|
|
print("Tokenizing dataset...") |
|
|
tokenized_datasets = dataset.map( |
|
|
tokenize_function, |
|
|
batched=True, |
|
|
remove_columns=dataset["train"].column_names |
|
|
) |
|
|
|
|
|
|
|
|
print("Setting up training arguments...") |
|
|
training_args = TrainingArguments( |
|
|
output_dir="./results", |
|
|
learning_rate=2e-5, |
|
|
per_device_train_batch_size=16, |
|
|
per_device_eval_batch_size=16, |
|
|
num_train_epochs=3, |
|
|
weight_decay=0.01, |
|
|
evaluation_strategy="epoch", |
|
|
save_strategy="epoch", |
|
|
load_best_model_at_end=True, |
|
|
push_to_hub=True, |
|
|
hub_model_id="shaheerawan3/Vibescribe" |
|
|
) |
|
|
|
|
|
|
|
|
print("Initializing trainer...") |
|
|
trainer = Trainer( |
|
|
model=model, |
|
|
args=training_args, |
|
|
train_dataset=tokenized_datasets["train"], |
|
|
eval_dataset=tokenized_datasets["test"], |
|
|
tokenizer=tokenizer, |
|
|
data_collator=DataCollatorWithPadding(tokenizer=tokenizer), |
|
|
compute_metrics=compute_metrics |
|
|
) |
|
|
|
|
|
|
|
|
print("Starting training...") |
|
|
trainer.train() |
|
|
|
|
|
|
|
|
print("Pushing model to Hugging Face Hub...") |
|
|
trainer.push_to_hub() |
|
|
|
|
|
if __name__ == "__main__": |
|
|
train_model() |