Calculate the perplexity of a language model given a list of predicted probabilities for the actual next tokens in a sequence. Perplexity measures how well a probability model predicts a sample and is defined as the exponentiation of the average negative log-likelihood.
import math
from typing import List
def calculate_perplexity(probabilities: List[float]) -> float:
n = len(probabilities)
if n == 0:
raise ValueError("Empty probability list")
log_likelihood = 0.0
for p in probabilities:
if p <= 0:
raise ValueError("Probabilities must be positive")
log_likelihood += math.log(p)
avg_neg_log_likelihood = -log_likelihood / n
perplexity = math.exp(avg_neg_log_likelihood)
return round(perplexity, 4)