Table of Contents
Introduction to Text Generator
What is a Markov chain?
Implementation of text generation
1. Generate a lookup table
2. Convert frequency to probability
3. Load the data set
4. Build a Markov chain
5. Text Sampling
6. Generate text
What to learn next
Home Technology peripherals AI Building text generators using Markov chains

Building text generators using Markov chains

Apr 09, 2023 pm 10:11 PM
machine learning natural language text generator

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.

Building text generators using Markov chains

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.

Building text generators using Markov chains

#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.

Building text generators using Markov chains

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:

  1. Generate lookup table: Create a table to record word frequency
  2. Convert frequencies to probabilities: Convert our findings into a usable form
  3. Load dataset: Load and utilize a training set
  4. Build a Markov chain: Use probabilities for each word and character creation chains
  5. Sample the data: Create a function to sample various parts of the corpus
  6. Generate text: Test our model

Building text generators using Markov chains

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:

Building text generators using Markov chains

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}}
Copy after login

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:

Building text generators using Markov chains

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}}
Copy after login

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.')
Copy after login

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)
Copy after login

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]
Copy after login

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)
Copy after login

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.
Copy after login

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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

This article will take you to understand SHAP: model explanation for machine learning This article will take you to understand SHAP: model explanation for machine learning Jun 01, 2024 am 10:58 AM

In the fields of machine learning and data science, model interpretability has always been a focus of researchers and practitioners. With the widespread application of complex models such as deep learning and ensemble methods, understanding the model's decision-making process has become particularly important. Explainable AI|XAI helps build trust and confidence in machine learning models by increasing the transparency of the model. Improving model transparency can be achieved through methods such as the widespread use of multiple complex models, as well as the decision-making processes used to explain the models. These methods include feature importance analysis, model prediction interval estimation, local interpretability algorithms, etc. Feature importance analysis can explain the decision-making process of a model by evaluating the degree of influence of the model on the input features. Model prediction interval estimate

Transparent! An in-depth analysis of the principles of major machine learning models! Transparent! An in-depth analysis of the principles of major machine learning models! Apr 12, 2024 pm 05:55 PM

In layman’s terms, a machine learning model is a mathematical function that maps input data to a predicted output. More specifically, a machine learning model is a mathematical function that adjusts model parameters by learning from training data to minimize the error between the predicted output and the true label. There are many models in machine learning, such as logistic regression models, decision tree models, support vector machine models, etc. Each model has its applicable data types and problem types. At the same time, there are many commonalities between different models, or there is a hidden path for model evolution. Taking the connectionist perceptron as an example, by increasing the number of hidden layers of the perceptron, we can transform it into a deep neural network. If a kernel function is added to the perceptron, it can be converted into an SVM. this one

Identify overfitting and underfitting through learning curves Identify overfitting and underfitting through learning curves Apr 29, 2024 pm 06:50 PM

This article will introduce how to effectively identify overfitting and underfitting in machine learning models through learning curves. Underfitting and overfitting 1. Overfitting If a model is overtrained on the data so that it learns noise from it, then the model is said to be overfitting. An overfitted model learns every example so perfectly that it will misclassify an unseen/new example. For an overfitted model, we will get a perfect/near-perfect training set score and a terrible validation set/test score. Slightly modified: "Cause of overfitting: Use a complex model to solve a simple problem and extract noise from the data. Because a small data set as a training set may not represent the correct representation of all data." 2. Underfitting Heru

The evolution of artificial intelligence in space exploration and human settlement engineering The evolution of artificial intelligence in space exploration and human settlement engineering Apr 29, 2024 pm 03:25 PM

In the 1950s, artificial intelligence (AI) was born. That's when researchers discovered that machines could perform human-like tasks, such as thinking. Later, in the 1960s, the U.S. Department of Defense funded artificial intelligence and established laboratories for further development. Researchers are finding applications for artificial intelligence in many areas, such as space exploration and survival in extreme environments. Space exploration is the study of the universe, which covers the entire universe beyond the earth. Space is classified as an extreme environment because its conditions are different from those on Earth. To survive in space, many factors must be considered and precautions must be taken. Scientists and researchers believe that exploring space and understanding the current state of everything can help understand how the universe works and prepare for potential environmental crises

Implementing Machine Learning Algorithms in C++: Common Challenges and Solutions Implementing Machine Learning Algorithms in C++: Common Challenges and Solutions Jun 03, 2024 pm 01:25 PM

Common challenges faced by machine learning algorithms in C++ include memory management, multi-threading, performance optimization, and maintainability. Solutions include using smart pointers, modern threading libraries, SIMD instructions and third-party libraries, as well as following coding style guidelines and using automation tools. Practical cases show how to use the Eigen library to implement linear regression algorithms, effectively manage memory and use high-performance matrix operations.

Explainable AI: Explaining complex AI/ML models Explainable AI: Explaining complex AI/ML models Jun 03, 2024 pm 10:08 PM

Translator | Reviewed by Li Rui | Chonglou Artificial intelligence (AI) and machine learning (ML) models are becoming increasingly complex today, and the output produced by these models is a black box – unable to be explained to stakeholders. Explainable AI (XAI) aims to solve this problem by enabling stakeholders to understand how these models work, ensuring they understand how these models actually make decisions, and ensuring transparency in AI systems, Trust and accountability to address this issue. This article explores various explainable artificial intelligence (XAI) techniques to illustrate their underlying principles. Several reasons why explainable AI is crucial Trust and transparency: For AI systems to be widely accepted and trusted, users need to understand how decisions are made

Five schools of machine learning you don't know about Five schools of machine learning you don't know about Jun 05, 2024 pm 08:51 PM

Machine learning is an important branch of artificial intelligence that gives computers the ability to learn from data and improve their capabilities without being explicitly programmed. Machine learning has a wide range of applications in various fields, from image recognition and natural language processing to recommendation systems and fraud detection, and it is changing the way we live. There are many different methods and theories in the field of machine learning, among which the five most influential methods are called the "Five Schools of Machine Learning". The five major schools are the symbolic school, the connectionist school, the evolutionary school, the Bayesian school and the analogy school. 1. Symbolism, also known as symbolism, emphasizes the use of symbols for logical reasoning and expression of knowledge. This school of thought believes that learning is a process of reverse deduction, through existing

Is Flash Attention stable? Meta and Harvard found that their model weight deviations fluctuated by orders of magnitude Is Flash Attention stable? Meta and Harvard found that their model weight deviations fluctuated by orders of magnitude May 30, 2024 pm 01:24 PM

MetaFAIR teamed up with Harvard to provide a new research framework for optimizing the data bias generated when large-scale machine learning is performed. It is known that the training of large language models often takes months and uses hundreds or even thousands of GPUs. Taking the LLaMA270B model as an example, its training requires a total of 1,720,320 GPU hours. Training large models presents unique systemic challenges due to the scale and complexity of these workloads. Recently, many institutions have reported instability in the training process when training SOTA generative AI models. They usually appear in the form of loss spikes. For example, Google's PaLM model experienced up to 20 loss spikes during the training process. Numerical bias is the root cause of this training inaccuracy,

See all articles