Download train_model.py from tmutton/wcag-accessibility-issues: direct link, hf CLI and curl.
- Browser
- Download file 2.9 kB
-
https://huggingface.co/datasets/tmutton/wcag-accessibility-issues/resolve/main/train_model.py
- Command line
-
hf download hf://datasets/tmutton/wcag-accessibility-issues/train_model.py
-
curl -L -o train_model.py https://huggingface.co/datasets/tmutton/wcag-accessibility-issues/resolve/main/train_model.py
2.9 kB
| import numpy as np | |
| from datasets import load_dataset | |
| from sklearn.metrics import accuracy_score, precision_recall_fscore_support | |
| from transformers import ( | |
| AutoModelForSequenceClassification, | |
| AutoTokenizer, | |
| DataCollatorWithPadding, | |
| Trainer, | |
| TrainingArguments, | |
| ) | |
| MODEL_NAME = "distilbert-base-uncased" | |
| LABELS = [ | |
| "1.3.1 Info and Relationships", | |
| "2.1.1 Keyboard", | |
| "2.4.3 Focus Order", | |
| "2.4.7 Focus Visible", | |
| "4.1.2 Name, Role, Value", | |
| ] | |
| label2id = {label: i for i, label in enumerate(LABELS)} | |
| id2label = {i: label for i, label in enumerate(LABELS)} | |
| # Load our CSV files | |
| dataset = load_dataset( | |
| "csv", | |
| data_files={ | |
| "train": "train.csv", | |
| "validation": "validation.csv", | |
| "test": "test.csv", | |
| }, | |
| ) | |
| # Load DistilBERT's tokenizer | |
| tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME) | |
| def preprocess(example): | |
| encoded = tokenizer( | |
| example["text"], | |
| truncation=True, | |
| ) | |
| encoded["label_id"] = label2id[example["label"]] | |
| return encoded | |
| tokenized_dataset = dataset.map( | |
| preprocess, | |
| remove_columns=["text", "label"], | |
| ) | |
| tokenized_dataset = tokenized_dataset.rename_column( | |
| "label_id", | |
| "labels", | |
| ) | |
| # Pads each batch to the longest sentence in that batch | |
| data_collator = DataCollatorWithPadding( | |
| tokenizer=tokenizer | |
| ) | |
| # Load pretrained DistilBERT with our new 5-class head | |
| model = AutoModelForSequenceClassification.from_pretrained( | |
| MODEL_NAME, | |
| num_labels=len(LABELS), | |
| id2label=id2label, | |
| label2id=label2id, | |
| ) | |
| def compute_metrics(eval_pred): | |
| logits, labels = eval_pred | |
| predictions = np.argmax(logits, axis=-1) | |
| precision, recall, f1, _ = precision_recall_fscore_support( | |
| labels, | |
| predictions, | |
| average="weighted", | |
| zero_division=0, | |
| ) | |
| accuracy = accuracy_score( | |
| labels, | |
| predictions, | |
| ) | |
| return { | |
| "accuracy": accuracy, | |
| "precision": precision, | |
| "recall": recall, | |
| "f1": f1, | |
| } | |
| training_args = TrainingArguments( | |
| output_dir="./results", | |
| num_train_epochs=5, | |
| per_device_train_batch_size=8, | |
| per_device_eval_batch_size=8, | |
| learning_rate=2e-5, | |
| eval_strategy="epoch", | |
| save_strategy="epoch", | |
| logging_strategy="epoch", | |
| load_best_model_at_end=True, | |
| metric_for_best_model="f1", | |
| ) | |
| trainer = Trainer( | |
| model=model, | |
| args=training_args, | |
| train_dataset=tokenized_dataset["train"], | |
| eval_dataset=tokenized_dataset["validation"], | |
| data_collator=data_collator, | |
| compute_metrics=compute_metrics, | |
| ) | |
| print("\nStarting training...\n") | |
| trainer.train() | |
| print("\nEvaluating final model on test data...\n") | |
| test_results = trainer.evaluate( | |
| tokenized_dataset["test"] | |
| ) | |
| print(test_results) | |
| # Save our finished model locally | |
| trainer.save_model("./wcag-classifier") | |
| tokenizer.save_pretrained("./wcag-classifier") |