<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Alagra Gifty on Medium]]></title>
        <description><![CDATA[Stories by Alagra Gifty on Medium]]></description>
        <link>https://medium.com/@alagragifty91?source=rss-70afda56878f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*znuRraR4L2fNjYhasi9-ig.jpeg</url>
            <title>Stories by Alagra Gifty on Medium</title>
            <link>https://medium.com/@alagragifty91?source=rss-70afda56878f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 11:03:55 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@alagragifty91/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Markov Chains in Action: I Built a Text Generator From Scratch]]></title>
            <link>https://medium.com/@alagragifty91/markov-chains-in-action-i-built-a-text-generator-from-scratch-48c2b91076f0?source=rss-70afda56878f------2</link>
            <guid isPermaLink="false">https://medium.com/p/48c2b91076f0</guid>
            <category><![CDATA[statistics]]></category>
            <category><![CDATA[markov-chains]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[text-generator]]></category>
            <category><![CDATA[linear-algebra]]></category>
            <dc:creator><![CDATA[Alagra Gifty]]></dc:creator>
            <pubDate>Sat, 14 Nov 2026 02:19:05 GMT</pubDate>
            <atom:updated>2026-11-14T02:19:05.962Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Stage one of the search engine I’m building from scratch, and the probability idea that links autocomplete to search.</em></p><p>I built a text generator from scratch. Just Python, word counting, transition probabilities, and the mathematics behind Markov chains.</p><p>Most people use search engines and AI chatbots every day without knowing how they work underneath. I wanted to understand them properly, so I decided to build a search engine from scratch, one stage at a time, and to learn the math behind each piece as I go.</p><p>Stage one was a text generator. It uses an idea from probability that is over a century old, the Markov chain, and it turns out to connect directly to both modern language models and to how Google first ranked web pages. This article explains the idea in plain language and shows how I built it.</p><h3>What is a Markov chain?</h3><p>A Markov chain is a way of describing a system that moves between states, where the next state depends only on the current one, not on how you got there. This is called the Markov property.</p><p>Weather is the classic example. If tomorrow’s weather depends only on today’s, you can describe the whole system with a table of probabilities: given that today is sunny, there is some chance tomorrow is sunny and some chance it rains.</p><p>Text works the same way if you treat each word as a state. Given the current word, what is the probability of each possible next word? That table of probabilities is the whole model.</p><h3>A tiny example</h3><p>Take a very small training text:</p><blockquote>the cat sat on the mat the cat ate the fish</blockquote><p>Look at every word and note what comes right after it. After “the”, the word “cat” appears twice, and “mat” and “fish” appear once each. After “cat”, we see “sat” once and “ate” once. Every other word is followed by exactly one word. Drawing these as arrows between words gives a graph, where each arrow is labeled with its probability.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*8QhHP8f9ifUs3P6USyyvzg.png" /></figure><h3>Turning Counts Into Probabilities</h3><p>To turn counts into probabilities, divide each count by the total number of times the current word appears. After “the” there are four observations, so “cat” gets 2 out of 4, which is 0.50, and “mat” and “fish” each get 1 out of 4, which is 0.25.</p><p>This is called maximum likelihood estimation: you pick the probabilities that make the training text as likely as possible. It sounds fancy, but here it simply means counting and dividing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*3uLgjNhKcxciny5I3Y4Qmw.png" /></figure><h3>Generating text</h3><p>Now the fun part. Pick a starting word. Look up its row in the table. Draw the next word at random, weighted by those probabilities, so “cat” comes up half the time after “the”. Repeat from the new word until you hit the length you want, or a word with nothing after it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*Sgu2MYrPNVNRveyh-ewUrA.png" /></figure><p>I built this model using text extracted from a Gutenberg book in PDF format. The model works with one previous word at a time (a first-order Markov chain), using the words and their transition probabilities to generate new text.</p><h3>A Look at the Code</h3><p>The main part of my implementation involved cleaning the extracted text, building a dictionary of word transitions, and using those transitions to generate new text.</p><p>I first converted the text to lowercase and removed punctuation using Python’s string module.</p><pre>import string</pre><pre>text = text.lower()<br>text = text.translate(str.maketrans(&quot;&quot;, &quot;&quot;, string.punctuation))</pre><pre>words = text.split()</pre><p>Next, I created a transition dictionary to count how frequently one word followed another.</p><pre>transitions = {}</pre><pre>for i in range(len(words) - 1):<br>    current_word = words[i]<br>    next_word = words[i + 1]</pre><pre>    if current_word not in transitions:<br>        transitions[current_word] = {}</pre><pre>    if next_word not in transitions[current_word]:<br>        transitions[current_word][next_word] = 0</pre><pre>    transitions[current_word][next_word] += 1</pre><p>Finally, I wrote a function to generate text. It takes a starting word and a desired length, then repeatedly selects the next word using weighted random selection.</p><pre>import random</pre><pre>def generate_text(start_word, length):<br>    current_word = start_word<br>    result = [current_word]</pre><pre>    for _ in range(length - 1):<br>        next_words = transitions.get(current_word, {})</pre><pre>        if not next_words:<br>            break</pre><pre>        words_list = list(next_words.keys())<br>        counts = list(next_words.values())</pre><pre>        current_word = random.choices(<br>            words_list, weights=counts, k=1<br>        )[0]</pre><pre>        result.append(current_word)</pre><pre>    return &quot; &quot;.join(result)</pre><p>I chose the starting word manually when testing the generator. For example:</p><pre>print(generate_text(&quot;law&quot;, 20))</pre><p>One important detail is that I used word frequencies as weights rather than choosing the next word uniformly. This means that words appearing more frequently after the current word have a higher probability of being selected.</p><p>The implementation uses a first-order Markov chain: it considers only the immediately preceding word when selecting the next one.</p><h3>What it produced</h3><p>Here is one of the outputs generated by my model:</p><blockquote><em>law does not be found the volumes of which lies take away insomuch that of certain problems in question referred to the prism which are in the project gutenberg license</em></blockquote><p>Some phrases, such as <em>“problems in question”</em> and <em>“referred to the prism”</em>, resemble natural book language. However, the complete sentence is difficult to understand.</p><p>What I noticed is that the model can produce phrases that sound natural, but it struggles to maintain grammatical structure and meaning across a sentence.</p><p>This is because it predicts words based on previous word patterns rather than understanding the context.</p><h3><strong>Why the Generated Text Ignores Capitalization?</strong></h3><p>Before counting any words, our model converts all text to lowercase. This means <em>The</em>, <em>the</em>, and <em>THE</em> are treated as the same word. That makes counting words and calculating transition probabilities much simpler, but it also throws away any information about capitalization.</p><p>As a result, the generated text doesn’t follow standard capitalization rules. Sentences may begin with lowercase letters, and proper nouns like names and places lose their original capitalization.</p><p>This is a deliberate simplification in our first implementation. The goal was to understand word transitions and the mathematics behind Markov chains, not to perfect the formatting of the output.</p><h3>What Went Wrong</h3><p>The first problem I hit was speed, not math.</p><p>When I built the transition table, my generator took far too long to run. The counting was right and the output was right. The slowdown came down to one line: a print statement sitting <strong>inside</strong> the loop.</p><p>That meant every time the loop went through one pair of words, the program also stopped to print. A text with thousands of words means thousands of prints. Printing is slow compared with counting, so the program spent most of its time talking instead of working.</p><h3>What a Markov chain can’t do</h3><p>The model has no memory beyond its current state, so it cannot keep track of a topic, a subject, or the start of a sentence. You can extend it to look at the last two or three words instead of one, and the output gets more coherent. The cost is that it starts copying long stretches of the training text, because most word combinations are only ever seen once.</p><p>This is the same basic task that large language models perform: predict the next token given what came before. The difference is that a Markov chain looks at one or a few words and stores a lookup table, while a transformer looks at thousands of tokens and learns a compact function. A useful way to compare models like these is perplexity, which measures how surprised a model is by text it has not seen.</p><h3>What Next</h3><p>The next stages of my search engine are a crawler, an inverted index, ranking with TF-IDF and BM25, PageRank, and evaluation.</p><p>The Markov idea comes back at PageRank. Imagine someone clicking random links on the web, forever. The pages they land on most often are the most important ones. That random surfer is a Markov chain.</p><p>Same math. Different job.</p><h3>Try It Yourself</h3><p>The full notebook is on Google Colab: <a href="https://colab.research.google.com/drive/1mVUuwKT_7mYaSV-6_fvln6ZaCu4Lbzip?usp=sharing">Markov text generator notebook</a></p><p>If you’re building something similar, or you have ideas to improve it, tell me in the comments.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=48c2b91076f0" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>