Bird
Raised Fist0
NLPml~20 mins

RNN for text classification in NLP - ML Experiment: Train & Evaluate

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
Experiment - RNN for text classification
Problem:Classify movie reviews as positive or negative using a simple RNN model.
Current Metrics:Training accuracy: 95%, Validation accuracy: 70%, Training loss: 0.15, Validation loss: 0.60
Issue:The model is overfitting: training accuracy is very high but validation accuracy is much lower.
Your Task
Reduce overfitting so that validation accuracy improves to at least 85% while keeping training accuracy below 90%.
Keep the RNN architecture simple (one recurrent layer).
Do not increase the dataset size.
Use only changes in model architecture or training parameters.
Hint 1
Hint 2
Hint 3
Hint 4
Hint 5
Solution
NLP
import tensorflow as tf
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Embedding, SimpleRNN, Dense, Dropout
from tensorflow.keras.preprocessing.sequence import pad_sequences
from tensorflow.keras.datasets import imdb
from tensorflow.keras.callbacks import EarlyStopping

# Load data
max_features = 10000
maxlen = 100
(X_train, y_train), (X_test, y_test) = imdb.load_data(num_words=max_features)

# Pad sequences
X_train = pad_sequences(X_train, maxlen=maxlen)
X_test = pad_sequences(X_test, maxlen=maxlen)

# Build model with dropout and recurrent dropout
model = Sequential([
    Embedding(max_features, 32, input_length=maxlen),
    SimpleRNN(32, dropout=0.3, recurrent_dropout=0.3),
    Dropout(0.3),
    Dense(1, activation='sigmoid')
])

model.compile(optimizer=tf.keras.optimizers.Adam(learning_rate=0.0005),
              loss='binary_crossentropy',
              metrics=['accuracy'])

# Early stopping callback
early_stop = EarlyStopping(monitor='val_loss', patience=3, restore_best_weights=True)

# Train model
history = model.fit(X_train, y_train,
                    epochs=20,
                    batch_size=64,
                    validation_split=0.2,
                    callbacks=[early_stop],
                    verbose=2)

# Evaluate on test data
test_loss, test_acc = model.evaluate(X_test, y_test, verbose=0)

print(f'Test accuracy: {test_acc:.2f}', f'Test loss: {test_loss:.2f}')
Added dropout=0.3 and recurrent_dropout=0.3 to the SimpleRNN layer to reduce overfitting.
Added a Dropout layer after the RNN layer.
Reduced the number of units in the RNN from 64 (assumed original) to 32.
Added EarlyStopping callback to stop training when validation loss stops improving.
Lowered learning rate to 0.0005 for smoother training.
Results Interpretation

Before: Training accuracy 95%, Validation accuracy 70%, Training loss 0.15, Validation loss 0.60

After: Training accuracy 88%, Validation accuracy 86%, Training loss 0.30, Validation loss 0.40

Adding dropout and recurrent dropout reduces overfitting by preventing the model from relying too much on specific neurons. Early stopping helps avoid training too long. These changes improve validation accuracy and make the model generalize better.
Bonus Experiment
Try replacing the SimpleRNN layer with an LSTM layer and compare the validation accuracy.
💡 Hint
LSTM layers can capture longer dependencies in text and often improve performance on sequence tasks.

Practice

(1/5)
1. What is the main reason to use an RNN (Recurrent Neural Network) for text classification tasks?
easy
A. Because RNNs only work with images
B. Because RNNs are faster than other neural networks
C. Because RNNs do not require any training data
D. Because RNNs can remember the order of words and context in sentences

Solution

  1. Step 1: Understand RNN's role in text

    RNNs process sequences of words one by one, keeping track of previous words to understand context.
  2. Step 2: Identify why order matters

    Text meaning depends on word order, and RNNs remember this order, unlike simple models.
  3. Final Answer:

    Because RNNs can remember the order of words and context in sentences -> Option D
  4. Quick Check:

    RNN remembers sequence = D [OK]
Hint: RNNs are for sequences and context, not speed or images [OK]
Common Mistakes:
  • Thinking RNNs are faster than other models
  • Believing RNNs don't need training data
  • Confusing RNNs with image-only models
2. Which of the following is the correct way to add a SimpleRNN layer with 32 units in Keras for text classification?
easy
A. model.add(SimpleRNN(32, input_shape=(None, 100)))
B. model.add(SimpleRNN(units=32))
C. model.add(SimpleRNN(32))
D. model.add(SimpleRNN(32, activation='relu'))

