|
| 1 | +""" |
| 2 | +Optuna example for fine-tuning a BERT-based text classification model on the IMDb dataset |
| 3 | +with hyperparameter optimization using Optuna. In this example, we fine-tune a lightweight |
| 4 | +pre-trained BERT model on a small subset of the IMDb dataset to classify movie reviews as |
| 5 | +positive or negative. We optimize the validation accuracy by tuning the learning rate |
| 6 | +and batch size. To learn more about transformers' hyperparameter search, |
| 7 | +you can check the following documentation: |
| 8 | +https://huggingface.co/docs/transformers/en/hpo_train. |
| 9 | +""" |
| 10 | + |
| 11 | +from datasets import load_dataset |
| 12 | +import evaluate |
| 13 | + |
| 14 | +from transformers import AutoModelForSequenceClassification |
| 15 | +from transformers import AutoTokenizer |
| 16 | +from transformers import set_seed |
| 17 | +from transformers import Trainer |
| 18 | +from transformers import TrainingArguments |
| 19 | + |
| 20 | + |
| 21 | +set_seed(42) |
| 22 | + |
| 23 | + |
| 24 | +train_dataset = load_dataset("imdb", split="train").shuffle(seed=42).select(range(1000)) |
| 25 | +valid_dataset = load_dataset("imdb", split="test").shuffle(seed=42).select(range(500)) |
| 26 | + |
| 27 | +model_name = "prajjwal1/bert-tiny" |
| 28 | +tokenizer = AutoTokenizer.from_pretrained(model_name) |
| 29 | + |
| 30 | + |
| 31 | +def tokenize(batch): |
| 32 | + return tokenizer(batch["text"], padding="max_length", truncation=True, max_length=512) |
| 33 | + |
| 34 | + |
| 35 | +tokenized_train = train_dataset.map(tokenize, batched=True).select_columns( |
| 36 | + ["input_ids", "attention_mask", "label"] |
| 37 | +) |
| 38 | +tokenized_valid = valid_dataset.map(tokenize, batched=True).select_columns( |
| 39 | + ["input_ids", "attention_mask", "label"] |
| 40 | +) |
| 41 | + |
| 42 | + |
| 43 | +metric = evaluate.load("accuracy") |
| 44 | + |
| 45 | + |
| 46 | +def model_init(): |
| 47 | + return AutoModelForSequenceClassification.from_pretrained(model_name, num_labels=2) |
| 48 | + |
| 49 | + |
| 50 | +def compute_metrics(eval_pred): |
| 51 | + predictions = eval_pred.predictions.argmax(axis=-1) |
| 52 | + labels = eval_pred.label_ids |
| 53 | + return metric.compute(predictions=predictions, references=labels) |
| 54 | + |
| 55 | + |
| 56 | +def compute_objective(metrics): |
| 57 | + return metrics["eval_accuracy"] |
| 58 | + |
| 59 | + |
| 60 | +training_args = TrainingArguments( |
| 61 | + eval_strategy="epoch", |
| 62 | + save_strategy="best", |
| 63 | + load_best_model_at_end=True, |
| 64 | + logging_strategy="epoch", |
| 65 | + report_to="none", |
| 66 | +) |
| 67 | + |
| 68 | + |
| 69 | +trainer = Trainer( |
| 70 | + model_init=model_init, |
| 71 | + args=training_args, |
| 72 | + train_dataset=tokenized_train, |
| 73 | + eval_dataset=tokenized_valid, |
| 74 | + processing_class=tokenizer, |
| 75 | + compute_metrics=compute_metrics, |
| 76 | +) |
| 77 | + |
| 78 | + |
| 79 | +def optuna_hp_space(trial): |
| 80 | + return { |
| 81 | + "learning_rate": trial.suggest_float("learning_rate", 1e-6, 1e-4, log=True), |
| 82 | + "per_device_train_batch_size": trial.suggest_categorical( |
| 83 | + "per_device_train_batch_size", [16, 32, 64, 128] |
| 84 | + ), |
| 85 | + } |
| 86 | + |
| 87 | + |
| 88 | +best_run = trainer.hyperparameter_search( |
| 89 | + direction="maximize", |
| 90 | + backend="optuna", |
| 91 | + hp_space=optuna_hp_space, |
| 92 | + n_trials=5, |
| 93 | + compute_objective=compute_objective, |
| 94 | +) |
| 95 | + |
| 96 | +print(best_run) |
0 commit comments