Building text generators using Markov chains
In this article, we will introduce a popular machine learning project - text generator. You will learn how to build a text generator and learn how to implement a Markov chain to achieve a faster prediction model.
Introduction to Text Generator
Text generation is popular across industries, especially in mobile, apps, and data science. Even the press uses text generation to aid the writing process.
In daily life, we will come into contact with some text generation technologies. Text completion, search suggestions, Smart Compose, and chat robots are all examples of applications.
This article will use Markov chain to build A text generator. This would be a character-based model that takes the previous character of the chain and generates the next letter in the sequence.
By training our program using example words, the text generator will learn common character order patterns. The text generator will then apply these patterns to the input, which is an incomplete word, and output the character with the highest probability of completing the word.
#Text generation is a branch of natural language processing that predicts and generates the next character based on previously observed language patterns.
Before machine learning, NLP performed text generation by creating a table containing all the words in the English language and matching the passed string to the existing words. There are two problems with this approach.
- Searching thousands of words will be very slow.
- The generator can only complete words it has seen before.
The advent of machine learning and deep learning has allowed us to drastically reduce runtime and increase generality in NLP because the generator can complete words it has never encountered before. NLP can be extended to predict words, phrases or sentences if desired!
For this project we will be doing it exclusively using Markov chains. Markov processes are the basis of many natural language processing projects involving written language and simulating samples from complex distributions.
Markov processes are so powerful that they can be used to generate ostensibly real-looking text using only a sample document.
What is a Markov chain?
A Markov chain is a stochastic process that models a sequence of events where the probability of each event depends on the state of the previous event . The model has a finite set of states, and the conditional probability of moving from one state to another is fixed.
The probability of each transition only depends on the previous state of the model, not the entire history of events.
For example, suppose you want to build a Markov chain model to predict weather.
In this model we have two states, sunny or rainy. If we have a sunny day today, there is a higher probability (70%) that it will be sunny tomorrow. The same goes for rain; if it's already rained, it's likely to continue to rain.
But it is possible (30%) that the weather will change state, so we include that in our Markov chain model as well.
Markov chains are the perfect model for our text generator because our model will predict the next character using only the previous character. The advantages of using a Markov chain are that it is accurate, requires less memory (only 1 previous state is stored) and is fast to execute.
Implementation of text generation
The text generator will be completed in 6 steps:
- Generate lookup table: Create a table to record word frequency
- Convert frequencies to probabilities: Convert our findings into a usable form
- Load dataset: Load and utilize a training set
- Build a Markov chain: Use probabilities for each word and character creation chains
- Sample the data: Create a function to sample various parts of the corpus
- Generate text: Test our model
1. Generate a lookup table
First, we will create a table to record the occurrence of each character state in the training corpus. Save the last 'K' character and 'K1' character from the training corpus and save them in a lookup table.
For example, imagine that our training corpus contains, "the man was, they, then, the, the". Then the number of occurrences of the word is:
- "the" — 3
- "then" — 1
- "they" — 1
- " man” — 1
The following are the results in the lookup table:
In the above example, we take K = 3, which means that 3 characters will be considered at a time and the next character (K 1) will be used as the output character. Treat the word (X) as a character in the above lookup table and the output character (Y) as a single space (" ") since there is no word after the first the. Also calculated is the number of times this sequence appears in the data set, in this case 3 times.
This generates data for each word in the corpus, that is, all possible X and Y pairs are generated.
Here's how we generate the lookup table in the code:
def generateTable(data,k=4): T = {} for i in range(len(data)-k): X = data[i:i+k] Y = data[i+k] #print("X %s and Y %s "%(X,Y)) if T.get(X) is None: T[X] = {} T[X][Y] = 1 else: if T[X].get(Y) is None: T[X][Y] = 1 else: T[X][Y] += 1 return T T = generateTable("hello hello helli") print(T) #{'llo ': {'h': 2}, 'ello': {' ': 2}, 'o he': {'l': 2}, 'lo h': {'e': 2}, 'hell': {'i': 1, 'o': 2}, ' hel': {'l': 2}}
Simple explanation of the code:
In line 3, a dictionary is created that will store X and Its corresponding Y and frequency values. Lines 9 to 17 check for occurrences of X and Y. If there is already an X and Y pair in the lookup dictionary, just increase it by 1.
2. Convert frequency to probability
Once we have this table and the number of occurrences, we can get the probability of Y occurring after a given occurrence of x. The formula is:
For example, if X = the, Y = n, our formula is like this:
When X =the Y = n Frequency: 2, total frequency in the table: 8, therefore: P = 2/8= 0.125= 12.5%
Here is how we apply this formula to convert the lookup table into a Markov chain with usable probabilities:
def convertFreqIntoProb(T): for kx in T.keys(): s = float(sum(T[kx].values())) for k in T[kx].keys(): T[kx][k] = T[kx][k]/s return T T = convertFreqIntoProb(T) print(T) #{'llo ': {'h': 1.0}, 'ello': {' ': 1.0}, 'o he': {'l': 1.0}, 'lo h': {'e': 1.0}, 'hell': {'i': 0.3333333333333333, 'o': 0.6666666666666666}, ' hel': {'l': 1.0}}
Simple explanation:
Add the frequency values of a specific key, and then divide each frequency value of this key by the added value to get the probability.
3. Load the data set
The real training corpus will be loaded next. You can use any long text (.txt) document you want.
For simplicity a political speech will be used to provide enough vocabulary to teach our model.
text_path = "train_corpus.txt" def load_text(filename): with open(filename,encoding='utf8') as f: return f.read().lower() text = load_text(text_path) print('Loaded the dataset.')
This data set can provide enough events for our sample project to make reasonably accurate predictions. As with all machine learning, a larger training corpus will produce more accurate predictions.
4. Build a Markov chain
Let us build a Markov chain and associate the probability with each character. The generateTable() and convertFreqIntoProb() functions created in steps 1 and 2 will be used here to build the Markov model.
def MarkovChain(text,k=4): T = generateTable(text,k) T = convertFreqIntoProb(T) return T model = MarkovChain(text)
In line 1, a method is created to generate a Markov model. The method accepts a text corpus and a K value, which is the value that tells the Markov model to consider K characters and predict the next character. Line 2, the lookup table is generated by providing the text corpus and K to the method generateTable(), which we created in the previous section. Line 3 converts the frequency to a probability value using the convertFreqIntoProb() method, which we also created in the previous lesson.
5. Text Sampling
Create a sampling function that uses the unfinished words (ctx), the Markov chain model (model) in step 4 and the base for forming the word The number of characters (k).
We will use this function to sample the passed context and return the next possible character and determine the probability that it is the correct character.
import numpy as np def sample_next(ctx,model,k): ctx = ctx[-k:] if model.get(ctx) is None: return " " possible_Chars = list(model[ctx].keys()) possible_values = list(model[ctx].values()) print(possible_Chars) print(possible_values) return np.random.choice(possible_Chars,p=possible_values) sample_next("commo",model,4) #['n'] #[1.0]
Code explanation:
The function sample_next accepts three parameters: ctx, model and k value.
ctx is the text used to generate some new text. But here only the last K characters in ctx will be used by the model to predict the next character in the sequence. For example, we pass common, K = 4, and the text that the model uses to generate the next character is ommo, because the Markov model only uses the previous history.
On lines 9 and 10, the possible characters and their probability values are printed, since these characters also exist in our model. We get the next predicted character to be n, with probability 1.0. Since the word commo is more likely to be more common after generating the next character
on line 12, we return a character based on the probability value discussed above.
6. Generate text
Finally combine all the above functions to generate some text.
def generateText(starting_sent,k=4,maxLen=1000): sentence = starting_sent ctx = starting_sent[-k:] for ix in range(maxLen): next_prediction = sample_next(ctx,model,k) sentence += next_prediction ctx = sentence[-k:] return sentence print("Function Created Successfully!") text = generateText("dear",k=4,maxLen=2000) print(text)
The results are as follows:
dear country brought new consciousness. i heartily great service of their lives, our country, many of tricoloring a color flag on their lives independence today.my devoted to be oppression of independence.these day the obc common many country, millions of oppression of massacrifice of indian whom everest. my dear country is not in the sevents went was demanding and nights by plowing in the message of the country is crossed, oppressed, women, to overcrowding for years of the south, it is like the ashok chakra of constitutional states crossed, deprived, oppressions of freedom, i bow my heart to proud of our country.my dear country, millions under to be a hundred years of the south, it is going their heroes.
The above function accepts three parameters: the starting word of the generated text, the value of K and the maximum character length of the required text. Running the code will result in a 2000 character text starting with "dear".
While this speech may not make much sense, the words are complete and often imitate familiar patterns in words.
What to learn next
This is a simple text generation project. Use this project to learn how natural language processing and Markov chains work in action, which you can use as you continue your deep learning journey.
This article is just to introduce the experimental project carried out by Markov chain, because it will not play any role in actual application. If you want to get better text generation effect, then please learn GPT- 3 such tools.
The above is the detailed content of Building text generators using Markov chains. For more information, please follow other related articles on the PHP Chinese website!
![Can't use ChatGPT! Explaining the causes and solutions that can be tested immediately [Latest 2025]](https://img.php.cn/upload/article/001/242/473/174717025174979.jpg?x-oss-process=image/resize,p_40)
ChatGPT is not accessible? This article provides a variety of practical solutions! Many users may encounter problems such as inaccessibility or slow response when using ChatGPT on a daily basis. This article will guide you to solve these problems step by step based on different situations. Causes of ChatGPT's inaccessibility and preliminary troubleshooting First, we need to determine whether the problem lies in the OpenAI server side, or the user's own network or device problems. Please follow the steps below to troubleshoot: Step 1: Check the official status of OpenAI Visit the OpenAI Status page (status.openai.com) to see if the ChatGPT service is running normally. If a red or yellow alarm is displayed, it means Open

On 10 May 2025, MIT physicist Max Tegmark told The Guardian that AI labs should emulate Oppenheimer’s Trinity-test calculus before releasing Artificial Super-Intelligence. “My assessment is that the 'Compton constant', the probability that a race to

AI music creation technology is changing with each passing day. This article will use AI models such as ChatGPT as an example to explain in detail how to use AI to assist music creation, and explain it with actual cases. We will introduce how to create music through SunoAI, AI jukebox on Hugging Face, and Python's Music21 library. Through these technologies, everyone can easily create original music. However, it should be noted that the copyright issue of AI-generated content cannot be ignored, and you must be cautious when using it. Let’s explore the infinite possibilities of AI in the music field together! OpenAI's latest AI agent "OpenAI Deep Research" introduces: [ChatGPT]Ope

The emergence of ChatGPT-4 has greatly expanded the possibility of AI applications. Compared with GPT-3.5, ChatGPT-4 has significantly improved. It has powerful context comprehension capabilities and can also recognize and generate images. It is a universal AI assistant. It has shown great potential in many fields such as improving business efficiency and assisting creation. However, at the same time, we must also pay attention to the precautions in its use. This article will explain the characteristics of ChatGPT-4 in detail and introduce effective usage methods for different scenarios. The article contains skills to make full use of the latest AI technologies, please refer to it. OpenAI's latest AI agent, please click the link below for details of "OpenAI Deep Research"

ChatGPT App: Unleash your creativity with the AI assistant! Beginner's Guide The ChatGPT app is an innovative AI assistant that handles a wide range of tasks, including writing, translation, and question answering. It is a tool with endless possibilities that is useful for creative activities and information gathering. In this article, we will explain in an easy-to-understand way for beginners, from how to install the ChatGPT smartphone app, to the features unique to apps such as voice input functions and plugins, as well as the points to keep in mind when using the app. We'll also be taking a closer look at plugin restrictions and device-to-device configuration synchronization

ChatGPT Chinese version: Unlock new experience of Chinese AI dialogue ChatGPT is popular all over the world, did you know it also offers a Chinese version? This powerful AI tool not only supports daily conversations, but also handles professional content and is compatible with Simplified and Traditional Chinese. Whether it is a user in China or a friend who is learning Chinese, you can benefit from it. This article will introduce in detail how to use ChatGPT Chinese version, including account settings, Chinese prompt word input, filter use, and selection of different packages, and analyze potential risks and response strategies. In addition, we will also compare ChatGPT Chinese version with other Chinese AI tools to help you better understand its advantages and application scenarios. OpenAI's latest AI intelligence

These can be thought of as the next leap forward in the field of generative AI, which gave us ChatGPT and other large-language-model chatbots. Rather than simply answering questions or generating information, they can take action on our behalf, inter

Efficient multiple account management techniques using ChatGPT | A thorough explanation of how to use business and private life! ChatGPT is used in a variety of situations, but some people may be worried about managing multiple accounts. This article will explain in detail how to create multiple accounts for ChatGPT, what to do when using it, and how to operate it safely and efficiently. We also cover important points such as the difference in business and private use, and complying with OpenAI's terms of use, and provide a guide to help you safely utilize multiple accounts. OpenAI


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

Notepad++7.3.1
Easy-to-use and free code editor

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

SublimeText3 Mac version
God-level code editing software (SublimeText3)

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment
