Learning to generate text, one character at a time (optional)
A Tiny Shakespeare companion to Lectures 14 and 15
Author
Marcel Turcotte
Published
November 30, 2026
This material will not appear on course evaluations.
How much of a play could a network learn by predicting its next character? We compare a feedforward network and a one-dimensional convolutional network (CNN) on continuous text and look for spelling, dialogue layout, and coherence. The experiment connects Lecture 14’s cross-entropy with Lecture 15’s convolution.
This notebook extends the name-generation exercise and can be run on its own. Name-generation notebook
Preparation
Run the cells in order from a fresh kernel with NumPy, Matplotlib, and TensorFlow with Keras. Each training call reports its elapsed time.
Show setup
import osos.environ["KERAS_BACKEND"] ="tensorflow"from pathlib import Pathfrom time import perf_counterimport numpy as npimport matplotlib.pyplot as pltimport tensorflow as tffrom tensorflow import kerasSEED =42CONTEXT_LENGTH =32HIDDEN_UNITS =128FILTERS =64KERNEL_SIZE =3EPOCHS =12BATCH_SIZE =256LEARNING_RATE =0.003keras.utils.set_random_seed(SEED)print(f"TensorFlow {tf.__version__}, Keras backend: {keras.backend.backend()}")
TensorFlow 2.21.0, Keras backend: tensorflow
The corpus and its partitions
Tiny Shakespeare contains approximately 1.1 million characters from Shakespeare’s works. Capitalization, punctuation, spaces, and newlines all contribute to the patterns the model learns. Tiny Shakespeare corpus
The setup uses the bundled data/tiny_shakespeare.txt or downloads the pinned copy.
Corpus: 1,115,394 characters
Partitions: 892,315 training, 111,539 validation, 111,540 test
We split the text into contiguous 80%, 10%, and 10% blocks before making examples. Each window and target stay in the same block. Later blocks can contain different plays and speakers.
From text to training examples
The input is a window of characters. The target is the character immediately after it. Moving the window one character forward gives another example.
First context 'First Citizen:\nBefore we proceed'
Next character ' '
Each character is a token. We assign integer IDs using the 65 characters in the training block and reuse that vocabulary throughout. One-hot encoding sets the channel for the current character to 1 and all other channels to 0. The default input has shape (32, 65), and the target stays an integer ID.
vocabulary =sorted(set(train_text))VOCAB_SIZE =len(vocabulary)char_to_id = {char: index for index, char inenumerate(vocabulary)}def encode(passage):return np.array([char_to_id[char] for char in passage], dtype="int32")train_ids = encode(train_text)valid_ids = encode(valid_text)test_ids = encode(test_text)print("Vocabulary size", VOCAB_SIZE)
Vocabulary size 65
The text supplies the targets. To keep memory use manageable, we store the character IDs and build one-hot inputs a batch at a time. The first CONTEXT_LENGTH characters in each block supply context for the first example.
The feedforward network flattens the context and uses a Dense layer to combine its positions. It returns one logit per possible next character. Cross-entropy averages the negative log probability of the observed targets. from_logits=True tells Keras that the model returns scores before softmax.
Autoregressive generation samples a character, appends it, and repeats with the updated context. The model’s weights stay fixed. Use a prompt with at least CONTEXT_LENGTH characters from the vocabulary. We generate a fixed number of characters, including any punctuation and newlines sampled.
We save a continuation from the untrained model, then train it on next-character examples.
mlp_history = train_model(mlp)
Epoch 1/12
/Users/turcotte/.virtualenvs/csi4106/lib/python3.12/site-packages/keras/src/trainers/epoch_iterator.py:74: UserWarning: `shuffle=True` was passed, but will be ignored since the data `x` was provided as a tf.data.Dataset. The Dataset is expected to already be shuffled (via `.shuffle(buffer_size)`).
self.data_adapter = data_adapters.get_data_adapter(
The CNN applies shared filters to triples of characters before flattening. The Dense layer combines those responses across the whole window. At the default context length the two models have similar parameter counts. They train on the same examples with the same settings.
Prompt
First Citizen:
Before we proceed any further, hear me speak.
Al
Untrained feedforward
lPqf,xkm.QLuboPBX$obkLysl?R!3dixILS?.RCePogHpmLGe3?
mdglPW3-eRXkbXWF!OANpC$FGdWmeNn: 'gR:T3fOLHbJ'-xtfExlhPF,sQAGY?qjgObZc'N!TJ3,Z;uXJZ xRl'RTvYSEIUO os3W-eFeil,uC!XKonIwFUDv;$PzsjssVHldL,iEvD-p3;aq?HlxT.
C3f-UeY?ngj..vNGSdwGu Xb,3NxZvnQm
-
Trained feedforward
l: new, and steat the would beet
Lest Tobsens. France, sish resties,
Let hath my homb, if guil of cruretand blood,
Which save in thus nawns live can Now nessaxe ther to the wailus.
DORSET:
Ye parns inia a bill of thank in werarge not;
My b
Trained Conv1D
l:
Now, and the marriay. He have lie less.
QUEEN ELIZABETH:
I shall leave if the sea.
CORIOLANUS:
What, make he from the hand and please and plaenided
The quick and thrife. Amy, to must revent coungly a denance to cere those
Than your sai
Follow learning on held-out text
Validation loss measures next-character prediction on unseen passages. Compare it with training loss across epochs.
Each model sees only the last CONTEXT_LENGTH characters. What happens when two prompts share that entire suffix? Compare the two predictions for each model.
shared_context = PROMPT[-CONTEXT_LENGTH:]prefix_a ="The king is angry.\n"+ shared_contextprefix_b ="The king is pleased.\n"+ shared_contextprint("Shared context", repr(shared_context))for model in (mlp, cnn): probabilities_a = next_probabilities(model, prefix_a) probabilities_b = next_probabilities(model, prefix_b) difference = np.max(np.abs(probabilities_a - probabilities_b))print(f"{model.name} largest probability difference {difference:.1e}")
Shared context ' any further, hear me speak.\n\nAl'
feedforward largest probability difference 0.0e+00
convolutional largest probability difference 0.0e+00
Both calls give each model the same input, so its predictions agree exactly.
Try a different context length
For an optional experiment, change CONTEXT_LENGTH from 32 to 8, restart the kernel, and rerun through the validation plots. Compare the samples and validation loss. The shorter context also reduces the number of parameters.
Final evaluation on the test block
Run this cell once after choosing settings. The table shows mean cross-entropy in nats per target. The bigram reference uses only the immediately preceding character.
Show final evaluation code
bigram_counts = np.ones((VOCAB_SIZE, VOCAB_SIZE))np.add.at(bigram_counts, (train_ids[:-1], train_ids[1:]), 1)bigram_probabilities = bigram_counts / bigram_counts.sum(axis=1, keepdims=True)previous = test_ids[CONTEXT_LENGTH -1:-1]targets = test_ids[CONTEXT_LENGTH:]bigram_loss =-np.log(bigram_probabilities[previous, targets]).mean()test_losses = {"Bigram": bigram_loss}test_data = make_dataset(test_ids)for label, model in (("Feedforward", mlp), ("Conv1D", cnn)): test_losses[label] = model.evaluate(test_data, verbose=0)print(f"{'Model':<15}{'Cross-entropy (nats per target)':>32}")for label, loss in test_losses.items():print(f"{label:<15}{loss:>32.3f}")
Model Cross-entropy (nats per target)
Bigram 2.503
Feedforward 2.348
Conv1D 2.372
References
Shakespeare, W. Text compiled as Tiny Shakespeare in Karpathy, A., char-rnn. The loading cell specifies the exact corpus revision and checksum.