v9.1.1
Menu

Text Generator

hardPROLanguage ModelingNLP 3: Advanced

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

Input
3
i love nlp
i love ml
i hate bugs
5
Output
i love ml
Reasoning
  • Inputs: train_sents holds three sentences, each padded as ⟨s⟩ w1…wn ⟨/s⟩\langle s\rangle\ w_1 \dots w_n\ \langle /s\rangle, so every sentence contributes one bigram per adjacent pair. max_len =5= 5 caps the number of words produced.
  • After the start token: all three sentences begin with "i", so c(⟨s⟩,i)=3c(\langle s\rangle, \text{i}) = 3 is the only option. First word: "i".
  • After "i": c(i,love)=2c(\text{i}, \text{love}) = 2 beats c(i,hate)=1c(\text{i}, \text{hate}) = 1, so P(love∣i)=2/3P(\text{love} \mid \text{i}) = 2/3 wins. Second word: "love".
  • After "love": c(love,nlp)=c(love,ml)=1c(\text{love}, \text{nlp}) = c(\text{love}, \text{ml}) = 1, a tie at P=1/2P = 1/2. Alphabetically "ml" comes before "nlp", so it is chosen.
  • After "ml": the only continuation is the end token with c=1c = 1, 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_len =2= 2 the 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

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.