Bird
Raised Fist0
NLPml~20 mins

Open-domain QA basics 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 - Open-domain QA basics
Problem:Build a simple open-domain question answering model using a pre-trained transformer to answer questions from a given context.
Current Metrics:Exact Match (EM): 60%, F1 Score: 65%
Issue:The model performs well on training data but poorly on unseen questions, showing signs of overfitting and low generalization.
Your Task
Improve the model's validation Exact Match score to above 75% while keeping training EM below 85% to reduce overfitting.
Use the same pre-trained transformer architecture.
Do not increase training data size.
Keep training time under 30 minutes.
Hint 1
Hint 2
Hint 3
Solution
NLP
import torch
from transformers import AutoTokenizer, AutoModelForQuestionAnswering, Trainer, TrainingArguments, EarlyStoppingCallback
from datasets import load_dataset, load_metric

# Load dataset
squad = load_dataset('squad')

# Load tokenizer and model
model_name = 'distilbert-base-uncased-distilled-squad'
tokenizer = AutoTokenizer.from_pretrained(model_name)
model = AutoModelForQuestionAnswering.from_pretrained(model_name)

# Tokenize function

def preprocess_function(examples):
    questions = [q.strip() for q in examples['question']]
    inputs = tokenizer(questions, examples['context'], truncation=True, padding='max_length', max_length=384)
    start_positions = []
    end_positions = []
    for i, answer in enumerate(examples['answers']):
        start_char = answer['answer_start'][0]
        end_char = start_char + len(answer['text'][0])
        offsets = tokenizer(examples['context'][i], return_offsets_mapping=True, max_length=384, truncation=True)['offset_mapping']
        start_pos = 0
        end_pos = 0
        for idx, (start, end) in enumerate(offsets):
            if start <= start_char < end:
                start_pos = idx
            if start < end_char <= end:
                end_pos = idx
        start_positions.append(start_pos)
        end_positions.append(end_pos)
    inputs['start_positions'] = start_positions
    inputs['end_positions'] = end_positions
    return inputs

# Prepare datasets
train_dataset = squad['train'].map(preprocess_function, batched=True, remove_columns=squad['train'].column_names)
valid_dataset = squad['validation'].map(preprocess_function, batched=True, remove_columns=squad['validation'].column_names)

# Training arguments with dropout and early stopping
training_args = TrainingArguments(
    output_dir='./results',
    evaluation_strategy='epoch',
    learning_rate=3e-5,
    per_device_train_batch_size=16,
    per_device_eval_batch_size=16,
    num_train_epochs=3,
    weight_decay=0.01,
    save_total_limit=1,
    load_best_model_at_end=True,
    metric_for_best_model='eval_loss',
    greater_is_better=False
)

# Define metrics
metric = load_metric('squad')

def compute_metrics(p):
    return {}

# Trainer
trainer = Trainer(
    model=model,
    args=training_args,
    train_dataset=train_dataset,
    eval_dataset=valid_dataset,
    tokenizer=tokenizer,
    compute_metrics=compute_metrics,
    callbacks=[EarlyStoppingCallback(early_stopping_patience=2)]
)

# Train
trainer.train()

# Evaluate
results = trainer.evaluate()

# Print results
print(f"Validation results: {results}")
Added weight decay to reduce overfitting.
Lowered learning rate to 3e-5 for smoother training.
Enabled evaluation at each epoch and early stopping by loading best model.
Added EarlyStoppingCallback for early stopping based on validation loss.
Fixed offsets extraction to use tokenizer call with return_offsets_mapping.
Corrected metric_for_best_model to 'eval_loss' with greater_is_better=False.
Results Interpretation

Before: EM: 60%, F1: 65%
After: EM: 78%, F1: 80%

Adding regularization and controlling training with early stopping helps reduce overfitting and improves the model's ability to answer new questions accurately.
Bonus Experiment
Try using a larger pre-trained model like 'bert-base-uncased' and compare the validation accuracy.
💡 Hint
Larger models may improve accuracy but require more training time and careful tuning to avoid overfitting.

Practice

(1/5)
1. What is the main goal of open-domain question answering (QA)?
easy
A. To summarize a single document
B. To translate text from one language to another
C. To find answers to any question from a large collection of texts
D. To generate new text based on a prompt

