v9.1.1
Menu

Perplexity Calculator

mediumPROLanguage ModelingNLP 3: Advanced

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

Learn this in

More from NLP 3: Advanced

PRO

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

Sign in to run your code against the test cases.