Text Generator
Generate text using a bigram language model with deterministic selection (always pick the most probable next word).
Build a bigram model from training data. Starting from <s>, at each step choose the word with the highest P(w | prev_word). If there is a tie, choose the alphabetically first word. Stop when </s> is generated or max_length words are reached.
Input:
- train_sents: a list of N training sentences (strings of space-separated words)
- max_len: the maximum number of generated words, not counting <s>/</s>
Output: The generated sentence as a string (words separated by single spaces, no <s> or </s>).
Note: Use raw counts (no smoothing) for generation — pick the highest count bigram.
Example
3 i love nlp i love ml i hate bugs 5
i love ml
- Inputs:
train_sentsholds three sentences, each padded as , so every sentence contributes one bigram per adjacent pair.max_lencaps the number of words produced. - After the start token: all three sentences begin with "i", so is the only option. First word: "i".
- After "i": beats , so wins. Second word: "love".
- After "love": , a tie at . Alphabetically "ml" comes before "nlp", so it is chosen.
- After "ml": the only continuation is the end token with , so generation stops after 3 words, well under the cap of 5. Output:
i love ml. - Notice the output is a sentence that never appears in training: greedy choices made locally can stitch together pieces of different sentences. With
max_lenthe same walk would be cut off at "i love".
Constraints
- Start from <s>, pick highest-count next word
- Ties broken alphabetically (smallest word first)
- Stop at </s> or when max_length words generated
- Do NOT include <s> or </s> in output
- Use raw counts (no smoothing) for generation