Bird
Raised Fist0
NLPml~5 mins

RNN-based text generation in NLP

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Introduction
RNN-based text generation helps computers write text by learning patterns from example sentences. It can create new sentences that sound like the original text.
When you want a computer to write stories or poems similar to a style you provide.
When you need to autocomplete sentences or suggest text in chat apps.
When generating code snippets based on previous code examples.
When creating chatbots that respond with natural language.
When experimenting with creative writing using AI.
Syntax
NLP
model = Sequential()
model.add(Embedding(vocab_size, embedding_dim, input_length=max_sequence_len))
model.add(SimpleRNN(units))
model.add(Dense(vocab_size, activation='softmax'))
model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
Use Embedding layer to convert words into numbers the model can understand.
SimpleRNN layer processes the sequence of words step-by-step to learn patterns.
Examples
This example creates an RNN model for a vocabulary of 1000 words and sequences of length 10.
NLP
model = Sequential()
model.add(Embedding(1000, 64, input_length=10))
model.add(SimpleRNN(128))
model.add(Dense(1000, activation='softmax'))
model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
Here, the model handles longer sequences (20 words) and a bigger vocabulary (5000 words).
NLP
model = Sequential()
model.add(Embedding(5000, 100, input_length=20))
model.add(SimpleRNN(256))
model.add(Dense(5000, activation='softmax'))
model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
Sample Model
This program trains a small RNN model on a tiny text sample. It learns to predict the next word given two words. Then it generates three new words starting from 'hello world'.
NLP
import numpy as np
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Embedding, SimpleRNN, Dense
from tensorflow.keras.utils import to_categorical

# Sample text data
text = "hello world hello machine learning"

# Create a simple word index
words = sorted(set(text.split()))
word_to_index = {w: i for i, w in enumerate(words)}
index_to_word = {i: w for w, i in word_to_index.items()}

# Prepare sequences (input and target)
sequence_length = 2
sequences = []
tokens = text.split()
for i in range(len(tokens) - sequence_length):
    seq = tokens[i:i+sequence_length+1]
    sequences.append([word_to_index[w] for w in seq])

sequences = np.array(sequences)
X, y = sequences[:, :-1], sequences[:, -1]
y = to_categorical(y, num_classes=len(words))

# Build the model
model = Sequential()
model.add(Embedding(input_dim=len(words), output_dim=10, input_length=sequence_length))
model.add(SimpleRNN(20))
model.add(Dense(len(words), activation='softmax'))
model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])

# Train the model
model.fit(X, y, epochs=100, verbose=0)

# Generate text function
def generate_text(seed_text, next_words=3):
    result = seed_text.split()
    for _ in range(next_words):
        encoded = [word_to_index[w] for w in result[-sequence_length:]]
        encoded = np.array(encoded).reshape(1, sequence_length)
        pred = model.predict(encoded, verbose=0)
        next_index = np.argmax(pred)
        next_word = index_to_word[next_index]
        result.append(next_word)
    return ' '.join(result)

# Generate new text
output_text = generate_text('hello world')
print(output_text)
OutputSuccess
Important Notes
Training on very small text limits the quality of generated text.
Increasing epochs or model size can improve results but needs more data.
SimpleRNN is easy to understand but LSTM or GRU layers often work better for text.
Summary
RNNs read text word by word to learn patterns for generating new text.
Embedding layers turn words into numbers the model can work with.
Training needs input sequences and the next word as the target.

Practice

(1/5)
1. What is the main purpose of using an RNN in text generation?
easy
A. To count the number of words in a sentence
B. To sort words alphabetically
C. To translate text into another language
D. To learn patterns in sequences of words to predict the next word

Solution

  1. Step 1: Understand RNN function in text

    RNNs process sequences step-by-step, remembering past words to predict what comes next.
  2. Step 2: Identify the goal of text generation

    The goal is to generate new text by predicting the next word based on learned patterns.
  3. Final Answer:

    To learn patterns in sequences of words to predict the next word -> Option D
  4. Quick Check:

    RNN predicts next word in sequence = C [OK]
Hint: RNNs remember word order to guess the next word [OK]
Common Mistakes:
  • Thinking RNNs just count words
  • Confusing RNNs with sorting algorithms
  • Assuming RNNs translate text directly
2. Which of the following is the correct way to define an embedding layer in a Keras RNN model for text generation?
easy
A. Embedding(input_length=64, input_dim=10, output_dim=1000)
B. Embedding(output_dim=1000, input_dim=64, input_length=10)
C. Embedding(input_dim=1000, output_dim=64, input_length=10)
D. Embedding(input_dim=10, output_dim=1000, input_length=64)

