PIXELBANKv9.1.0
Menu

Perplexity Calculator

Calculate the perplexity of a language model on a test sentence.

Perplexity measures how well a probability model predicts a sample: Perplexity=exp⁡(−1N∑i=1Nlog⁡P(wi∣wi−1))\text{Perplexity} = \exp\left(-\frac{1}{N} \sum_{i=1}^{N} \log P(w_i | w_{i-1})\right)

Where N is the number of tokens in the test sentence (including </s> but not <s>).

Use the same bigram model with Laplace smoothing as the N-Gram Language Model problem.

Input format:

  • Line 1: Number of training sentences
  • Following lines: Training sentences
  • Last line: Test sentence

Output: Perplexity rounded to 4 decimal places.

Example:

Input:
2
the cat sat
the dog sat
the cat ran
Output:
3.1202
Reasoning:

Build bigram model (same as N-Gram LM problem)

Test: <s> the cat ran </s> N = 4 tokens (the, cat, ran, </s>)

Compute log probs for each bigram, sum them, divide by -N, then exp.

Perplexity = exp(-log_prob_sum / N)

Constraints:

  • N counts all tokens in test after <s> (including </s>)
  • Use Laplace-smoothed bigram probabilities
  • Use natural log and exp
  • Round to 4 decimal places
🔒

Editor locked

The code editor is locked for Pro problems. It is only available for free problems. Please upgrade to gain access to the code editor for all problems.

solution.py

Test Results

0/0
Run code to see test results.
Perplexity Calculator - Medium | PixelBank