N-Gram Language Model
Build a bigram language model and compute the probability of a sentence.
Training: From the training text, count bigram frequencies and compute:
Use Laplace smoothing:
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
2 i love nlp i love coding i love nlp
-3.6636
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