This is my training data, I want to fine tune DistilBERT model on that, how to do that
text,labels
"I’m looking for a hobby that teaches me survival and outdoor skills.","Survival Skills,Outdoor Skills"
"Can you recommend a hobby to improve my sense of timing and coordination?","Timing,Coordination"
"I want a hobby that’s intellectually challenging and fosters curiosity.","Scientific Curiosity,Logical Reasoning"
"I’d love to try a hobby that involves experimenting with flavors and food science.","Flavor Pairing,Chemistry"
"What’s a fun hobby to improve my editing and audio production skills?","Audio Editing,Technology"
"I want an eco-friendly hobby that connects me with sustainability practices.","Sustainability,Environmental Awareness"
"Can you suggest a hobby where I can improve my breathing and relaxation?","Breathing Control,Stress Relief"
"Looking for a high-energy activity that tests my stamina and strength.","Stamina,Strength"
"I’d like to learn to make drinks, like coffee or cocktails, as a hobby.","Brewing Techniques,Flavor Combinations"
"What’s a good hobby for exploring new places and enjoying the outdoors?","Exploration,Outdoor Activity"
"I want a creative hobby to improve my skills with colors and patterns.","Color Theory,Design Sense"
"Can you recommend a hobby that involves strategy and thinking ahead?","Strategy,Logical Reasoning"
"I’d like a musical hobby to develop my vocal control and performance skills.","Vocal Control,Performance Skills"
"What’s a hobby that helps me stay fit while improving balance and flexibility?","Balance,Flexibility"
"I’m interested in a hobby that lets me practice gardening and taking care of plants.","Horticulture,Nature Appreciation"
"I want to try a hobby that sharpens my observation and attention to detail.","Observation,Critical Thinking"
"What’s a hobby that involves creating art and developing craftsmanship?","Craftsmanship,Art Appreciation"
"I want a hobby where I can practice teamwork and leadership skills.","Teamwork,Leadership"
"I’m looking for a hobby that lets me explore wildlife and learn about animals.","Wildlife Appreciation,Environmental Awareness"
"Can you recommend a hobby that helps with mental focus and clarity?","Mental Clarity,Mindfulness"
"I’d like to learn a skill that involves crafting functional or decorative items.","Crafting,Artistic Skills"
"What’s a hobby where I can explore historical stories and reenact events?","Historical Appreciation,Storytelling"
"I want a fitness hobby that also improves my cardiovascular health.","Cardiovascular Health,Endurance"
"Can you suggest a hobby where I can create unique and stylish designs?","Design Skills,Aesthetic Appreciation"
"I’d like a hobby to explore flavors and develop my sensory skills.","Sensory Analysis,Cooking"
"What’s a hobby to help me understand photography and creative editing?","Photography,Digital Media"
Assistant
Fine-tuning a DistilBERT model for your specific dataset involves several steps. Assuming you are familiar with Python and have some experience using libraries like Hugging Face's Transformers and PyTorch or TensorFlow, here’s a step-by-step guide on how to proceed:
Prerequisites
Python Installed: Make sure you have Python installed on your machine.
Libraries: You'll need the following libraries. You can install them using pip:
If you plan to use TensorFlow, you can install it instead of PyTorch.
Step 1: Load Your Data
First, you need to load your dataset. You can use the Pandas library to achieve this.
python
import pandas as pd
# Load the dataset
data = pd.read_csv('path_to_your_data.csv')
# Split into texts and labels
texts = data['text'].tolist()
labels = data['labels'].tolist()
Step 2: Preprocess Your Data
You need to convert the labels into a format that can be used for training. Assuming you want to treat this as a multi-label classification problem. Here's how you can prepare the labels:
python
from sklearn.preprocessing import MultiLabelBinarizer
# Convert labels to a list of lists
labels = [label.split(',') for label in labels]
# Use MultiLabelBinarizer to convert labels to binary format
mlb = MultiLabelBinarizer()
labels = mlb.fit_transform(labels)
Step 3: Tokenize Your Input Data
Next, use the tokenizer from the Transformers library to tokenize your input texts.
python
from transformers import DistilBertTokenizer
# Load the tokenizer
tokenizer = DistilBertTokenizer.from_pretrained('distilbert-base-uncased')
# Tokenize the texts
encodings = tokenizer(texts, truncation=True, padding=True, return_tensors='pt')
File c:\Users\Marcin\anaconda3\Lib\site-packages\transformers\trainer.py:2279, in Trainer._inner_training_loop(self, batch_size, args, resume_from_checkpoint, trial, ignore_keys_for_eval)
2276 self.control = self.callback_handler.on_step_begin(args, self.state, self.control)
2278 with self.accelerator.accumulate(model):
-> 2279 tr_loss_step = self.training_step(model, inputs)
2281 if (
2282 args.logging_nan_inf_filter
2283 and not is_torch_xla_available()
2284 and (torch.isnan(tr_loss_step) or torch.isinf(tr_loss_step))
2285 ):
2286 # if loss is nan or inf simply add the average of previous logged losses
2287 tr_loss += tr_loss / (1 + self.state.global_step - self._globalstep_last_logged)
File c:\Users\Marcin\anaconda3\Lib\site-packages\transformers\trainer.py:3318, in Trainer.training_step(self, model, inputs)
3315 return loss_mb.reduce_mean().detach().to(self.args.device)
3317 with self.compute_loss_context_manager():
-> 3318 loss = self.compute_loss(model, inputs)
3320 del inputs
3321 if (
3322 self.args.torch_empty_cache_steps is not None
3323 and self.state.global_step % self.args.torch_empty_cache_steps == 0
3324 ):
File c:\Users\Marcin\anaconda3\Lib\site-packages\transformers\trainer.py:3363, in Trainer.compute_loss(self, model, inputs, return_outputs)
3361 else:
3362 labels = None
-> 3363 outputs = model(**inputs)
3364 # Save past state if it exists
3365 # TODO: this needs to be fixed and made cleaner later.
3366 if self.args.past_index >= 0:
File c:\Users\Marcin\anaconda3\Lib\site-packages\torch
n\modules\module.py:1562, in Module._call_impl(self, *args, **kwargs)
1557 # If we don't have any hooks, we want to skip the rest of the logic in
1558 # this function, and just call forward.
1559 if not (self._backward_hooks or self._backward_pre_hooks or self._forward_hooks or self._forward_pre_hooks
1560 or _global_backward_pre_hooks or _global_backward_hooks
1561 or _global_forward_hooks or _global_forward_pre_hooks):
-> 1562 return forward_call(*args, **kwargs)
1564 try:
1565 result = None
Assistant
The error you're encountering (Expected input batch_size (8) to match target batch_size (400)) suggests that there is a mismatch between the shape of the model's output (logits) and the shape of the labels being passed to the loss function.
Possible Causes
Multi-label Classification: It seems you are treating the problem as a multi-label classification problem. The error suggests that the model is expecting a different output format than what it is currently receiving.
Logits and Labels Shape: The DistilBertForSequenceClassification model by default is set up for single-label classification (which uses CrossEntropyLoss). For multi-label classification, it should connect with BCEWithLogitsLoss, which expects the output logits and the labels to match in terms of shape.
Solution
You will need to modify the model to handle multi-label classification properly. Here's how to do it:
Use DistilBertForSequenceClassification with Adjusted Output Layer: Specify num_labels according to the number of unique labels in your dataset.
Change the Model Type:
Use BCEWithLogitsLoss instead of CrossEntropyLoss.
Make sure the labels are formatted as float tensors in the range [0, 1].
Adjust the Configuration: Here’s how to adjust the model to fit multi-label classification.
Implementation Steps
Step 1: Modify the Model for Multi-label Classification
When initializing the model, set the appropriate classification head and loss function:
python
from transformers import DistilBertForSequenceClassification, Trainer, TrainingArguments
# Modify the model to handle multi-label classification
model = DistilBertForSequenceClassification.from_pretrained('distilbert-base-uncased',
num_labels=len(mlb.classes_),
problem_type="multi_label_classification")
Step 2: Ensure Labels are in the Right Format
User
Create a code in 1 cell
Assistant
You can consolidate all the steps into a single cell for ease of execution. Below is the complete code to fine-tune a DistilBERT model on your dataset for multi-label classification. Make sure to install the required libraries (transformers, torch, pandas, and scikit-learn) before running this code.
python
import pandas as pd
import torch
from torch.utils.data import Dataset
from transformers import DistilBertTokenizer, DistilBertForSequenceClassification, Trainer, TrainingArguments
from sklearn.preprocessing import MultiLabelBinarizer
# Load dataset
data = pd.read_csv('path_to_your_data.csv')
texts = data['text'].tolist()
labels = [label.split(',') for label in data['labels'].tolist()]
# Multi-label binarization
mlb = MultiLabelBinarizer()
labels = mlb.fit_transform(labels)
# Tokenization
tokenizer = DistilBertTokenizer.from_pretrained('distilbert-base-uncased')
encodings = tokenizer(texts, truncation=True, padding=True, return_tensors='pt')
# Custom Dataset Class
class CustomDataset(Dataset):
def __init__(self, encodings, labels):
self.encodings = encodings
self.labels = torch.tensor(labels, dtype=torch.float32) # Convert labels to float tensor
def __getitem__(self, idx):
item = {key: val[idx] for key, val in self.encodings.items()}
item['labels'] = self.labels[idx] # Use pre-converted float tensor
return item
def __len__(self):
return len(self.labels)
# Create Dataset
dataset = CustomDataset(encodings, labels)
# Load DistilBERT model
model = DistilBertForSequenceClassification.from_pretrained('distilbert-base-uncased',
num_labels=len(mlb.classes_),
problem_type="multi_label_classification")
# Training arguments
training_args = TrainingArguments(
output_dir='./results',
evaluation_strategy='epoch',
learning_rate=2e-5,
per_device_train_batch_size=8,
num_train_epochs=3,
weight_decay=0.01,
)
# Trainer
trainer = Trainer(
model=model,
args=training_args,
train_dataset=dataset,
)
# Train the model
trainer.train()
# Save the model
model.save_pretrained('my_fine_tuned_model')
tokenizer.save_pretrained('my_fine_tuned_model')
User
ValueError Traceback (most recent call last)
Cell In[34], line 60
53 trainer = Trainer(
54 model=model,
55 args=training_args,
56 train_dataset=dataset,
57 )
59 # Train the model
---> 60 trainer.train()
62 # Save the model
63 model.save_pretrained('my_fine_tuned_model')
File c:\Users\Marcin\anaconda3\Lib\site-packages\transformers\trainer.py:2376, in Trainer._inner_training_loop(self, batch_size, args, resume_from_checkpoint, trial, ignore_keys_for_eval)
2373 self.control.should_training_stop = True
...
947 # If we have persistent workers, don't do a fork bomb especially as eval datasets
948 # don't change during training
949 dataloader_key = eval_dataset if isinstance(eval_dataset, str) else "eval"
ValueError: Trainer: evaluation requires an eval_dataset.
Assistant
The error you encountered indicates that the Trainer class is set up to perform evaluation during training, but you haven't provided an evaluation dataset (eval_dataset). This is an optional step, and you can proceed without it if evaluation is not necessary for your current needs.
If you want to remove this requirement, you can simply modify the TrainingArguments to set the evaluation strategy to "no", or you can provide an evaluation dataset if you have one. Below are two options for handling this:
Option 1: Disable Evaluation
If you don't need evaluation during training, set the evaluation_strategy to 'no' in the TrainingArguments:
I want to have evaluation, split the dataset to train test val
Assistant
To split your dataset into training, validation, and test sets while retaining your multi-label setup, you'll want to follow this approach. The common practice is to allocate your data roughly as follows: 70% for training, 15% for validation, and 15% for testing.
Here's a complete code example that includes splitting your dataset and setting up the model for training with evaluation:
python
User
Split the code to before creating dataset with test train val sets, and next cell with training on 10 epochs.
Assistant
Certainly! Below is how you can structure the code into two separate cells. The first cell handles loading the dataset, preprocessing, and splitting it into training, validation, and test sets. The second cell focuses on training the model for 10 epochs.
Cell 1: Data Loading, Preprocessing, and Splitting
python
import pandas as pd
import torch
from torch.utils.data import Dataset
from transformers import DistilBertTokenizer
from sklearn.preprocessing import MultiLabelBinarizer
from sklearn.model_selection import train_test_split
# Load dataset
data = pd.read_csv('path_to_your_data.csv') # Update this with your actual path
texts = data['text'].tolist()
labels = [label.split(',') for label in data['labels'].tolist()]
# Multi-label binarization
mlb = MultiLabelBinarizer()
labels = mlb.fit_transform(labels)
# Split the dataset into train, validation, and test sets (70% train, 15% val, 15% test)
train_texts, temp_texts, train_labels, temp_labels = train_test_split(
texts, labels, test_size=0.3, random_state=42
)
val_texts, test_texts, val_labels, test_labels = train_test_split(
temp_texts, temp_labels, test_size=0.5, random_state=42
)
# Tokenization for train, validation, and test sets
tokenizer = DistilBertTokenizer.from_pretrained('distilbert-base-uncased')
train_encodings = tokenizer(train_texts, truncation=True, padding=True, return_tensors='pt')
val_encodings = tokenizer(val_texts, truncation=True, padding=True, return_tensors='pt')
test_encodings = tokenizer(test_texts, truncation=True, padding=True, return_tensors='pt')
# Custom Dataset Class
class CustomDataset(Dataset):
def __init__(self, encodings, labels):
self.encodings = encodings
self.labels = torch.tensor(labels, dtype=torch.float32)
def __getitem__(self, idx):
item = {key: val[idx] for key, val in self.encodings.items()}
item['labels'] = self.labels[idx]
return item
def __len__(self):
return len(self.labels)
# Create datasets
train_dataset = CustomDataset(train_encodings, train_labels)
val_dataset = CustomDataset(val_encodings, val_labels)
test_dataset = CustomDataset(test_encodings, test_labels)
# Save the tokenized datasets and labels for use in the second cell if needed
torch.save(train_dataset, 'train_dataset.pt')
torch.save(val_dataset, 'val_dataset.pt')
torch.save(test_dataset, 'test_dataset.pt')
# Save the MultiLabelBinarizer for encoding/decoding labels
import joblib
joblib.dump(mlb, 'mlb.joblib')
User
Now perform inference of this fine tuned model on query like that:
"recommend hobby timing coordination"
Assistant
To perform inference using your fine-tuned DistilBERT model, you need to follow a series of steps. This involves tokenizing the input text, passing it to the model, and then processing the output to get your predicted labels.
Here’s how you can do this in a new cell after you've completed the training:
Inference Code
python
import torch
from transformers import DistilBertTokenizer, DistilBertForSequenceClassification
import joblib
# Load the fine-tuned model and tokenizer
model = DistilBertForSequenceClassification.from_pretrained('my_fine_tuned_model')
tokenizer = DistilBertTokenizer.from_pretrained('my_fine_tuned_model')
# Load the MultiLabelBinarizer to decode the labels
mlb = joblib.load('mlb.joblib')
# Set the model to evaluation mode
model.eval()
# Define the input query
query = "recommend hobby timing coordination"
# Tokenize the input
inputs = tokenizer(query, truncation=True, padding=True, return_tensors='pt')
# Perform inference
with torch.no_grad():
logits = model(**inputs).logits
# Get probabilities (using sigmoid for multi-label)
probabilities = torch.sigmoid(logits)
# Convert probabilities to binary predictions (thresholding at 0.5)
predictions = (probabilities > 0.5).int()
# Get the predicted labels
predicted_labels = mlb.inverse_transform(predictions.numpy())
# Display the results
print(f"Query: {query}")
print(f"Predicted Labels: {predicted_labels}")
Explanation of the Code
Load Model and Tokenizer: Load your fine-tuned model and tokenizer from the saved directory.
Load MultiLabelBinarizer: This is used to decode your label predictions back into readable format.
Set Model to Evaluation Mode: This is necessary to ensure that dropout layers (if present) behave appropriately during inference.
User
I want to see also probabilities of each label predicted
Assistant
To see the probabilities of each label predicted by your fine-tuned DistilBERT model, you can modify the inference code to include the probabilities alongside the predicted labels. Below is the updated code that prints the predicted labels along with their associated probabilities:
Inference Code with Probabilities
python
import torch
from transformers import DistilBertTokenizer, DistilBertForSequenceClassification
import joblib
# Load the fine-tuned model and tokenizer
model = DistilBertForSequenceClassification.from_pretrained('my_fine_tuned_model')
tokenizer = DistilBertTokenizer.from_pretrained('my_fine_tuned_model')
# Load the MultiLabelBinarizer to decode the labels
mlb = joblib.load('mlb.joblib')
# Set the model to evaluation mode
model.eval()
# Define the input query
query = "recommend hobby timing coordination"
# Tokenize the input
inputs = tokenizer(query, truncation=True, padding=True, return_tensors='pt')
# Perform inference
with torch.no_grad():
logits = model(**inputs).logits
# Get probabilities (using sigmoid for multi-label classification)
probabilities = torch.sigmoid(logits)
# Convert probabilities to binary predictions (thresholding at 0.5)
predictions = (probabilities > 0.5).int()
# Get the predicted labels
predicted_labels = mlb.inverse_transform(predictions.numpy())
# Prepare probabilities for labels
probabilities_numpy = probabilities.numpy()
# Display the results
print(f"Query: {query}")
print(f"Predicted Labels: {predicted_labels}")
# Print probabilities with their associated labels
for i, label in enumerate(mlb.classes_):
print(f"Label: {label}, Probability: {probabilities_numpy[0][i]:.4f}")
Explanation of Changes
User
also sorted by probabilities
Assistant
To display the predicted labels and their probabilities sorted by the probabilities in descending order, you can modify the inference code to create a sorted list of probabilities along with their associated labels. Below is the modified code:
Inference Code with Sorted Probabilities
python
import torch
from transformers import DistilBertTokenizer, DistilBertForSequenceClassification
import joblib
import numpy as np
# Load the fine-tuned model and tokenizer
model = DistilBertForSequenceClassification.from_pretrained('my_fine_tuned_model')
tokenizer = DistilBertTokenizer.from_pretrained('my_fine_tuned_model')
# Load the MultiLabelBinarizer
mlb = joblib.load('mlb.joblib')
# Set the model to evaluation mode
model.eval()
# Define the input query
query = "recommend hobby timing coordination"
# Tokenize the input
inputs = tokenizer(query, truncation=True, padding=True, return_tensors='pt')
# Perform inference
with torch.no_grad():
logits = model(**inputs).logits
# Get probabilities using sigmoid for multi-label classification
probabilities = torch.sigmoid(logits)
# Prepare probabilities for labels
probabilities_numpy = probabilities.numpy().flatten() # Flatten to 1D
# Pair each label with its probability
label_prob_pairs = list(zip(mlb.classes_, probabilities_numpy))
# Sort pairs by probability in descending order
sorted_label_prob_pairs = sorted(label_prob_pairs, key=lambda x: x[1], reverse=True)
# Display the results
print(f"Query: {query}")
print("Predicted Labels and Probabilities (sorted):")
# Print sorted labels with probabilities
for label, prob in sorted_label_prob_pairs:
print(f"Label: {label}, Probability: {prob:.4f}")
Not yet included in a published release.
Step 4: Create a Dataset Class
Now, create a PyTorch dataset class to handle loading and batching your data.
python
import torch
from torch.utils.data import Dataset
class CustomDataset(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)
# Create dataset
dataset = CustomDataset(encodings, labels)
Step 5: Fine-tune DistilBERT
Now you can create a model and fine-tune it on your dataset.
python
from transformers import DistilBertForSequenceClassification, Trainer, TrainingArguments
# Load the model
model = DistilBertForSequenceClassification.from_pretrained('distilbert-base-uncased', num_labels=len(mlb.classes_))
# Define training arguments
training_args = TrainingArguments(
output_dir='./results',
evaluation_strategy='epoch',
learning_rate=2e-5,
per_device_train_batch_size=8,
num_train_epochs=3,
weight_decay=0.01,
)
# Define Trainer
trainer = Trainer(
model=model,
args=training_args,
train_dataset=dataset,
)
# Train
trainer.train()
You can evaluate your model on a validation set or during the training process by passing in additional data.
Notes
You may want to split your data into training and validation sets to evaluate the performance of your model effectively.
Hyperparameters such as learning rate, batch size, and number of epochs may need to be tuned based on your specific dataset.
Ensure your system has enough resources when training, especially if the dataset is large.
This guide provides an overview, so feel free to expand upon it based on your specific requirements (metrics, data splits, etc.). If you have any specific questions, feel free to ask!
File c:\Users\Marcin\anaconda3\Lib\site-packages\torch
n\modules\module.py:1562, in Module._call_impl(self, *args, **kwargs)
1557 # If we don't have any hooks, we want to skip the rest of the logic in
1558 # this function, and just call forward.
1559 if not (self._backward_hooks or self._backward_pre_hooks or self._forward_hooks or self._forward_pre_hooks
1560 or _global_backward_pre_hooks or _global_backward_hooks
1561 or _global_forward_hooks or _global_forward_pre_hooks):
-> 1562 return forward_call(*args, **kwargs)
1564 try:
1565 result = None
File c:\Users\Marcin\anaconda3\Lib\site-packages\torch
n\functional.py:3104, in cross_entropy(input, target, weight, size_average, ignore_index, reduce, reduction, label_smoothing)
3102 if size_average is not None or reduce is not None:
3103 reduction = _Reduction.legacy_get_string(size_average, reduce)
-> 3104 return torch._C._nn.cross_entropy_loss(input, target, weight, _Reduction.get_enum(reduction), ignore_index, label_smoothing)
ValueError: Expected input batch_size (8) to match target batch_size (400)."
}
Ensure that your labels are in the form of float tensors and that their shape matches the output from the model:
python
from sklearn.preprocessing import MultiLabelBinarizer
# Convert labels to a list of lists
labels = [label.split(',') for label in labels]
# Use MultiLabelBinarizer to convert labels to binary format
mlb = MultiLabelBinarizer()
labels = mlb.fit_transform(labels)
# Convert to torch tensor and ensure dtype
labels = torch.tensor(labels, dtype=torch.float32)
Step 3: Use the Modified Dataset Class
When creating the dataset, ensure it passes the labels correctly:
python
class CustomDataset(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'] = self.labels[idx] # No conversion, already a torch.tensor
return item
def __len__(self):
return len(self.labels)
Step 4: Run Trainer
When you set up the Trainer, there is no need for additional special configurations since we have already specified the problem type during model initialization.
python
# Define training arguments
training_args = TrainingArguments(
output_dir='./results',
evaluation_strategy='epoch',
learning_rate=2e-5,
per_device_train_batch_size=8,
num_train_epochs=3,
weight_decay=0.01,
)
trainer = Trainer(
model=model,
args=training_args,
train_dataset=dataset,
)
# Train the model
trainer.train()
This setup allows the model to handle multi-label classifications correctly by matching labels and outputs. If you continue to encounter issues, please double-check the shapes of the tensors being passed during training.
Instructions to Run
Update the 'path_to_your_data.csv' with the actual path to your CSV file containing the dataset.
Run the code cell after ensuring you have all required libraries installed and your environment is properly set up.
This cell combines all necessary steps from loading the data to training and saving the model, handling multi-label classification correctly with DistilBERT.
import pandas as pd
import torch
from torch.utils.data import Dataset
from transformers import DistilBertTokenizer, DistilBertForSequenceClassification, Trainer, TrainingArguments
from sklearn.preprocessing import MultiLabelBinarizer
# Load dataset
data = pd.read_csv('path_to_your_data.csv')
texts = data['text'].tolist()
labels = [label.split(',') for label in data['labels'].tolist()]
# Multi-label binarization
mlb = MultiLabelBinarizer()
labels = mlb.fit_transform(labels)
# Tokenization
tokenizer = DistilBertTokenizer.from_pretrained('distilbert-base-uncased')
encodings = tokenizer(texts, truncation=True, padding=True, return_tensors='pt')
# Custom Dataset Class
class CustomDataset(Dataset):
def __init__(self, encodings, labels):
self.encodings = encodings
self.labels = torch.tensor(labels, dtype=torch.float32)
def __getitem__(self, idx):
item = {key: val[idx] for key, val in self.encodings.items()}
item['labels'] = self.labels[idx]
return item
def __len__(self):
return len(self.labels)
# Create Dataset
dataset = CustomDataset(encodings, labels)
# Load DistilBERT model
model = DistilBertForSequenceClassification.from_pretrained('distilbert-base-uncased',
num_labels=len(mlb.classes_),
problem_type="multi_label_classification")
# Training arguments
training_args = TrainingArguments(
output_dir='./results',
evaluation_strategy='no', # Disable evaluation
learning_rate=2e-5,
per_device_train_batch_size=8,
num_train_epochs=3,
weight_decay=0.01,
)
# Trainer
trainer = Trainer(
model=model,
args=training_args,
train_dataset=dataset,
)
# Train the model
trainer.train()
# Save the model
model.save_pretrained('my_fine_tuned_model')
tokenizer.save_pretrained('my_fine_tuned_model')
Option 2: Provide an Evaluation Dataset
If you have a separate evaluation dataset that you want to use, you can split your data into training and evaluation datasets. Here's how you could do it:
python
from sklearn.model_selection import train_test_split
# Split the dataset into training and evaluation sets
train_texts, eval_texts, train_labels, eval_labels = train_test_split(texts, labels, test_size=0.1, random_state=42)
# Tokenization for training and evaluation
train_encodings = tokenizer(train_texts, truncation=True, padding=True, return_tensors='pt')
eval_encodings = tokenizer(eval_texts, truncation=True, padding=True, return_tensors='pt')
# Create datasets
train_dataset = CustomDataset(train_encodings, train_labels)
eval_dataset = CustomDataset(eval_encodings, eval_labels)
# Trainer
trainer = Trainer(
model=model,
args=training_args,
train_dataset=train_dataset,
eval_dataset=eval_dataset, # Provide evaluation dataset
)
# Train the model
trainer.train()
# Save the model
model.save_pretrained('my_fine_tuned_model')
tokenizer.save_pretrained('my_fine_tuned_model')
Choose the option that best fits your situation! If you don't have a separate evaluation dataset, the first option to disable evaluation is simpler and often sufficient for quick training.
import pandas as pd
import torch
from torch.utils.data import Dataset
from transformers import DistilBertTokenizer, DistilBertForSequenceClassification, Trainer, TrainingArguments
from sklearn.preprocessing import MultiLabelBinarizer
from sklearn.model_selection import train_test_split
# Load dataset
data = pd.read_csv('path_to_your_data.csv')
texts = data['text'].tolist()
labels = [label.split(',') for label in data['labels'].tolist()]
# Multi-label binarization
mlb = MultiLabelBinarizer()
labels = mlb.fit_transform(labels)
# Split the dataset into train, validation, and test sets (70% train, 15% val, 15% test)
train_texts, temp_texts, train_labels, temp_labels = train_test_split(
texts, labels, test_size=0.3, random_state=42
)
val_texts, test_texts, val_labels, test_labels = train_test_split(
temp_texts, temp_labels, test_size=0.5, random_state=42
)
# Tokenization for train, validation, and test sets
tokenizer = DistilBertTokenizer.from_pretrained('distilbert-base-uncased')
train_encodings = tokenizer(train_texts, truncation=True, padding=True, return_tensors='pt')
val_encodings = tokenizer(val_texts, truncation=True, padding=True, return_tensors='pt')
test_encodings = tokenizer(test_texts, truncation=True, padding=True, return_tensors='pt')
# Custom Dataset Class
class CustomDataset(Dataset):
def __init__(self, encodings, labels):
self.encodings = encodings
self.labels = torch.tensor(labels, dtype=torch.float32)
def __getitem__(self, idx):
item = {key: val[idx] for key, val in self.encodings.items()}
item['labels'] = self.labels[idx]
return item
def __len__(self):
return len(self.labels)
# Create datasets
train_dataset = CustomDataset(train_encodings, train_labels)
val_dataset = CustomDataset(val_encodings, val_labels)
test_dataset = CustomDataset(test_encodings, test_labels)
# Load DistilBERT model
model = DistilBertForSequenceClassification.from_pretrained('distilbert-base-uncased',
num_labels=len(mlb.classes_),
problem_type="multi_label_classification")
# Training arguments
training_args = TrainingArguments(
output_dir='./results',
evaluation_strategy='epoch', # Evaluate at the end of each epoch
learning_rate=2e-5,
per_device_train_batch_size=8,
per_device_eval_batch_size=8, # Set for evaluation
num_train_epochs=3,
weight_decay=0.01,
)
# Trainer
trainer = Trainer(
model=model,
args=training_args,
train_dataset=train_dataset,
eval_dataset=val_dataset, # Use the validation dataset for evaluation
)
# Train the model
trainer.train()
# Evaluate on the validation set
eval_result = trainer.evaluate()
print(eval_result)
# Optionally evaluate on the test set
test_results = trainer.evaluate(test_dataset)
print(test_results)
# Save the model
model.save_pretrained('my_fine_tuned_model')
tokenizer.save_pretrained('my_fine_tuned_model')
Breakdown of the Steps
Load and Prepare Data:
Load your CSV data and split the labels into a binary format suitable for multi-label classification.
Dataset Splitting:
Use train_test_split from sklearn to create splits for training, validation, and test datasets.
Tokenization:
Tokenize the texts for each dataset.
Custom Dataset Class:
Create a dataset class to handle the tokenized inputs and their associated labels.
Model Initialization:
Load the DistilBERT model configured for multi-label classification.
Training Setup:
Specify training arguments and initiate the Trainer class, providing the training and validation datasets.
Training and Evaluation:
Train the model and evaluate its performance on the validation set after each epoch, and optionally evaluate it on the test set afterward.
Notes
Adjust the batch sizes and number of epochs according to your available computational resources.
The print statements for evaluation results will give you metrics based on the validation and test datasets, allowing you to confirm the model's performance.
This code should help you correctly set up training and evaluation of a DistilBERT model on your dataset!
Cell 2: Model Training
python
import torch
from transformers import DistilBertForSequenceClassification, Trainer, TrainingArguments
# Load datasets
train_dataset = torch.load('train_dataset.pt')
val_dataset = torch.load('val_dataset.pt')
test_dataset = torch.load('test_dataset.pt')
# Load DistilBERT model
model = DistilBertForSequenceClassification.from_pretrained('distilbert-base-uncased',
num_labels=len(train_dataset.labels[0]), # Get num_labels from first example
problem_type="multi_label_classification")
# Training arguments
training_args = TrainingArguments(
output_dir='./results',
evaluation_strategy='epoch', # Evaluate at the end of each epoch
learning_rate=2e-5,
per_device_train_batch_size=8,
per_device_eval_batch_size=8, # Set for evaluation
num_train_epochs=10, # Train for 10 epochs
weight_decay=0.01,
)
# Trainer
trainer = Trainer(
model=model,
args=training_args,
train_dataset=train_dataset,
eval_dataset=val_dataset, # Use the validation dataset for evaluation
)
# Train the model
trainer.train()
# Evaluate on the validation set
eval_result = trainer.evaluate()
print(eval_result)
# Optionally evaluate on the test set
test_results = trainer.evaluate(test_dataset)
print(test_results)
# Save the model
model.save_pretrained('my_fine_tuned_model')
tokenizer.save_pretrained('my_fine_tuned_model')
Instructions to Execute
Run Cell 1 to load your dataset, preprocess the data, binarize the labels, and create your train, validation, and test datasets.
Run Cell 2 to load the datasets, train the DistilBERT model for 10 epochs, evaluate it, and save the trained model.
Make sure to adjust 'path_to_your_data.csv' to the correct location of your CSV file. Additionally, ensure you have installed the necessary libraries before executing the code.
Tokenize the Input: Prepare your input text for the model by tokenizing it. This includes adding padding and truncation when necessary.
Perform Inference: Use torch.no_grad() to turn off gradient calculations, optimizing memory usage during inference. Get the model's logits.
Process Outputs:
Convert logits to probabilities using the sigmoid function.
Convert probabilities to binary predictions based on a threshold (e.g., 0.5).
Get Predicted Labels: Use the inverse_transform method of the MultiLabelBinarizer to convert the binary predictions back into the original label format.
Print the Results: Finally, print the input query and the corresponding predicted labels.
Running the Inference
After you train and save your model, run the inference code to get predictions for the specified query.
You can change the query string in the code to test other inputs as needed.
Make sure you have the model fine-tuned and saved before running this inference code. This implementation will allow you to see the recommended hobbies corresponding to your input text.
Calculate Probabilities: The line probabilities = torch.sigmoid(logits) gives you the probabilities associated with each label, as the output logits are converted into probabilities.
Prepare Probabilities Array: probabilities_numpy = probabilities.numpy() converts the tensor to a NumPy array for easier manipulation.
Display Probabilities: A loop over mlb.classes_ allows you to print each label along with its corresponding probability. The probabilities are formatted to four decimal places with :.4f.
Running the Inference
After you run this adjusted inference code, you will see the query, the predicted labels, and the probability associated with each label.
This will provide a clearer understanding of how confident the model is about each prediction.
Feel free to modify the query string to test different inputs and observe the results!
Explanation of Changes
Flatten the Probabilities: The line probabilities_numpy = probabilities.numpy().flatten() ensures that the probabilities array is flattened into a 1D array for easier pairing with labels.
Pairing Labels with Probabilities: label_prob_pairs is a list of tuples where each tuple contains a label and its corresponding probability, created using zip.
Sorting: The sorted function is used to sort the tuple pairs based on the probability values in descending order using the key=lambda x: x[1] argument.
Display Sorted Results: The sorted results are printed in a loop, showing each label alongside its probability formatted to four decimal places.
Running the Inference
After executing this adjusted inference code, you will receive a list of predicted labels for the input query, sorted by their associated probabilities. This allows you to quickly identify which labels the model is most confident about.