🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
đŸ’ŧ Servicesâ„šī¸ Aboutâœ‰ī¸ ContactView Pricing Plansfrom $10

Question Answering

Generative NLPExtractive and Generative QA SystemsđŸŸĸ Free Lesson

Question Answering

Question answering (QA) systems aim to automatically answer questions posed in natural language. QA spans extractive, generative, and retrieval-based approaches.

QA Types Comparison

TypeInputOutputExample
Extractive(Question, Context)Span from contextSQuAD
Generative(Question, Context)Free-form answerNatural Questions
Open-domainQuestionAnswer + sourcesTriviaQA
Closed-bookQuestionAnswer onlyWebQuestions
Multi-hop(Question, Contexts)Chain of reasoningHotpotQA

Extractive QA

Extractive QA identifies a span of text from the context that answers the question.

python
from transformers import (
    AutoModelForQuestionAnswering,
    AutoTokenizer,
    pipeline
)

# Using Hugging Face pipeline
qa_pipeline = pipeline(
    "question-answering",
    model="distilbert-base-cased-distilled-squad"
)

context = """
BERT was developed by Google and released in 2018.
It achieved state-of-the-art results on eleven NLP tasks.
BERT stands for Bidirectional Encoder Representations from Transformers.
"""

question = "When was BERT released?"
result = qa_pipeline(question=question, context=context)

print(f"Answer: {result['answer']}")
print(f"Score: {result['score']:.4f}")
print(f"Start: {result['start']}, End: {result['end']}")
# Answer: 2018
# Score: 0.9876

Custom Extractive QA Model

python
import torch
import torch.nn as nn
from transformers import AutoModel

class ExtractiveQA(nn.Module):
    def __init__(self, model_name="bert-base-uncased"):
        super().__init__()
        self.encoder = AutoModel.from_pretrained(model_name)
        hidden_size = self.encoder.config.hidden_size

        self.qa_outputs = nn.Linear(hidden_size, 2)  # start + end logits

    def forward(self, input_ids, attention_mask, token_type_ids=None):
        outputs = self.encoder(
            input_ids=input_ids,
            attention_mask=attention_mask,
            token_type_ids=token_type_ids
        )

        sequence_output = outputs.last_hidden_state
        logits = self.qa_outputs(sequence_output)  # (batch, seq_len, 2)

        start_logits, end_logits = logits.split(1, dim=-1)
        start_logits = start_logits.squeeze(-1)
        end_logits = end_logits.squeeze(-1)

        return start_logits, end_logits

def train_qa_step(model, batch, optimizer):
    model.train()
    start_logits, end_logits = model(
        batch['input_ids'],
        batch['attention_mask'],
        batch.get('token_type_ids')
    )

    # Loss: negative log-likelihood of start and end positions
    start_loss = nn.functional.cross_entropy(start_logits, batch['start_positions'])
    end_loss = nn.functional.cross_entropy(end_logits, batch['end_positions'])
    loss = (start_loss + end_loss) / 2

    loss.backward()
    optimizer.step()
    optimizer.zero_grad()
    return loss.item()

SQuAD Dataset

VersionTrainDevDescription
SQuAD 1.187,59910,570Extractive QA
SQuAD 2.0130,31911,877+ Unanswerable questions
Natural Questions307,3737,844Real Google queries
TriviaQA95,00013,838Trivia questions
HotpotQA90,5647,405Multi-hop reasoning

Generative QA

Generative QA produces free-form answers rather than extracting spans.

python
from transformers import AutoModelForCausalLM, AutoTokenizer

class GenerativeQA:
    def __init__(self, model_name="google/gemma-2b"):
        self.tokenizer = AutoTokenizer.from_pretrained(model_name)
        self.model = AutoModelForCausalLM.from_pretrained(model_name)

    def answer(self, question, context="", max_length=200):
        prompt = f"Question: {question}\nContext: {context}\nAnswer:"
        inputs = self.tokenizer(prompt, return_tensors="pt")

        outputs = self.model.generate(
            **inputs,
            max_length=max_length,
            temperature=0.7,
            top_p=0.9,
            do_sample=True
        )

        return self.tokenizer.decode(outputs[0], skip_special_tokens=True)