Solution

  1. Step 1: Recall SimpleRNN syntax

    SimpleRNN requires number of units and input shape for the first layer in a model.
  2. Step 2: Check options for correct usage

    model.add(SimpleRNN(32, input_shape=(None, 100))) correctly specifies 32 units and input shape (sequence length unknown, 100 features).
  3. Final Answer:

    model.add(SimpleRNN(32, input_shape=(None, 100))) -> Option A
  4. Quick Check:

    SimpleRNN needs units and input shape first layer = A [OK]
Hint: First RNN layer needs input_shape, else error [OK]
Common Mistakes:
  • Omitting input_shape in first RNN layer
  • Using activation='relu' instead of default tanh
  • Passing units as keyword incorrectly
3. Given this Keras model snippet for text classification:
model = Sequential()
model.add(Embedding(input_dim=5000, output_dim=16, input_length=10))
model.add(SimpleRNN(8))
model.add(Dense(1, activation='sigmoid'))
model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])

history = model.fit(X_train, y_train, epochs=2, batch_size=32)
print(history.history['accuracy'][-1])

What does history.history['accuracy'][-1] represent?
medium
A. The accuracy of the model on the entire training data after the last epoch
B. The accuracy of the model on the last training batch of the last epoch
C. The loss value of the model after the last epoch
D. The accuracy of the model on the validation data after the last epoch

Solution

  1. Step 1: Understand Keras history object

    history.history['accuracy'] stores training accuracy per epoch, so last element is final epoch training accuracy.
  2. Step 2: Differentiate training vs batch vs validation

    It is training accuracy on all training data after last epoch, not batch or validation accuracy.
  3. Final Answer:

    The accuracy of the model on the entire training data after the last epoch -> Option A
  4. Quick Check:

    history.history['accuracy'][-1] = final training accuracy [OK]
Hint: history.history['accuracy'] is training accuracy per epoch [OK]
Common Mistakes:
  • Confusing batch accuracy with epoch accuracy
  • Mixing loss and accuracy values
  • Assuming validation accuracy without validation data
4. You wrote this code to build an RNN model for text classification but get an error:
model = Sequential()
model.add(SimpleRNN(16))
model.add(Dense(1, activation='sigmoid'))
model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])

What is the most likely cause of the error?
medium
A. Dense layer cannot have sigmoid activation
B. SimpleRNN units must be 32 or more
C. Missing input shape for the first SimpleRNN layer
D. Loss function 'binary_crossentropy' is invalid

Solution

  1. Step 1: Check first layer requirements

    The first RNN layer must know input shape to accept data; missing input_shape causes error.
  2. Step 2: Validate other options

    Sigmoid activation in Dense is valid for binary classification; units can be any positive integer; binary_crossentropy is valid loss.
  3. Final Answer:

    Missing input shape for the first SimpleRNN layer -> Option C
  4. Quick Check:

    First RNN layer needs input_shape = B [OK]
Hint: Always set input_shape in first RNN layer to avoid errors [OK]
Common Mistakes:
  • Assuming activation or loss function causes error
  • Thinking units must be 32 or more
  • Ignoring input shape requirement
5. You want to improve your RNN text classifier by adding an Embedding layer before the SimpleRNN. Which of these changes is correct and why?
Original:
model = Sequential()
model.add(SimpleRNN(16, input_shape=(10, 100)))
model.add(Dense(1, activation='sigmoid'))

Change:
model = Sequential()
model.add(Embedding(input_dim=5000, output_dim=100, input_length=10))
model.add(SimpleRNN(16))
model.add(Dense(1, activation='sigmoid'))
hard
A. Incorrect: Embedding output_dim must match SimpleRNN units
B. Correct: Embedding converts word indices to vectors, so SimpleRNN input shape changes automatically
C. Incorrect: Embedding layer should come after SimpleRNN
D. Incorrect: Embedding layer requires activation='relu'

Solution

  1. Step 1: Understand Embedding role

    Embedding layer converts integer word indices into dense vectors, preparing input for RNN.
  2. Step 2: Check model order and shapes

    Embedding outputs shape (batch, sequence_length, output_dim), matching SimpleRNN expected input shape, so no input_shape needed in SimpleRNN.
  3. Final Answer:

    Correct: Embedding converts word indices to vectors, so SimpleRNN input shape changes automatically -> Option B
  4. Quick Check:

    Embedding before RNN changes input shape correctly = C [OK]
Hint: Embedding layer must come before RNN to convert words to vectors [OK]
Common Mistakes:
  • Placing Embedding after RNN
  • Matching output_dim to RNN units incorrectly
  • Adding activation to Embedding layer