Solution

  1. Step 1: Recall embedding layer parameters

    Embedding layers require input_dim (vocab size), output_dim (embedding size), and input_length (sequence length).
  2. Step 2: Match parameters correctly

    Embedding(input_dim=1000, output_dim=64, input_length=10) correctly sets input_dim=1000 (vocab size), output_dim=64 (embedding size), input_length=10 (sequence length).
  3. Final Answer:

    Embedding(input_dim=1000, output_dim=64, input_length=10) -> Option C
  4. Quick Check:

    Embedding(input_dim, output_dim, input_length) = A [OK]
Hint: Input_dim = vocab size, output_dim = embedding size [OK]
Common Mistakes:
  • Swapping input_dim and output_dim
  • Confusing input_length with output_dim
  • Using wrong parameter names
3. Given this code snippet for training an RNN text generator, what will be the shape of the input data X if the vocabulary size is 5000, sequence length is 20, and batch size is 32?
model = Sequential()
model.add(Embedding(input_dim=5000, output_dim=50, input_length=20))
model.add(SimpleRNN(100))
model.add(Dense(5000, activation='softmax'))

X = np.random.randint(0, 5000, (32, 20))
medium
A. (20, 32)
B. (32, 20)
C. (32, 50)
D. (5000, 20)

Solution

  1. Step 1: Understand input shape for embedding

    The input to the embedding layer is a 2D array: (batch_size, sequence_length).
  2. Step 2: Check given data shape

    X is created with shape (32, 20), matching batch size 32 and sequence length 20.
  3. Final Answer:

    (32, 20) -> Option B
  4. Quick Check:

    Input shape = (batch_size, sequence_length) = (32, 20) [OK]
Hint: Input shape = batch size by sequence length [OK]
Common Mistakes:
  • Confusing embedding output shape with input shape
  • Swapping batch size and sequence length
  • Assuming embedding changes input shape
4. You wrote this code to train an RNN text generator but get a shape mismatch error:
model = Sequential()
model.add(Embedding(input_dim=10000, output_dim=64, input_length=15))
model.add(SimpleRNN(128))
model.add(Dense(10000, activation='softmax'))

X = np.random.randint(0, 10000, (64, 15))
y = np.random.randint(0, 10000, (64, 15))  # target labels

model.compile(loss='sparse_categorical_crossentropy', optimizer='adam')
model.fit(X, y, epochs=5)

What is the main issue causing the error?
medium
A. Target labels y should be shape (64,) with integer word indices, not (64, 15)
B. Embedding input_dim is too large
C. SimpleRNN units should match output_dim of embedding
D. Loss function sparse_categorical_crossentropy is incorrect

Solution

  1. Step 1: Check target label shape for next word prediction

    For next word prediction, y should be a 1D array of word indices (batch_size,), not sequences.
  2. Step 2: Identify mismatch in y shape

    y has shape (64, 15), which causes shape mismatch with model output (64, 10000).
  3. Final Answer:

    Target labels y should be shape (64,) with integer word indices, not (64, 15) -> Option A
  4. Quick Check:

    y shape must match output shape = B [OK]
Hint: Targets for next word are 1D, not sequences [OK]
Common Mistakes:
  • Using sequences as targets instead of next word
  • Confusing embedding size with RNN units
  • Changing loss function unnecessarily
5. You want to generate text using a trained RNN model. Which approach correctly generates text word by word after training?
hard
A. Feed the model the initial seed sequence, predict the next word, append it, then use the updated sequence to predict again
B. Feed the entire training dataset at once to get all generated words
C. Use the model to predict all words simultaneously without updating input
D. Randomly select words from the vocabulary without using the model

Solution

  1. Step 1: Understand sequential generation

    Text generation uses the model to predict one word at a time, updating input with new words.
  2. Step 2: Identify correct iterative approach

    Feed the model the initial seed sequence, predict the next word, append it, then use the updated sequence to predict again describes feeding seed, predicting next word, appending it, and repeating, which is correct.
  3. Final Answer:

    Feed the model the initial seed sequence, predict the next word, append it, then use the updated sequence to predict again -> Option A
  4. Quick Check:

    Generate word-by-word with updated input = D [OK]
Hint: Generate text stepwise, updating input each time [OK]
Common Mistakes:
  • Trying to generate all words at once
  • Ignoring the need to update input sequence
  • Selecting words randomly without model