qa = GenerativeQA()
answer = qa.answer(
    "What is machine learning?",
    "Machine learning is a subset of AI that enables systems to learn from data."
)

Multi-Hop Question Answering

Multi-hop QA requires reasoning across multiple pieces of evidence.

python
def multi_hop_qa(question, paragraphs, model):
    # Hop 1: Identify relevant paragraphs
    relevance_scores = [model.score(question, p) for p in paragraphs]
    top_paragraphs = sorted(range(len(paragraphs)),
                           key=lambda i: relevance_scores[i], reverse=True)[:3]

    # Hop 2: Iteratively refine answer
    current_context = ""
    for idx in top_paragraphs:
        current_context += paragraphs[idx] + "\n"
        intermediate_answer = model.extract_answer(question, current_context)

        if is_final_answer(intermediate_answer):
            return intermediate_answer

    return intermediate_answer

def is_final_answer(answer):
    # Heuristic: if answer is a named entity or number, likely final
    return len(answer.split()) <= 5 and not answer.startswith("According")

Evaluation Metrics

MetricDescriptionRange
Exact Match (EM)Percentage of exact matches0-100
F1 ScoreToken-level overlap0-100
ROUGE-LLongest common subsequence0-1
BERTScoreSemantic similarity0-1

Extended Learning: Beyond the Basics

Key Concepts Summary

This lesson covers fundamental concepts that serve as building blocks for more advanced topics. Master these basics before moving to intermediate and advanced material.

Prerequisite Knowledge

Before studying this topic in depth, ensure you understand:

  • Basic definitions and terminology
  • Core formulas and their derivations
  • Common applications in real-world scenarios
  • Typical pitfalls and misconceptions

Step-by-Step Walkthrough

Let us work through a complete example to solidify understanding:

Step 1: Identify the problem type. Determine which category this problem falls into and which approach is most appropriate.

Step 2: Apply the relevant formula. Substitute known values into the appropriate equation, paying attention to units and constraints.

Step 3: Simplify and solve. Work through the algebra step by step, checking each intermediate result.

Step 4: Verify the answer. Check that the solution satisfies the original conditions and makes logical sense.

Common Mistakes to Avoid

  1. Misidentifying the problem type — Always start by categorizing the problem
  2. Incorrect formula application — Verify the formula applies to your specific case
  3. Unit errors — Always check units are consistent throughout
  4. Sign errors — Pay careful attention to positive and negative values
  5. Rounding too early — Keep full precision until the final answer
  6. Forgetting constraints — Check that solutions satisfy all given conditions

Real-World Applications

Understanding this concept is essential for:

  • Advanced problem solving in examinations
  • Building intuition for more complex topics
  • Developing analytical thinking skills
  • Applying mathematical reasoning to practical situations

Practice Exercises

  1. Basic: Solve 5 problems of increasing difficulty using the core concept.
  2. Intermediate: Apply the concept to word problems with multiple steps.
  3. Advanced: Combine this concept with 2-3 other topics in a comprehensive problem.
  4. Challenge: Create your own problem that requires this concept plus additional knowledge.

Interview and Exam Tips

  • Common question patterns: Identify which exam or interview formats test this topic
  • Time management: Practice completing problems within time constraints
  • Common traps: Know the typical mistakes examiners set as distractors
  • Verification strategy: Develop a quick method to check your answer

Related Topics

Quick Reference Card

ConceptFormula/RuleKey InsightCommon Use
Core DefinitionSee main textUnderstand the intuitionFoundation for all applications
Key FormulaSee main textMemorize the derivationDirect problem solving
Special CaseSee main textRecognize when it appliesSimplifies complex problems
Edge CaseSee main textKnow the limitationsAvoids errors

Further Reading

For students who want to go deeper:

  • Standard textbooks on the subject
  • Research papers applying this concept
  • Online courses with video explanations
  • Practice problem collections with detailed solutions
CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-11-14

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Need Expert NLP Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement