Can you produce a code in Python that trains multiple classifiers, one for each label?
For each label, loop over predefined different parameters combinations.
For each label create a config yaml file with the current training parameters.
For each label there is a predefined train and test sets.
For each label in each parameters combination there will be a new huggingface training phase.
Save all evaluation results per label per parameters combination in a file.
Assistant
User
Can you re-write only the sections needed to change the loss and metrics to use F1 score?
Assistant
User
Can you give me a function that takes a huggingface Trainer (That was pretrained) , evaluate results, finds the optimal threshold in F1 score and return: optimal threshold, precision, recall, F1 score and the support?
Assistant
Sure! Here's a function that takes a pre-trained Trainer object, computes the F1 score for each threshold, finds the optimal threshold that maximizes the F1 score, and returns the precision, recall, F1 score, and support at the optimal threshold:
python
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Sure! Here's an example code that trains multiple classifiers, one for each label, and loops over predefined different parameter combinations using Hugging Face's Transformers library in Python:
python
import yaml
import pandas as pd
from transformers import Trainer, TrainingArguments, AutoTokenizer, AutoModelForSequenceClassification
# Define a function to train a classifier for a single label
def train_classifier(label, train_dataset, test_dataset, param_combinations):
# Initialize an empty dictionary to store the evaluation results
eval_results = {}
# Load the tokenizer and model for the specific label
tokenizer = AutoTokenizer.from_pretrained(f"{label}-model")
model = AutoModelForSequenceClassification.from_pretrained(f"{label}-model")
# Loop over the predefined parameter combinations
for params in param_combinations:
# Create a TrainingArguments object with the current parameters
training_args = TrainingArguments(
output_dir=f"{label}-{params['batch_size']}-{params['learning_rate']}",
evaluation_strategy="epoch",
learning_rate=params["learning_rate"],
per_device_train_batch_size=params["batch_size"],
per_device_eval_batch_size=params["batch_size"],
num_train_epochs=params["num_epochs"],
weight_decay=params["weight_decay"],
logging_dir=f"{label}-{params['batch_size']}-{params['learning_rate']}/logs",
logging_steps=10,
load_best_model_at_end=True,
metric_for_best_model="accuracy",
)
# Create a Trainer object with the current TrainingArguments and the model
trainer = Trainer(
model=model,
args=training_args,
train_dataset=train_dataset,
eval_dataset=test_dataset,
)
# Train the model
trainer.train()
# Evaluate the model on the test dataset and store the results
eval_result = trainer.evaluate()
eval_results[f"{params['batch_size']}-{params['learning_rate']}"] = eval_result
# Save the current parameters to a YAML file
with open(
f"{label}-{params['batch_size']}-{params['learning_rate']}/config.yaml", "w"
) as f:
yaml.dump(params, f)
# Save the evaluation results to a CSV file
eval_df = pd.DataFrame.from_dict(eval_results, orient="index")
eval_df.to_csv(f"{label}-eval_results.csv")
# Define the training and test datasets for each label
label_train_datasets = {"label1": train_dataset1, "label2": train_dataset2, ...}
label_test_datasets = {"label1": test_dataset1, "label2": test_dataset2, ...}
# Define the parameter combinations for each label
label_param_combinations = {
"label1": [
{"batch_size": 16, "learning_rate": 1e-4, "num_epochs": 3, "weight_decay": 0.01},
{"batch_size": 32, "learning_rate": 5e-5, "num_epochs": 5, "weight_decay": 0.001},
{"batch_size": 64, "learning_rate": 1e-5, "num_epochs": 10, "weight_decay": 0.0001},
],
"label2": [
{"batch_size": 16, "learning_rate": 1e-4, "num_epochs": 3, "weight_decay": 0.01},
{"batch_size": 32, "learning_rate": 5e-5, "num_epochs": 5, "weight_decay": 0.001},
{"batch_size": 64, "learning_rate": 1e-5, "num_epochs": 10
Sure! Here's the modified code where we change the metric for evaluation to the F1 score:
python
import yaml
import pandas as pd
from sklearn.metrics import f1_score
from transformers import Trainer, TrainingArguments, AutoTokenizer, AutoModelForSequenceClassification
# Define a function to compute F1 score for the predictions
def compute_f1(pred):
labels = pred.label_ids
preds = pred.predictions.argmax(-1)
return {"f1_score": f1_score(labels, preds, average="macro")}
# Define a function to train a classifier for a single label
def train_classifier(label, train_dataset, test_dataset, param_combinations):
# Initialize an empty dictionary to store the evaluation results
eval_results = {}
# Load the tokenizer and model for the specific label
tokenizer = AutoTokenizer.from_pretrained(f"{label}-model")
model = AutoModelForSequenceClassification.from_pretrained(f"{label}-model")
# Loop over the predefined parameter combinations
for params in param_combinations:
# Create a TrainingArguments object with the current parameters and the F1 score metric
training_args = TrainingArguments(
output_dir=f"{label}-{params['batch_size']}-{params['learning_rate']}",
evaluation_strategy="epoch",
learning_rate=params["learning_rate"],
per_device_train_batch_size=params["batch_size"],
per_device_eval_batch_size=params["batch_size"],
num_train_epochs=params["num_epochs"],
weight_decay=params["weight_decay"],
logging_dir=f"{label}-{params['batch_size']}-{params['learning_rate']}/logs",
logging_steps=10,
load_best_model_at_end=True,
metric_for_best_model="f1_score", # change the metric to F1 score
)
# Create a Trainer object with the current TrainingArguments and the model
trainer = Trainer(
model=model,
args=training_args,
train_dataset=train_dataset,
eval_dataset=test_dataset,
compute_metrics=compute_f1, # specify the compute function for F1 score
)
# Train the model
trainer.train()
# Evaluate the model on the test dataset and store the results
eval_result = trainer.evaluate()
eval_results[f"{params['batch_size']}-{params['learning_rate']}"] = eval_result
# Save the current parameters to a YAML file
with open(
f"{label}-{params['batch_size']}-{params['learning_rate']}/config.yaml", "w"
) as f:
yaml.dump(params, f)
# Save the evaluation results to a CSV file
eval_df = pd.DataFrame.from_dict(eval_results, orient="index")
eval_df.to_csv(f"{label}-eval_results.csv")
# Define the training and test datasets for each label
label_train_datasets = {"label1": train_dataset1, "label2": train_dataset2, ...}
label_test_datasets = {"label1": test_dataset1, "label2": test_dataset2, ...}
# Define the parameter combinations for each label
label_param_combinations = {
"label1": [
{"batch_size": 16, "learning_rate": 1e-4, "num_epochs": 3, "weight_decay": 0.01},
{"batch_size": 32, "learning_rate": 5e-5, "num_epochs": 5, "weight_decay": 0.001},
{"batch_size": 64, "learning_rate": 1e-5, "num_epochs": 10, "weight_decay": 0.0001},
],
"label2": [
{"batch_size":
from sklearn.metrics import classification_report, f1_score
def compute_optimal_threshold(trainer):
# Evaluate the trained model on the validation dataset
eval_result = trainer.evaluate()
labels = eval_result["eval_label_ids"]
preds = trainer.predict(trainer.eval_dataset).predictions
# Compute the F1 score for each threshold between 0 and 1
thresholds = [i/100 for i in range(0, 101)]
f1_scores = []
for threshold in thresholds:
preds_threshold = (preds[:, 1] > threshold).astype(int)
f1_scores.append(f1_score(labels, preds_threshold))
# Find the optimal threshold that maximizes the F1 score
optimal_threshold = thresholds[f1_scores.index(max(f1_scores))]
# Compute the precision, recall, F1 score, and support at the optimal threshold
preds_threshold = (preds[:, 1] > optimal_threshold).astype(int)
report = classification_report(
labels, preds_threshold, output_dict=True, zero_division=0
)
precision = report["1"]["precision"]
recall = report["1"]["recall"]
f1_score = report["1"]["f1-score"]
support = report["1"]["support"]
return optimal_threshold, precision, recall, f1_score, support
To use this function, simply pass a pre-trained Trainer object to it, like so:
Note that this function assumes a binary classification task with labels 0 and 1, and the predictions are taken from the second column of the output logits. If your task or model is different, you may need to modify this function accordingly.