File size: 4,984 Bytes
5e1c670 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 |
import pandas as pd
import numpy as np
import torch
import os
from typing import List, Union
from transformers import AutoTokenizer, Trainer, AutoModelForSequenceClassification, TrainingArguments, DataCollatorWithPadding, pipeline, AutoModel
from datasets import load_dataset, Dataset, DatasetDict
import shap
import wandb
import evaluate
import logging
os.environ["TOKENIZERS_PARALLELISM"] = "false"
device: str = 'cuda' if torch.cuda.is_available() else 'cpu'
SEED: int = 42
BATCH_SIZE: int = 16
EPOCHS: int = 3
SUBSAMPLING: float = 0.1
# WandB configuration
os.environ["WANDB_PROJECT"] = "DAEDRA multiclass model training"
os.environ["WANDB_LOG_MODEL"] = "checkpoint" # log all model checkpoints
os.environ["WANDB_NOTEBOOK_NAME"] = "DAEDRA.ipynb"
dataset = load_dataset("chrisvoncsefalvay/vaers-outcomes")
if SUBSAMPLING < 1:
_ = DatasetDict()
for each in dataset.keys():
_[each] = dataset[each].shuffle(seed=SEED).select(range(int(len(dataset[each]) * SUBSAMPLING)))
dataset = _
accuracy = evaluate.load("accuracy")
precision, recall = evaluate.load("precision"), evaluate.load("recall")
f1 = evaluate.load("f1")
def compute_metrics(eval_pred):
predictions, labels = eval_pred
predictions = np.argmax(predictions, axis=1)
return {
'accuracy': accuracy.compute(predictions=predictions, references=labels)["accuracy"],
'precision_macroaverage': precision.compute(predictions=predictions, references=labels, average='macro')["precision"],
'precision_microaverage': precision.compute(predictions=predictions, references=labels, average='micro')["precision"],
'recall_macroaverage': recall.compute(predictions=predictions, references=labels, average='macro')["recall"],
'recall_microaverage': recall.compute(predictions=predictions, references=labels, average='micro')["recall"],
'f1_microaverage': f1.compute(predictions=predictions, references=labels, average='micro')["f1"]
}
label_map = {i: label for i, label in enumerate(dataset["test"].features["label"].names)}
def train_from_model(model_ckpt: str, push: bool = False):
print(f"Initialising training based on {model_ckpt}...")
print("Tokenising...")
tokenizer = AutoTokenizer.from_pretrained(model_ckpt)
cols = dataset["train"].column_names
cols.remove("label")
ds_enc = dataset.map(lambda x: tokenizer(x["text"], truncation=True, max_length=512), batched=True, remove_columns=cols)
print("Loading model...")
try:
model = AutoModelForSequenceClassification.from_pretrained(model_ckpt,
num_labels=len(dataset["test"].features["label"].names),
id2label=label_map,
label2id={v:k for k,v in label_map.items()})
except OSError:
model = AutoModelForSequenceClassification.from_pretrained(model_ckpt,
num_labels=len(dataset["test"].features["label"].names),
id2label=label_map,
label2id={v:k for k,v in label_map.items()},
from_tf=True)
args = TrainingArguments(
output_dir="vaers",
evaluation_strategy="steps",
eval_steps=100,
save_strategy="epoch",
learning_rate=2e-5,
per_device_train_batch_size=BATCH_SIZE,
per_device_eval_batch_size=BATCH_SIZE,
num_train_epochs=EPOCHS,
weight_decay=.01,
logging_steps=1,
run_name=f"daedra-minisample-comparison-{SUBSAMPLING}",
report_to=["wandb"])
trainer = Trainer(
model=model,
args=args,
train_dataset=ds_enc["train"],
eval_dataset=ds_enc["test"],
tokenizer=tokenizer,
compute_metrics=compute_metrics)
if SUBSAMPLING != 1.0:
wandb_tag: List[str] = [f"subsample-{SUBSAMPLING}"]
else:
wandb_tag: List[str] = [f"full_sample"]
wandb_tag.append(f"batch_size-{BATCH_SIZE}")
wandb_tag.append(f"base:{model_ckpt}")
if "/" in model_ckpt:
sanitised_model_name = model_ckpt.split("/")[1]
else:
sanitised_model_name = model_ckpt
wandb.init(name=f"daedra_{SUBSAMPLING}-{sanitised_model_name}", tags=wandb_tag, magic=True)
print("Starting training...")
trainer.train()
print("Training finished.")
wandb.finish()
if __name__ == "__main__":
wandb.finish()
for mname in (
#"dmis-lab/biobert-base-cased-v1.2",
"emilyalsentzer/Bio_ClinicalBERT",
"bert-base-uncased",
"distilbert-base-uncased"
):
print(f"Now training on subsample with {mname}...")
train_from_model(mname) |