For text generation using RNNs, common metrics include perplexity and cross-entropy loss. These measure how well the model predicts the next word or character in a sequence. Lower perplexity means the model is better at guessing the next token, which leads to more natural and coherent text. Accuracy can be used but is less informative because predicting exact next words is hard and many outputs can be valid.
Text generation with RNN in TensorFlow - Model Metrics & Evaluation
Text generation is a sequence prediction task with many possible outputs, so confusion matrices are not practical. Instead, we look at loss curves and perplexity scores over training epochs.
Epoch | Training Loss | Validation Loss | Perplexity
-----------------------------------------------
1 | 2.5 | 2.7 | 12.2
2 | 2.1 | 2.3 | 9.9
3 | 1.8 | 2.0 | 7.4
4 | 1.6 | 1.9 | 6.7
5 | 1.5 | 1.8 | 6.1
This shows the model is improving as loss and perplexity decrease.
Precision and recall are less relevant for text generation because the output is open-ended. Instead, there is a tradeoff between creativity and coherence. For example:
- High creativity: The model generates surprising and diverse text but may produce errors or nonsense.
- High coherence: The model produces safe, predictable text but may be boring or repetitive.
This tradeoff can be controlled by parameters like temperature during sampling.
Good:
- Low cross-entropy loss (e.g., below 1.5 on validation data)
- Low perplexity (close to 1 means perfect prediction)
- Generated text is fluent, relevant, and context-aware
Bad:
- High loss and perplexity (e.g., above 3 or 4)
- Generated text is random, repetitive, or nonsensical
- Model overfits training data and fails on new prompts
- Overfitting: Low training loss but high validation loss means the model memorizes training text and can't generalize.
- Ignoring diversity: Only optimizing for loss can lead to dull, repetitive text.
- Using accuracy: Accuracy is misleading because many next words can be correct; it doesn't capture quality well.
- Data leakage: If test data overlaps with training, metrics will be unrealistically good.
Your RNN text generation model has a validation accuracy of 85% but a perplexity of 50. Is this model good for generating text? Why or why not?
Answer: No, this model is not good. The high accuracy is misleading because many next words can be correct, so accuracy is not reliable here. The very high perplexity (50) means the model is very uncertain about the next word predictions, so generated text will likely be poor quality and incoherent.
Practice
Solution
Step 1: Understand RNN function in text
RNNs process sequences and learn how words follow each other.Step 2: Identify the goal of text generation
The goal is to predict the next word based on previous words.Final Answer:
To learn patterns in sequences of words and predict the next word -> Option CQuick Check:
RNN predicts next word = B [OK]
- Thinking RNNs sort or count words
- Confusing RNN with image processing
- Assuming RNNs translate text directly
Solution
Step 1: Identify embedding layer syntax
Embedding layers use input_dim and output_dim to map words to vectors.Step 2: Match correct TensorFlow layer
tf.keras.layers.Embedding is the correct layer for word embeddings.Final Answer:
tf.keras.layers.Embedding(input_dim=vocab_size, output_dim=embedding_dim) -> Option DQuick Check:
Embedding layer uses input_dim and output_dim = A [OK]
- Using Dense instead of Embedding for word vectors
- Confusing Conv2D with text embedding
- Applying MaxPooling1D incorrectly for embeddings
model = tf.keras.Sequential([ tf.keras.layers.Embedding(input_dim=1000, output_dim=64), tf.keras.layers.SimpleRNN(128, return_sequences=False), tf.keras.layers.Dense(1000, activation='softmax') ]) input_shape = (32, 10) # batch size 32, sequence length 10 output = model(tf.random.uniform(input_shape, maxval=1000, dtype=tf.int32)) print(output.shape)
Solution
Step 1: Analyze RNN layer output shape
SimpleRNN with return_sequences=False outputs (batch_size, units) = (32, 128).Step 2: Check Dense layer output shape
Dense layer with 1000 units outputs (32, 1000).Final Answer:
(32, 1000) -> Option AQuick Check:
Final output shape = (batch_size, vocab_size) = C [OK]
- Confusing return_sequences=True output shape
- Ignoring batch size in output shape
- Mixing RNN units with Dense output units
model = tf.keras.Sequential([ tf.keras.layers.Embedding(input_dim=5000, output_dim=64), tf.keras.layers.SimpleRNN(128, return_sequences=True), tf.keras.layers.Dense(5000, activation='softmax') ]) model.compile(optimizer='adam', loss='sparse_categorical_crossentropy') # Training data: input sequences of shape (batch_size, seq_length) # Labels: next word indices of shape (batch_size, seq_length) model.fit(train_data, train_labels, epochs=5)
Solution
Step 1: Check RNN output and labels shape
return_sequences=True outputs sequences matching label shape (batch_size, seq_length).Step 2: Verify loss function suitability
sparse_categorical_crossentropy is correct for integer labels in classification.Final Answer:
Using return_sequences=True but labels shape is (batch_size, seq_length) which is correct -> Option BQuick Check:
return_sequences=True matches label shape = A [OK]
- Assuming labels must be 1D when output is sequence
- Choosing wrong loss function for integer labels
- Changing embedding input_dim unnecessarily
Solution
Step 1: Understand text generation process
Text generation uses seed text and predicts one word at a time.Step 2: Describe iterative prediction
After predicting a word, append it to input and predict next word repeatedly.Final Answer:
Feed initial seed text, predict next word, append it, then feed updated text repeatedly -> Option AQuick Check:
Stepwise prediction with updated input = D [OK]
- Trying to predict all words at once without feedback
- Ignoring seed text and using random words
- Feeding entire dataset instead of seed for generation
Ready to prove it?
Pass the test and this pattern moves unknown