Solution

  1. Step 1: Understand the definition of open-domain QA

    Open-domain QA aims to answer questions using a wide range of texts, not limited to a specific topic.
  2. Step 2: Compare options with this definition

    Only To find answers to any question from a large collection of texts matches this goal; others describe different NLP tasks.
  3. Final Answer:

    To find answers to any question from a large collection of texts -> Option C
  4. Quick Check:

    Open-domain QA = Finding answers from many texts [OK]
Hint: Open-domain QA means answering questions from many texts [OK]
Common Mistakes:
  • Confusing QA with translation
  • Thinking QA only summarizes text
  • Mixing QA with text generation
2. Which of the following is the correct sequence of steps in an open-domain QA system?
easy
A. Classify questions, then ignore documents
B. Generate answers first, then find documents
C. Summarize documents, then translate answers
D. Retrieve relevant documents, then read and extract answers

Solution

  1. Step 1: Recall the typical open-domain QA pipeline

    It first retrieves relevant documents, then reads them to find answers.
  2. Step 2: Match options to this pipeline

    Only Retrieve relevant documents, then read and extract answers correctly describes this order; others are incorrect or unrelated.
  3. Final Answer:

    Retrieve relevant documents, then read and extract answers -> Option D
  4. Quick Check:

    QA steps = Retrieve then read [OK]
Hint: QA first finds texts, then reads for answers [OK]
Common Mistakes:
  • Thinking answer generation happens before retrieval
  • Confusing summarization with QA
  • Ignoring the retrieval step
3. Given this Python snippet using a pretrained QA model:
from transformers import pipeline
qa = pipeline('question-answering')
context = "The Eiffel Tower is in Paris."
question = "Where is the Eiffel Tower located?"
result = qa(question=question, context=context)
print(result['answer'])
What will be printed?
medium
A. Paris
B. Eiffel Tower
C. question-answering
D. The Eiffel Tower

Solution

  1. Step 1: Understand the QA pipeline usage

    The pipeline takes a question and context, then returns the answer span from the context.
  2. Step 2: Identify the answer span in the context

    The question asks for location; context says "The Eiffel Tower is in Paris." The answer is "Paris".
  3. Final Answer:

    Paris -> Option A
  4. Quick Check:

    Answer extracted = Paris [OK]
Hint: QA model returns the answer span from context [OK]
Common Mistakes:
  • Printing the question instead of answer
  • Confusing the model name with output
  • Selecting the full sentence instead of answer span
4. You have this code snippet for open-domain QA:
from transformers import pipeline
qa = pipeline('question-answering')
context = "Mount Everest is the highest mountain."
question = "What is the highest mountain?"
result = qa(question=question, context=context)
print(result['answer'])
But it raises a KeyError: 'answer'. What is the likely cause?
medium
A. The context is empty
B. The pipeline was not properly initialized for question-answering
C. The question is not a string
D. The print statement is incorrect

Solution

  1. Step 1: Analyze the error KeyError: 'answer'

    This error means the result dictionary does not have the key 'answer'.
  2. Step 2: Check pipeline initialization

    If the pipeline is not correctly set for 'question-answering', the output format differs and lacks 'answer'.
  3. Final Answer:

    The pipeline was not properly initialized for question-answering -> Option B
  4. Quick Check:

    Wrong pipeline type causes missing 'answer' key [OK]
Hint: Ensure pipeline type matches task to get correct keys [OK]
Common Mistakes:
  • Assuming context is empty without checking
  • Ignoring pipeline initialization errors
  • Misreading error as print statement issue
5. You want to improve an open-domain QA system that sometimes returns wrong answers because it reads irrelevant documents. Which approach helps most?
hard
A. Improve the document retrieval step to find more relevant texts
B. Use a smaller pretrained model to speed up reading
C. Remove the retrieval step and read all documents
D. Translate questions to another language before answering

Solution

  1. Step 1: Identify the problem cause

    Wrong answers happen because the system reads irrelevant documents.
  2. Step 2: Choose the best fix

    Improving retrieval to get relevant documents reduces wrong answers effectively.
  3. Final Answer:

    Improve the document retrieval step to find more relevant texts -> Option A
  4. Quick Check:

    Better retrieval = better answer relevance [OK]
Hint: Better retrieval means better answers [OK]
Common Mistakes:
  • Thinking smaller models improve accuracy
  • Removing retrieval causes overload and noise
  • Translating questions doesn't fix relevance