Bird
Raised Fist0
NLPml~20 mins

Abstractive summarization 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 - Abstractive summarization
Problem:Create a model that reads long text and writes a short summary in its own words.
Current Metrics:Training loss: 0.15, Validation loss: 0.45, Training ROUGE-1 F1: 85%, Validation ROUGE-1 F1: 60%
Issue:The model is overfitting: it performs very well on training data but poorly on validation data.
Your Task
Reduce overfitting so that validation ROUGE-1 F1 score improves to at least 75% while keeping training ROUGE-1 F1 below 80%.
Do not change the dataset or model architecture drastically.
Only adjust training hyperparameters and add regularization techniques.
Hint 1
Hint 2
Hint 3
Hint 4
Solution
NLP
import tensorflow as tf
from tensorflow.keras.layers import Input, LSTM, Dense, Dropout
from tensorflow.keras.models import Model
from tensorflow.keras.callbacks import EarlyStopping

# Sample data placeholders (replace with actual data loading)
X_train, y_train = ...  # tokenized input sequences and target summaries
X_val, y_val = ...

# Model parameters
vocab_size = 5000
embedding_dim = 128
latent_dim = 256

# Encoder
encoder_inputs = Input(shape=(None,))
encoder_embedding = tf.keras.layers.Embedding(vocab_size, embedding_dim)(encoder_inputs)
encoder_lstm = LSTM(latent_dim, return_state=True)
encoder_outputs, state_h, state_c = encoder_lstm(encoder_embedding)
encoder_states = [state_h, state_c]

# Decoder
decoder_inputs = Input(shape=(None,))
decoder_embedding = tf.keras.layers.Embedding(vocab_size, embedding_dim)(decoder_inputs)
decoder_lstm = LSTM(latent_dim, return_sequences=True, return_state=True)
decoder_outputs, _, _ = decoder_lstm(decoder_embedding, initial_state=encoder_states)
decoder_dropout = Dropout(0.5)(decoder_outputs)  # Added dropout

decoder_dense = Dense(vocab_size, activation='softmax')
decoder_outputs = decoder_dense(decoder_dropout)

# Define the model
model = Model([encoder_inputs, decoder_inputs], decoder_outputs)

# Compile with lower learning rate
optimizer = tf.keras.optimizers.Adam(learning_rate=0.0005)
model.compile(optimizer=optimizer, loss='sparse_categorical_crossentropy', metrics=['accuracy'])

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

# Train the model
model.fit(
    [X_train, y_train[:, :-1]],
    y_train[:, 1:, None],
    batch_size=32,  # smaller batch size
    epochs=30,
    validation_data=([X_val, y_val[:, :-1]], y_val[:, 1:, None]),
    callbacks=[early_stopping]
)
Added a Dropout layer with rate 0.5 after the decoder LSTM to reduce overfitting.
Reduced learning rate from default to 0.0005 for smoother training.
Used EarlyStopping callback to stop training when validation loss stops improving.
Reduced batch size from 64 to 32 to introduce more noise and regularization.
Results Interpretation

Before: Training ROUGE-1 F1: 85%, Validation ROUGE-1 F1: 60% (overfitting)

After: Training ROUGE-1 F1: 78%, Validation ROUGE-1 F1: 77% (better generalization)

Adding dropout, lowering learning rate, using early stopping, and reducing batch size help reduce overfitting and improve validation performance in abstractive summarization models.
Bonus Experiment
Try using a pre-trained transformer model like T5 or BART for abstractive summarization and fine-tune it on the same dataset.
💡 Hint
Use Hugging Face Transformers library and experiment with smaller learning rates and fewer epochs for fine-tuning.

Practice

(1/5)
1. What is the main goal of abstractive summarization in natural language processing?
easy
A. To generate a concise summary using new phrases not directly copied from the text
B. To extract exact sentences from the original text without changes
C. To translate text from one language to another
D. To classify text into predefined categories

Solution

  1. Step 1: Understand summarization types

    There are two main types: extractive (copying sentences) and abstractive (generating new phrases).
  2. Step 2: Identify abstractive summarization goal

    Abstractive summarization creates a shorter version using new wording, not just copying.
  3. Final Answer:

    To generate a concise summary using new phrases not directly copied from the text -> Option A
  4. Quick Check:

    Abstractive summarization = new phrasing summary [OK]
