To enhance your metric evaluation, we'll refine the custom F1 score by incorporating n-gram overlaps and a weighting strategy. Additionally, we'll integrate the ROUGE metric into the compute_metrics function. Here's how you can achieve this:
-
Enhanced Custom F1 Score with N-gram Overlaps and Weighting:
- N-gram Overlaps: Instead of only considering unigram (single word) overlaps, we'll compute overlaps for multiple n-grams (e.g., unigrams, bigrams, trigrams, and four-grams).
- Weighting Strategy: Assign different weights to each n-gram level to emphasize the importance of higher-order n-grams. For example, trigrams and four-grams might be weighted more heavily than unigrams and bigrams, as they capture more contextual information.
-
Incorporate ROUGE Metric:
- We'll use the
evaluate library to load the ROUGE metric and compute it alongside the existing metrics.
Here's the refined code with detailed comments:
import numpy as np
import evaluate
from nltk.util import ngrams
from collections import Counter
# Ensure you have NLTK's punkt tokenizer downloaded
import nltk
nltk.download('punkt')
def f1_score_custom(preds, labels, max_n=4, weights=None):
"""
Compute a weighted F1 score based on n-gram overlaps between predictions and labels.
Args:
preds (list of str): Predicted texts.
labels (list of str): Reference texts.
max_n (int): Maximum n-gram level to consider.
weights (dict): Weights for each n-gram level. If None, equal weights are used.
Returns:
float: Weighted F1 score averaged over all predictions.
"""
if weights is None:
# Assign higher weights to higher n-grams
weights = {n: n for n in range(1, max_n + 1)}
total_f1 = 0
for p, l in zip(preds, labels):
p_tokens = nltk.word_tokenize(p.lower())
l_tokens = nltk.word_tokenize(l.lower())
f1_scores = []
for n in range(1, max_n + 1):
p_ngrams = Counter(ngrams(p_tokens, n))
l_ngrams = Counter(ngrams(l_tokens, n))
common_ngrams = p_ngrams & l_ngrams
num_common = sum(common_ngrams.values())
if len(p_ngrams) == 0 or len(l_ngrams) == 0:
f1 = 0
else:
precision = num_common / sum(p_ngrams.values())
recall = num_common / sum(l_ngrams.values())
if precision + recall == 0:
f1 = 0
else:
f1 = 2 * precision * recall / (precision + recall)
f1_scores.append(weights[n] * f1)
# Normalize by the total weight
weighted_f1 = sum(f1_scores) / sum(weights.values())
total_f1 += weighted_f1
return total_f1 / len(preds) if len(preds) > 0 else 0
# Load evaluation metrics
metric_bert = evaluate.load("bertscore")
metric_meteor = evaluate.load("meteor")
metric_rouge = evaluate.load("rouge")
def compute_metrics(eval_pred, tokenizer):
"""
Compute evaluation metrics including custom weighted F1, METEOR, BERTScore, and ROUGE.
Args:
eval_pred (tuple): Tuple containing predictions and labels.
tokenizer (PreTrainedTokenizer): Tokenizer used to decode the predictions and labels.
Returns:
dict: Dictionary containing all computed metrics.
"""
preds, labels = eval_pred
# If logits are returned as a tuple, extract the first element
if isinstance(preds, tuple):
preds = preds[0]
# Replace -100 in labels as we can't decode them
preds = np.where(preds != -100, preds, tokenizer.pad_token_id)
labels = np.where(labels != -100, labels, tokenizer.pad_token_id)
# Decode the predicted tokens into text
decoded_preds = tokenizer.batch_decode(preds, skip_special_tokens=True)
decoded_labels = tokenizer.batch_decode(labels, skip_special_tokens=True)
# Post-process predictions and labels
decoded_preds = [pred.strip() for pred in decoded_preds]
decoded_labels = [label.strip() for label in decoded_labels]
# Prepare references for metrics that expect a list of references
references = [[label] for label in decoded_labels]
# Flatten labels for F1 and METEOR calculation
flattened_labels = [label for label in decoded_labels] # Assuming each label list contains one element
# Compute Custom Weighted F1 Score
f1_score = f1_score_custom(decoded_preds, flattened_labels, max_n=4)
# Compute METEOR
meteor_result = metric_meteor.compute(predictions=decoded_preds, references=flattened_labels)
meteor_score = meteor_result["meteor"]
# Compute BERTScore (using default 'bert-base-uncased' model)
bert_result = metric_bert.compute(predictions=decoded_preds, references=flattened_labels, lang="en")
bert_score_f1 = np.mean(bert_result["f1"])
# Compute ROUGE
rouge_result = metric_rouge.compute(predictions=decoded_preds, references=flattened_labels, use_stemmer=True)
# Extract average scores for ROUGE-1, ROUGE-2, ROUGE-L
rouge1 = rouge_result["rouge1"].mid.fmeasure * 100
rouge2 = rouge_result["rouge2"].mid.fmeasure * 100
rougel = rouge_result["rougeL"].mid.fmeasure * 100
# Combine the metrics
result = {
"f1_weighted": f1_score * 100,
"meteor": meteor_score * 100, # Express METEOR as percentage
"bert_score_f1": bert_score_f1 * 100, # Express BERTScore F1 as percentage
"rouge1": rouge1,
"rouge2": rouge2,
"rougeL": rougel
}
return result
Detailed Explanation
-
Custom Weighted F1 Score (f1_score_custom):
- N-gram Extraction: Using NLTK's
ngrams function, we extract n-grams up to max_n (default is 4). For each n from 1 to 4, we generate n-grams for both prediction and label.
- Counting Common N-grams: We use Python's
Counter to count the frequency of each n-gram. The intersection p_ngrams & l_ngrams gives the common n-grams between prediction and label.
- Precision and Recall: Calculated for each n-gram level. Precision is the ratio of common n-grams to total predicted n-grams, and recall is the ratio of common n-grams to total label n-grams.
- F1 Calculation: The F1 score is computed for each n-gram level and then weighted according to the predefined
weights. By default, higher n-grams are given higher weights, emphasizing the importance of capturing more contextual information.
- Averaging: The weighted F1 scores are averaged over all predictions.
-
Incorporating ROUGE Metric:
- Loading ROUGE: We load the ROUGE metric using
evaluate.load("rouge").
- Computing ROUGE Scores: After decoding the predictions and labels, we compute ROUGE scores (
rouge1, rouge2, and rougeL) using the compute method. We use stemming (use_stemmer=True) to improve matching by reducing words to their root forms.
- Extracting F-scores: ROUGE returns precision, recall, and F1 (fmeasure). We extract the F1 scores (
rouge1.mid.fmeasure, etc.) and multiply by 100 to express them as percentages.
-
Final compute_metrics Function:
- Decoding and Preprocessing: Predictions and labels are decoded from token IDs to strings. Special tokens are skipped, and any padding tokens (
-100) are replaced with the tokenizer's pad token.
- Metrics Calculation: The function computes the custom weighted F1 score, METEOR, BERTScore (F1), and ROUGE scores.
- Result Compilation: All metrics are compiled into a dictionary and returned. This allows for easy logging and monitoring during training and evaluation.
Additional Tips
-
Tokenizer Dependency: Ensure that the tokenizer is passed to the compute_metrics function if it's defined outside the scope. Alternatively, you can use a closure or a class to encapsulate both the tokenizer and the metrics.
# Example using a closure
def get_compute_metrics(tokenizer):
def compute_metrics(eval_pred):
# [Insert the compute_metrics function here]
...
return compute_metrics
compute_metrics_fn = get_compute_metrics(tokenizer)
-
Handling Multiple References: If you have multiple reference translations or answers per prediction, adjust the decoded_labels accordingly. The current implementation assumes one reference per prediction.
-
Performance Considerations: Computing n-grams and multiple metrics can be computationally intensive for large datasets. Consider optimizing or parallelizing if performance is a concern.
-
Installing Dependencies: Make sure to install the necessary libraries if you haven't already:
pip install evaluate nltk
Additionally, NLTK's punkt tokenizer is downloaded within the script, but ensure that the environment has internet access or pre-download it as needed.
By implementing these enhancements, your evaluation will capture more nuanced aspects of the model's performance, providing a more comprehensive assessment.