Below is a Python code example that achieves what you've described. This script assumes several things for simplicity and to fill in gaps not specified in your question:
Dataset Structure: You have a directory datasets/ where each label's dataset is stored in a separate subdirectory (e.g., datasets/label1/, datasets/label2/, etc.). Within each label directory, there are two files: train.csv and test.csv. Each CSV file should have at least two columns: one for the text data (assumed to be named 'text') and one for the corresponding labels (assumed to be named 'label').
Validation: The script checks if the required dataset files exist before attempting to load them.
Predefined Parameters Combinations: These are defined as a list of dictionaries in the script. You can add or modify these as needed. Each dictionary should specify the model name, batch size, and number of epochs.
Classifiers: For simplicity, this example uses Hugging Face's Trainer API with a AutoModelForSequenceClassification from the transformers library. The model type (e.g., distilbert-base-uncased) is part of the parameters to loop over.
Config YAML File: Created for each label with the current training parameters.
Evaluation Results: Saved to a file named evaluation_results.txt in the project root, with each line representing the results for a specific label and parameters combination.
Dependencies:
transformers
torch
yaml
pandas (for handling CSV files)
numpy (not explicitly used here but often required for ML environments)
Python Script:
python
import os
import yaml
from transformers import AutoModelForSequenceClassification, AutoTokenizer
from transformers import Trainer, TrainingArguments
from sklearn.metrics import accuracy_score
from sklearn.model_selection import train_test_split
import pandas as pd
import torch
# Define labels and parameters combinations
labels = ['label1', 'label2'] # Extend this list as needed
parameters_combinations = [
{'model_name': 'distilbert-base-uncased', 'batch_size': 16, 'epochs': 3},
{'model_name': 'bert-base-uncased', 'batch_size': 8, 'epochs': 5},
# Add more combinations here
]
# Function to compute metrics
def compute_metrics(pred):
labels = pred.label_ids
preds = pred.predictions.argmax(-1)
acc = accuracy_score(labels, preds)
return {'accuracy': acc}
# Main loop over labels and parameters combinations
for label in labels:
dataset_path = f"datasets/{label}/"
# Validate dataset files
train_file_path = os.path.join(dataset_path, 'train.csv')
test_file_path = os.path.join(dataset_path, 'test.csv')
if not os.path.exists(train_file_path) or not os.path.exists(test_file_path):
print(f"Skipping label '{label}': Missing dataset files in {dataset_path}.")
continue
train_df = pd.read_csv(train_file_path)
test_df = pd.read_csv(test_file_path)
# Assuming your text data is in a column named 'text' and labels in 'label'
# Validate required columns
required_columns = ['text', 'label']
if not all(col in train_df.columns for col in required_columns) or not all(col in test_df.columns for col in required_columns):
print(f"Skipping label '{label}': Dataset is missing required 'text' or 'label' columns.")
continue
train_text, train_labels = train_df['text'], train_df['label']
test_text, test_labels = test_df['text'], test_df['label']
for params in parameters_combinations:
# Create config YAML file for current label and parameters
config_file_name = f"{label}_{params['model_name']}_{params['batch_size']}_{params['epochs']}.yaml"
with open(config_file_name, 'w') as file:
yaml.dump(params, file)
# Prepare model, tokenizer, and dataset
model_name = params['model_name']
model = AutoModelForSequenceClassification.from_pretrained(model_name, num_labels=len(set(train_labels)))
tokenizer = AutoTokenizer.from_pretrained(model_name)
# Tokenize datasets
train_encodings = tokenizer(train_text.tolist(), truncation=True, padding=True)
test_encodings = tokenizer(test_text.tolist(), truncation=True, padding=True)
# Convert to torch datasets
class Dataset(torch.utils.data.Dataset):
def __init__(self, encodings, labels):
self.encodings = encodings
self.labels = labels
def __getitem__(self, idx):
item = {key: torch.tensor(val[idx]) for key, val in self.encodings.items()}
item['labels'] = torch.tensor(self.labels[idx])
return item
def __len__(self):
return len(self.labels)
train_dataset = Dataset(train_encodings, train_labels)
test_dataset = Dataset(test_encodings, test_labels)
# Training arguments
training_args = TrainingArguments(
output_dir=f"./{label}_{model_name}_results", # output directory
num_train_epochs=params['epochs'],
per_device_train_batch_size=params['batch_size'],
per_device_eval_batch_size=params['batch_size'],
evaluation_strategy="epoch",
learning_rate=5e-5,
save_total_limit=2,
save_steps=500,
load_best_model_at_end=True,
metric_for_best_model="accuracy",
greater_is_better=True,
save_on_each_node=True,
)
# Initialize our Trainer
trainer = Trainer(
model=model,
args=training_args,
train_dataset=train_dataset,
eval_dataset=test_dataset,
compute_metrics=compute_metrics,
)
# Train the model
trainer.train()
# Evaluate the model
eval_result = trainer.evaluate()
# Save evaluation results
with open("evaluation_results.txt", "a") as file:
file.write(f"Label: {label}, Model: {model_name}, Batch Size: {params['batch_size']}, Epochs: {params['epochs']}\n")
file.write(f"Accuracy: {eval_result['eval_accuracy']}\n\n")
print(f"Done with Label: {label}, Model: {model_name}, Batch Size: {params['batch_size']}, Epochs: {params['epochs']}")
Important Notes:
Customization: This script is a starting point. You might need to adjust it based on your specific dataset structure, column names, and the exact requirements of your project. For example, if your dataset uses different column names for text and labels, you will need to update the script accordingly.
Dataset Validation: The script checks if the required dataset files (train.csv and test.csv) exist for each label and if they contain the necessary columns ('text' and 'label'). If any of these conditions are not met, it skips the current label and logs a message.
Dependencies Installation: Ensure you have all necessary libraries installed. You can install them using pip: pip install transformers torch pandas numpy PyYAML.
Compute Resources: Training multiple models, especially with larger architectures, can be computationally intensive. Be mindful of your resource constraints.
Adaptability: While the script assumes a specific structure, it is designed to be flexible. You can modify the labels list, parameters_combinations, and dataset paths as needed. Additionally, you can customize the compute_metrics function to include more evaluation metrics.