v9.1.1
Menu

Bigram Probability Calculator

easyFREELanguage ModelingNLP 3: Advanced

Given a corpus of text, compute bigram probabilities.

A bigram probability is P(word2 | word1) = count(word1, word2) / count(word1), where count(word1, word2) is the number of times word2 immediately follows word1, and count(word1) is the number of bigrams whose first word is word1 (an occurrence of word1 as the very last word of the corpus starts no bigram, so it is not counted).

Input format:

  • corpus: the training corpus (a single line of lowercase text, words separated by spaces)
  • w1, w2: the first and second word of the bigram to query

Round the probability to 4 decimal places.

Output: The bigram probability as a float. If w1 never starts a bigram, return 0.0.

Example

Input
the cat sat on the mat
the cat
Output
0.5
Reasoning
  • Inputs: corpus is the text "the cat sat on the mat" (6 words), and the query is w1 = "the", w2 = "cat". We want P(cat∣the)P(\text{cat} \mid \text{the}): how often "cat" comes right after "the".
  • Bigrams: every pair of adjacent words. A text of nn words has n−1n - 1 of them, so here there are 5: (the, cat), (cat, sat), (sat, on), (on, the), (the, mat).
  • Denominator: bigrams whose first word is "the" are (the, cat) and (the, mat), so count(the)=2\text{count}(\text{the}) = 2.
  • Numerator: of those two, only (the, cat) has "cat" second, so count(the,cat)=1\text{count}(\text{the}, \text{cat}) = 1.
  • Result: P(cat∣the)=12=0.5P(\text{cat} \mid \text{the}) = \frac{1}{2} = 0.5, which rounded to 4 decimal places prints as 0.5.
  • Notice: the probabilities of all words following "the" add up to 1, since P(mat∣the)P(\text{mat} \mid \text{the}) is also 12\frac{1}{2}. A word that only appears as the last word (like "mat") starts no bigram, so querying it as w1 gives 0.0.

Constraints

  • All text is lowercase
  • Bigram probability = count(bigram) / count(first word)
  • Round to 4 decimal places
  • If the first word never appears, output 0.0

Learn this in

More from NLP 3: Advanced

solution.py

Test results

Sign in to run your code against the test cases.