PIXELBANKv9.1.0
Menu

Build a bigram language model and compute the probability of a sentence.

Training: From the training text, count bigram frequencies and compute: P(wi∣wi−1)=count(wi−1,wi)count(wi−1)P(w_i | w_{i-1}) = \frac{\text{count}(w_{i-1}, w_i)}{\text{count}(w_{i-1})}

Use Laplace smoothing: P(wi∣wi−1)=count(wi−1,wi)+1count(wi−1)+VP(w_i | w_{i-1}) = \frac{\text{count}(w_{i-1}, w_i) + 1}{\text{count}(w_{i-1}) + V}

Where V is the vocabulary size (unique words in training).

Add special tokens: <s> for sentence start and </s> for sentence end.

Input format:

  • Line 1: Number of training sentences N
  • Lines 2 to N+1: Training sentences (lowercase words)
  • Line N+2: Test sentence (lowercase words)

Output: Log probability (base e) of the test sentence, rounded to 4 decimal places.

Example:

Input:
2
i love nlp
i love coding
i love nlp
Output:
-3.6636
Reasoning:

Training with <s> and </s>:

  • <s> i love nlp </s>
  • <s> i love coding </s>

Vocabulary: {<s>, i, love, nlp, coding, </s>} => V = 6

Bigram counts:

  • (<s>, i): 2, count(<s>): 2 => P(i|<s>) = (2+1)/(2+6) = 3/8
  • (i, love): 2, count(i): 2 => P(love|i) = 3/8
  • (love, nlp): 1, count(love): 2 => P(nlp|love) = 2/8
  • (nlp, </s>): 1, count(nlp): 1 => P(</s>|nlp) = 2/7

Test: <s> i love nlp </s> log P = log(3/8) + log(3/8) + log(2/8) + log(2/7) = -0.9808 + -0.9808 + -1.3863 + -1.2528 = ...

Constraints:

  • Add <s> at start and </s> at end of each sentence
  • Include <s> and </s> in vocabulary count
  • Use Laplace smoothing (add-1)
  • Use natural log
  • Compute: sum of log P(w_i | w_{i-1}) for each bigram in test sentence
🔒

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.
N-Gram Language Model - Medium | PixelBank