Proof read the snippet of code below: [code]
- User
Proof read the snippet of code below:
code# Import Libraries import evaluate import numpy as np # Define F1 Score (Custom Implementation) def f1_score_custom(preds, labels): f1_total = 0 for p, l in zip(preds, labels): p_tokens = p.split() l_tokens = l.split() common = set(p_tokens) & set(l_tokens) # If no common tokens, F1 score is 0 if len(common) == 0: f1_total += 0 else: precision = len(common) / len(p_tokens) if len(p_tokens) > 0 else 0 recall = len(common) / len(l_tokens) if len(l_tokens) > 0 else 0 if precision + recall > 0: f1_total += 2 * precision * recall / (precision + recall) return f1_total / len(preds) if len(preds) > 0 else 0 # Load required metrics metric_bert = evaluate.load("bertscore") metric_meteor = evaluate.load("meteor") # Define the compute_metrics function def compute_metrics(eval_pred): 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 preds and the 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] # METEOR and BERTScore expect a list of references # Flatten labels for F1 and METEOR calculation flattened_labels = [label[0] for label in decoded_labels] # Assuming each label list contains one element # Compute F1 Score f1_score = f1_score_custom(decoded_preds, flattened_labels) # 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"]) # Combine the metrics result = { "f1": f1_score, "meteor": meteor_score * 100, # Express METEOR as percentage "bert_score_f1": bert_score_f1 * 100 # Express BERTScore F1 as percentage } return result - Assistant