A language model from the news
The first script downloads the site's recent news stories, splits them into tokens, measures how sparse the n-grams get, builds a bigram model, prints the likeliest next words after a few contexts, and generates a sentence by sampling.
- Save it as
ngram.pyand runpython ngram.py. - Change the seed in
random.seed(4). How many sentences make sense to the end? - Turn it into a trigram model that uses two words of context. Does it write better, or does it run out of examples?
import collections
import json
import random
import re
import sys
import urllib.request
sys.stdout.reconfigure(encoding="utf-8") # names with accents print on any terminal
API = "https://tactical-insights.com/api"
# The corpus: every recent news story on the site, headline and summary.
news = json.load(urllib.request.urlopen(f"{API}/news?limit=200"))
text = " ".join(f"{n['title']}. {n.get('summary') or ''}" for n in news)
# Tokens: here simply words and full stops, in lower case. Real LLMs use subword tokens.
tokens = re.findall(r"[\w']+|\.", text.lower()) # \w includes accented letters such as the ñ in Coruña
print(f"{len(news)} stories, {len(tokens)} tokens, {len(set(tokens))} different ones")
print(f"about {len(text) / 4:.0f} tokens by the 4-characters-per-token rule of thumb\n")
# 1. Sparsity: how many n-grams appear only once?
for n in (1, 2, 3, 4):
grams = collections.Counter(tuple(tokens[i:i + n]) for i in range(len(tokens) - n + 1))
once = sum(1 for c in grams.values() if c == 1)
print(f"{n}-grams: {len(grams):>5} different, {once / len(grams):.0%} seen only once")
# 2. A bigram model: the probability of each next word, given one word of context.
following = collections.defaultdict(collections.Counter)
for a, b in zip(tokens, tokens[1:]):
following[a][b] += 1
def next_words(word, top=5):
counts = following[word]
total = sum(counts.values())
return [(w, c / total) for w, c in counts.most_common(top)]
for context in ("win", "the", "scored"):
print(f"\nafter '{context}': " + ", ".join(f"{w} {p:.0%}" for w, p in next_words(context)))
# 3. Generate text: start somewhere and keep sampling the next word.
random.seed(4)
word, sentence = "the", ["the"]
for _ in range(15):
counts = following[word]
if not counts:
break
word = random.choices(list(counts), weights=list(counts.values()))[0]
if word == ".":
break
sentence.append(word)
print("\ngenerated: " + " ".join(sentence))