Code a text genration model from scratch.
- User
Code a text genration model from scratch.
- Assistant
Code a text genration model from scratch.
Creating a text generation model from scratch is an excellent way to understand the fundamentals of natural language processing and deep learning. In this guide, we'll build a simple character-level Recurrent Neural Network (RNN) using Python and NumPy. This model will learn from a text corpus and generate new text character by character.
Table of Contents:
Before diving into the code, let's briefly understand what we're building:
For this example, we'll use a simple text file as our training data. You can use any text source, such as a book from Project Gutenberg.
# Load the data
data = open('input.txt', 'r').read()
data = data.lower() # Convert to lowercase
We need to convert characters to integers (and vice versa) to process them numerically.
chars = sorted(list(set(data)))
data_size, vocab_size = len(data), len(chars)
print(f'Data has {data_size} characters, {vocab_size} unique.')
# Create mappings
char_to_ix = { ch:i for i,ch in enumerate(chars) }
ix_to_char = { i:ch for i,ch in enumerate(chars) }
Set the model's hyperparameters and initialize weights.
import numpy as np
# Hyperparameters
hidden_size = 100 # Size of the hidden layer
seq_length = 25 # Number of steps to unroll
learning_rate = 1e-1
# Model parameters
Wxh = np.random.randn(hidden_size, vocab_size)*0.01 # Input to hidden
Whh = np.random.randn(hidden_size, hidden_size)*0.01 # Hidden to hidden
Why = np.random.randn(vocab_size, hidden_size)*0.01 # Hidden to output
bh = np.zeros((hidden_size, 1)) # Hidden bias
by = np.zeros((vocab_size, 1)) # Output bias
Implement the forward pass to compute the loss and store activations for the backward pass.
def lossFun(inputs, targets, hprev):
"""
inputs, targets are lists of integers.
hprev is Hx1 array of initial hidden state
Returns the loss, gradients on model parameters, and last hidden state
"""
xs, hs, ys, ps = {}, {}, {}, {}
hs[-1] = np.copy(hprev)
loss = 0
# Forward pass
for t in range(len(inputs)):
xs[t] = np.zeros((vocab_size,1)) # Encode in 1-of-k representation
xs[t][inputs[t]] = 1
hs[t] = np.tanh(np.dot(Wxh, xs[t]) + np.dot(Whh, hs[t-1]) + bh) # Hidden state
ys[t] = np.dot(Why, hs[t]) + by # Unnormalized log probabilities for next chars
ps[t] = np.exp(ys[t]) / np.sum(np.exp(ys[t])) # Probabilities for next chars
loss += -np.log(ps[t][targets[t],0]) # Softmax loss
return loss, xs, hs, ps
Implement backpropagation through time to compute gradients.
def backwardPass(inputs, targets, xs, hs, ps):
# Backward pass: compute gradients going backwards
global Wxh, Whh, Why, bh, by
dWxh, dWhh, dWhy = np.zeros_like(Wxh), np.zeros_like(Whh), np.zeros_like(Why)
dbh, dby = np.zeros_like(bh), np.zeros_like(by)
dhnext = np.zeros_like(hs[0])
for t in reversed(range(len(inputs))):
dy = np.copy(ps[t])
dy[targets[t]] -= 1 # Backprop into y
dWhy += np.dot(dy, hs[t].T)
dby += dy
dh = np.dot(Why.T, dy) + dhnext # Backprop into h
dhraw = (1 - hs[t] * hs[t]) * dh # Backprop through tanh nonlinearity
dbh += dhraw
dWxh += np.dot(dhraw, xs[t].T)
dWhh += np.dot(dhraw, hs[t-1].T)
dhnext = np.dot(Whh.T, dhraw)
# Clip to avoid exploding gradients
for dparam in [dWxh, dWhh, dWhy, dbh, dby]:
np.clip(dparam, -5, 5, out=dparam)
return dWxh, dWhh, dWhy, dbh, dby
We will use stochastic gradient descent (SGD) with a simple optimization technique.
# Initialize memory for Adagrad
mWxh, mWhh, mWhy = np.zeros_like(Wxh), np.zeros_like(Whh), np.zeros_like(Why)
mbh, mby = np.zeros_like(bh), np.zeros_like(by)
# Training loop
n, p = 0, 0
hprev = np.zeros((hidden_size,1)) # Reset RNN memory
while True:
# Prepare inputs
if p + seq_length + 1 >= len(data) or n == 0:
hprev = np.zeros((hidden_size,1)) # Reset RNN memory
p = 0 # Go from start of data
inputs = [char_to_ix[ch] for ch in data[p:p+seq_length]]
targets = [char_to_ix[ch] for ch in data[p+1:p+seq_length+1]]
# Forward and backward passes
loss, xs, hs, ps = lossFun(inputs, targets, hprev)
dWxh, dWhh, dWhy, dbh, dby = backwardPass(inputs, targets, xs, hs, ps)
hprev = hs[len(inputs)-1]
# Perform parameter update with Adagrad
for param, dparam, mem in zip([Wxh, Whh, Why, bh, by],
[dWxh, dWhh, dWhy, dbh, dby],
[mWxh, mWhh, mWhy, mbh, mby]):
mem += dparam * dparam
param += -learning_rate * dparam / (np.sqrt(mem) + 1e-8) # Adagrad update
p += seq_length # Move data pointer
n += 1 # Iteration counter
# Print progress
if n % 100 == 0:
print(f'Iteration {n}, Loss: {loss}')
After training, we can sample from the model to generate new text.
def sample(h, seed_ix, n):
"""
Sample a sequence of integers from the model
h is the memory state, seed_ix is seed letter for first time step
"""
x = np.zeros((vocab_size, 1))
x[seed_ix] = 1
ixes = []
for t in range(n):
h = np.tanh(np.dot(Wxh, x) + np.dot(Whh, h) + bh)
y = np.dot(Why, h) + by
p = np.exp(y) / np.sum(np.exp(y))
ix = np.random.choice(range(vocab_size), p=p.ravel())
x = np.zeros((vocab_size, 1))
x[ix] = 1
ixes.append(ix)
txt = ''.join(ix_to_char[ix] for ix in ixes)
return txt
You can use the sample function during training to see how the model is learning:
if n % 1000 == 0:
sample_text = sample(hprev, inputs[0], 200)
print(f'----\n {sample_text} \n----')
Here is the complete code combining all the steps:
[Note: For brevity, import statements, data loading, and variable initializations are omitted. Ensure you include all the necessary components from the sections above.]
import numpy as np
# Load and preprocess data...
# Initialize model parameters...
def lossFun(inputs, targets, hprev):
# Implement forward pass...
def backwardPass(inputs, targets, xs, hs, ps):
# Implement backward pass...
def sample(h, seed_ix, n):
# Implement sampling...
# Training loop
while True:
# Prepare inputs...
# Forward and backward passes...
# Update parameters...
# Print progress and sample text...
Building a text generation model from scratch involves understanding the underlying mechanisms of RNNs and how they process sequential data. This simple model serves as a foundation. For improved performance, consider:
References:
Disclaimer: This code is for educational purposes and serves as a simplified example. For production-grade models, consider using deep learning frameworks like TensorFlow or PyTorch.