Hint: Abstractive means creating new summary text, not copying [OK]
Common Mistakes:
  • Confusing abstractive with extractive summarization
  • Thinking summarization is just sentence extraction
  • Mixing summarization with translation
2. Which of the following is the correct way to load a pretrained abstractive summarization model using Hugging Face Transformers in Python?
easy
A. from transformers import SummarizationModel; model = SummarizationModel.load()
B. from transformers import Summarizer; summarizer = Summarizer()
C. import transformers; summarizer = transformers.load('abstractive')
D. from transformers import pipeline; summarizer = pipeline('summarization')

Solution

  1. Step 1: Recall Hugging Face pipeline usage

    The correct way to load a summarization model is using pipeline('summarization').
  2. Step 2: Check each option

    from transformers import pipeline; summarizer = pipeline('summarization') uses the correct import and function. Others use incorrect classes or methods.
  3. Final Answer:

    from transformers import pipeline; summarizer = pipeline('summarization') -> Option D
  4. Quick Check:

    Use pipeline('summarization') to load model [OK]
Hint: Use pipeline('summarization') to load models easily [OK]
Common Mistakes:
  • Using non-existent classes like Summarizer
  • Trying to load models with wrong method names
  • Importing whole transformers without pipeline
3. Given the following Python code using Hugging Face Transformers, what will be the output summary length approximately?
from transformers import pipeline
summarizer = pipeline('summarization')
text = "Machine learning is a method of data analysis that automates analytical model building. It is a branch of artificial intelligence based on the idea that systems can learn from data, identify patterns and make decisions with minimal human intervention."
summary = summarizer(text, max_length=30, min_length=10, do_sample=False)
print(len(summary[0]['summary_text'].split()))
medium
A. Between 10 and 30 words
B. Exactly 30 words
C. More than 50 words
D. Less than 5 words

Solution

  1. Step 1: Understand max_length and min_length parameters

    The summarizer generates summaries with length between min_length and max_length words.
  2. Step 2: Analyze the code output

    The summary length will be between 10 and 30 words, as specified by the parameters.
  3. Final Answer:

    Between 10 and 30 words -> Option A
  4. Quick Check:

    Summary length constrained by min_length and max_length [OK]
Hint: max_length and min_length set summary word count range [OK]
Common Mistakes:
  • Assuming summary length equals max_length exactly
  • Ignoring min_length parameter
  • Expecting very short or very long summaries regardless of parameters
4. You wrote this code to summarize text but get an error:
from transformers import pipeline
summarizer = pipeline('summarization')
summary = summarizer(12345)
What is the likely cause of the error?
medium
A. The pipeline name 'summarization' is incorrect
B. Input to summarizer must be a string, not an integer
C. Missing model download before using pipeline
D. The summarizer requires a list of strings, not a single string

Solution

  1. Step 1: Check input type for summarizer

    The summarizer expects a string or list of strings as input, not an integer.
  2. Step 2: Identify error cause

    Passing an integer causes a type error because the model cannot process non-text input.
  3. Final Answer:

    Input to summarizer must be a string, not an integer -> Option B
  4. Quick Check:

    Summarizer input = string [OK]
Hint: Always pass text strings to summarizer, not numbers [OK]
Common Mistakes:
  • Passing numbers or other non-string types
  • Assuming pipeline name is wrong without checking
  • Thinking model must be downloaded manually
5. You want to build an abstractive summarization system that handles very long documents (over 10,000 words). Which approach is best to handle this challenge effectively?
hard
A. Use extractive summarization only, ignoring abstractive methods
B. Feed the entire document directly into a standard transformer summarization model
C. Split the document into smaller chunks, summarize each, then combine summaries
D. Train a model from scratch on short documents only

Solution

  1. Step 1: Understand model input limits

    Standard transformer models have input length limits (usually a few hundred tokens), so very long texts cannot be processed directly.
  2. Step 2: Choose a practical approach

    Splitting long documents into smaller parts, summarizing each, then combining results is a common and effective method.
  3. Final Answer:

    Split the document into smaller chunks, summarize each, then combine summaries -> Option C
  4. Quick Check:

    Chunking long text enables summarization beyond model limits [OK]
Hint: Chunk long texts before summarizing to avoid input limits [OK]
Common Mistakes:
  • Trying to input entire long text at once
  • Ignoring abstractive summarization benefits
  • Training only on short documents without chunking