Table of Contents

    A/B Testing and Online Experimentation

    Model Evaluation and Validation

    A/B Testing and Online Experimentation

    Learn how to design, run, analyze, and interpret controlled online experiments for products, Machine Learning systems, websites, and business decisions.

    Introduction

    Offline evaluation tells us how a model or feature performed on historical data. It does not always tell us what will happen when real users interact with the changed system.

    A/B testing is a controlled experiment in which eligible experimental units are randomly assigned to different versions of an experience. Their outcomes are then compared using predefined metrics.

    Version A is commonly the current experience, called the control. Version B is the proposed change, called the treatment or variant. Random assignment helps make the groups comparable before the treatment is applied.

    Simple definition: An A/B test randomly assigns comparable experimental units to a control or treatment and measures whether the treatment causes a meaningful change in a predefined outcome.

    Learning Objectives

    By the End of This Lesson

    • Explain the purpose of A/B testing
    • Distinguish correlation from causal evidence
    • Define control, treatment, and experimental unit
    • Write a clear and testable hypothesis
    • Select primary, secondary, and guardrail metrics
    • Understand random assignment and sample-ratio checks
    • Explain null and alternative hypotheses
    • Interpret p-values and confidence intervals correctly
    • Distinguish statistical significance from practical significance
    • Understand false positives, false negatives, and statistical power
    • Plan sample size using a minimum detectable effect
    • Calculate absolute and relative changes
    • Analyze binary and continuous metrics
    • Recognize repeated-peeking and early-stopping risks
    • Understand novelty, carryover, interference, and logging risks
    • Apply experimentation to Machine Learning systems
    • Create an experiment decision record

    Prerequisites

    Recommended Knowledge

    • Basic probability and statistics
    • Mean, variance, and standard deviation
    • Sampling and population concepts
    • Machine Learning evaluation metrics
    • Basic Python, NumPy, and pandas
    • Basic business-metric interpretation

    Packages for the Coding Examples

    • NumPy
    • pandas
    • SciPy
    • statsmodels
    python -m pip install numpy pandas scipy statsmodels
    Data requirement: Use only authorized experiment data. Remove unnecessary personal information and follow applicable consent, security, retention, privacy, and organizational requirements.

    Control and Treatment

    Control

    • Represents the current or baseline experience
    • Provides a reference for comparison
    • Should remain stable during the experiment
    • Is commonly called version A

    Treatment

    • Receives the proposed change
    • Differs according to the documented treatment
    • Is evaluated against the same metric definitions
    • Is commonly called version B
    Basic Experiment
    Eligible Population → Random Assignment → Control or Treatment → Outcome Comparison

    Correlation vs Causation

    Observational data can reveal that two variables move together, but this does not prove that one caused the other. Users who choose a feature may already differ from users who do not choose it.

    Random assignment helps break systematic relationships between treatment assignment and pre-existing user characteristics. If the experiment is implemented correctly, differences in outcomes can be attributed more credibly to the treatment.

    Observational Claim Users who enabled the feature retained more often, so the feature must have caused the improved retention.
    Experimental Approach Randomly assign eligible users to experiences with and without the feature, then compare a predefined retention metric.

    Choose the Experimental Unit

    The experimental unit is the entity independently assigned to a variant. It should match how the treatment operates and how interference can occur.

    Unit Possible Use Important Risk
    User Personalized interface or recommendation change One user may use several devices
    Account Business or subscription experience Several users may share one account
    Session Short-lived experience A returning user may see several variants
    Store Retail process or pricing experiment Stores may differ substantially in size or location
    Geographical Area Region-level policy or marketing intervention Neighboring areas may influence each other
    Time Block Infrastructure or marketplace experiment Traffic and demand may vary by time
    Consistency rule: If assignment occurs at user level, calculate uncertainty using user-level experimental units rather than treating every user event as independent.

    Random Assignment

    Random assignment gives eligible experimental units a defined chance of receiving each variant. It is the foundation of a controlled experiment.

    Assignment Requirements

    • Define the eligible population before starting
    • Assign units using a reproducible randomization mechanism
    • Keep assignment persistent when repeated exposure matters
    • Prevent one unit from appearing in incompatible groups
    • Log assignment before measuring treatment outcomes
    • Validate traffic allocation after launch
    • Investigate unexpected group-size differences
    Invalid Assignment Send the treatment only to highly engaged users and compare them with all remaining users.
    Valid Principle Randomly assign eligible units using the predefined allocation and inclusion rules.

    Write the Hypothesis First

    A useful hypothesis describes the change, affected population, expected mechanism, primary outcome, expected direction, and decision the result will support.

    Hypothesis Template
    If we introduce X → for population Y → metric Z will change → because of mechanism M
    Weak Hypothesis The new design will be better.
    Stronger Hypothesis Simplifying the registration form for eligible new visitors will increase completed registrations because fewer required steps will reduce abandonment.

    Define Metrics Before Launch

    Metric Type Purpose Example
    Primary Metric Represents the outcome used for the main decision Completed registration rate
    Secondary Metric Provides additional diagnostic or behavioral context Time required to complete registration
    Guardrail Metric Detects unacceptable harm elsewhere Error rate or complaint rate
    Diagnostic Metric Helps explain the mechanism behind the result Form-step abandonment
    Data-Quality Metric Checks experiment instrumentation and assignment Missing assignment records
    Metric definition: Document the numerator, denominator, unit of analysis, inclusion rules, exclusion rules, event window, and aggregation method.

    Conversion Rate

    A binary conversion metric records whether an experimental unit completed a defined outcome.

    Conversion Rate
    \[ \hat{p} = \frac{\text{Number of Converting Units}} {\text{Number of Eligible Assigned Units}} \]

    If the unit is a user, one user should not be counted as several independent observations merely because the user generated several events.

    Absolute and Relative Change

    Report both absolute and relative changes. A relative percentage without the baseline can be difficult to interpret.

    Absolute Change
    \[ \Delta_{\text{absolute}} = \hat{p}_{B} - \hat{p}_{A} \]
    Relative Change
    \[ \Delta_{\text{relative}} = \frac{ \hat{p}_{B}-\hat{p}_{A} }{ \hat{p}_{A} } \times 100 \]
    Example: Moving from 10% to 11% is an absolute increase of one percentage point and a relative increase of 10%.

    Null and Alternative Hypotheses

    Two-Sided Hypotheses
    \[ H_0: p_A = p_B \] \[ H_1: p_A \neq p_B \]

    The null hypothesis represents no difference between variants. The alternative represents a difference. A directional alternative should be justified and chosen before observing the result.

    Post-Result Switching Start with a two-sided test, observe the direction, and then switch to a one-sided test to obtain a smaller p-value.
    Correct Practice Specify the hypothesis, direction, metric, analysis method, and decision rule before examining treatment outcomes.

    Type I and Type II Errors

    Decision Error Meaning Practical Interpretation
    Type I Error Rejecting a true null hypothesis Concluding that the treatment had an effect when it did not
    Type II Error Failing to reject a false null hypothesis Missing a real treatment effect
    Power Probability of detecting a specified effect when it exists Ability of the planned experiment to detect the intended improvement
    Statistical Power
    \[ \text{Power} = 1-\beta \]

    Understand the P-Value

    A p-value measures how surprising the observed result, or a more extreme result, would be if the null hypothesis and statistical assumptions were true.

    Incorrect Interpretation A p-value of 0.03 means there is a 3% probability that the null hypothesis is true.
    Correct Interpretation A p-value of 0.03 means that, under the null hypothesis and model assumptions, the probability of observing a result at least as extreme as the result obtained is 3%.
    Important: A p-value does not measure effect size, business value, probability that the result will replicate, or probability that the treatment is beneficial.

    Confidence Intervals

    A confidence interval communicates the estimated effect together with uncertainty. It is usually more informative than a significance label alone.

    General Confidence Interval
    \[ \text{Estimate} \pm \text{Critical Value} \times \text{Standard Error} \]

    Questions to Ask

    • Does the interval include no effect?
    • Does the interval include the minimum useful effect?
    • Does it include meaningful harm?
    • Is the interval too wide for a confident decision?
    • How does uncertainty affect the rollout decision?

    Statistical vs Practical Significance

    A statistically detectable result may still be too small to justify implementation. The treatment may require engineering work, create support costs, increase latency, or introduce operational risk.

    Question Statistical View Practical View
    Is there evidence of a difference? Hypothesis test and confidence interval Not sufficient by itself
    How large is the effect? Effect estimate Compare with minimum useful change
    Is implementation worthwhile? Statistics provide evidence Consider cost, risk, maintenance, and strategy
    Could the change cause harm? Review uncertainty and guardrails Apply safety and operational limits

    Minimum Detectable Effect

    The minimum detectable effect, commonly abbreviated as MDE, is the effect size the experiment is designed to detect with the selected significance level and statistical power.

    Sample-Size Inputs

    • Baseline metric level
    • Minimum effect worth detecting
    • Significance level
    • Desired statistical power
    • One-sided or two-sided hypothesis
    • Expected traffic allocation
    • Metric variance
    • Experimental-unit definition
    • Expected exclusions and data loss
    Mistake Run the experiment until the result becomes significant.
    Better Approach Plan the effect size, sample requirement, analysis method, and stopping rule before launch.

    Plan Sample Size in Python

    The following example demonstrates sample-size planning for two independent conversion proportions. The values are illustrative rather than universal recommendations.

    from statsmodels.stats.power import NormalIndPower
    from statsmodels.stats.proportion import proportion_effectsize
    
    
    baseline_rate = 0.10
    minimum_target_rate = 0.11
    
    effect_size = proportion_effectsize(
        baseline_rate,
        minimum_target_rate
    )
    
    power_analysis = NormalIndPower()
    
    sample_size_per_group = power_analysis.solve_power(
        effect_size=effect_size,
        alpha=0.05,
        power=0.80,
        ratio=1.0,
        alternative="two-sided"
    )
    
    print(
        round(sample_size_per_group)
    )
    Interpretation: The calculation depends on the supplied assumptions. A different baseline, MDE, power, allocation, unit, or analysis method can produce a different requirement.

    Analyze a Binary Conversion Experiment

    This example compares two independent conversion proportions using aggregated synthetic results.

    import numpy as np
    
    from statsmodels.stats.proportion import proportions_ztest
    from statsmodels.stats.proportion import confint_proportions_2indep
    
    
    control_conversions = 1020
    control_users = 10000
    
    treatment_conversions = 1110
    treatment_users = 10000
    
    
    control_rate = (
        control_conversions
        / control_users
    )
    
    treatment_rate = (
        treatment_conversions
        / treatment_users
    )
    
    absolute_change = (
        treatment_rate
        - control_rate
    )
    
    relative_change = (
        absolute_change
        / control_rate
    )
    
    
    conversion_counts = np.array([
        control_conversions,
        treatment_conversions
    ])
    
    sample_sizes = np.array([
        control_users,
        treatment_users
    ])
    
    
    test_statistic, p_value = proportions_ztest(
        count=conversion_counts,
        nobs=sample_sizes,
        alternative="two-sided"
    )
    
    
    confidence_interval = confint_proportions_2indep(
        count1=treatment_conversions,
        nobs1=treatment_users,
        count2=control_conversions,
        nobs2=control_users,
        method="wald",
        compare="diff",
        alpha=0.05
    )
    
    
    print("Control rate:", control_rate)
    print("Treatment rate:", treatment_rate)
    print("Absolute change:", absolute_change)
    print("Relative change:", relative_change)
    print("Test statistic:", test_statistic)
    print("P-value:", p_value)
    print("95% confidence interval:", confidence_interval)
    Limitation This synthetic example demonstrates mechanics only. A real experiment also requires trustworthy assignment, correct exposure logging, metric validation, sample-ratio checks, guardrails, and an analysis aligned with its experimental unit.

    Analyze a Continuous Metric

    Revenue, order value, session duration, and latency are examples of continuous metrics. Their distributions may be skewed or contain extreme values, so the analysis plan should reflect the metric's behavior.

    import numpy as np
    
    from scipy.stats import ttest_ind
    
    
    rng = np.random.default_rng(42)
    
    control_revenue = rng.gamma(
        shape=2.0,
        scale=20.0,
        size=5000
    )
    
    treatment_revenue = rng.gamma(
        shape=2.05,
        scale=20.0,
        size=5000
    )
    
    
    test_statistic, p_value = ttest_ind(
        treatment_revenue,
        control_revenue,
        equal_var=False
    )
    
    
    mean_difference = (
        treatment_revenue.mean()
        - control_revenue.mean()
    )
    
    
    print(
        "Control mean:",
        control_revenue.mean()
    )
    
    print(
        "Treatment mean:",
        treatment_revenue.mean()
    )
    
    print(
        "Mean difference:",
        mean_difference
    )
    
    print(
        "P-value:",
        p_value
    )
    Review requirement: Examine the unit of analysis, skew, missingness, extreme values, repeated observations, and whether the selected statistical method matches the metric and assignment design.

    Run an A/A Test

    An A/A test sends both groups to the same experience while retaining the experiment assignment and measurement pipeline.

    What an A/A Test Can Reveal

    • Broken or biased assignment
    • Unexpected sample-ratio differences
    • Variant-specific logging behavior
    • Inconsistent metric calculation
    • Unstable experiment infrastructure
    • Unexpected false-positive behavior across repeated tests
    Important: An A/A test can validate parts of the experimentation system, but it does not prove that every future treatment experiment will be valid.

    Sample-Ratio Mismatch

    Sample-ratio mismatch occurs when observed variant counts differ unexpectedly from the planned allocation beyond plausible random variation.

    Possible Causes

    • Assignment-service errors
    • Variant-specific crashes or redirects
    • Missing exposure events
    • Eligibility applied after assignment
    • Bot or employee filtering applied inconsistently
    • Cross-device identity differences
    • Data-pipeline loss for one variant
    Mistake Continue interpreting treatment effects after detecting unexplained sample-ratio mismatch.
    Better Approach Pause the decision, investigate assignment and logging, and restore trust in the experiment before interpreting outcome metrics.

    Repeated Peeking and Early Stopping

    Repeatedly checking a conventional fixed-horizon test and stopping as soon as significance appears can increase false-positive risk.

    Invalid Habit Check the p-value every hour and stop immediately when it first falls below the selected threshold.
    Valid Options Follow a fixed-horizon plan, or use a properly designed sequential method with predefined interim analyses and stopping boundaries.
    Operational monitoring: Safety and data-quality guardrails may still be monitored during an experiment. The statistical decision method must distinguish operational protection from repeated opportunistic significance testing.

    Multiple Testing

    Testing many metrics, variants, subgroups, and hypotheses increases the chance that at least one apparently positive result occurs by chance.

    Risk Controls

    • Declare one primary decision metric
    • Limit unnecessary variant and subgroup searches
    • Separate confirmatory analysis from exploration
    • Apply an appropriate multiplicity adjustment where required
    • Report the complete family of tested outcomes
    • Treat unplanned subgroup findings as hypotheses for future validation

    Novelty and Carryover Effects

    Effect Meaning Risk
    Novelty Effect Users react temporarily because an experience is new Short-term lift may not persist
    Learning Effect Users need time to understand a changed experience Early performance may understate later value
    Carryover Effect Previous treatment exposure affects later behavior Switching variants may contaminate comparison
    Seasonal Effect Behavior changes with recurring calendar or business conditions An unrepresentative period may distort conclusions

    Interference and Network Effects

    Standard analysis often assumes that one unit's treatment does not change another unit's outcome. This assumption can fail in social networks, marketplaces, collaborative tools, games, and shared accounts.

    Example Risk Randomize individual sellers to a pricing policy even though their decisions directly alter demand available to untreated sellers.
    Design Consideration Consider whether randomization should occur at a cluster, market, account, network, region, or time level that better contains the treatment's influence.

    A/B Testing Machine Learning Systems

    A model can improve offline accuracy but fail to improve the product outcome. It may increase latency, reduce diversity, change user behavior, or optimize a proxy that does not represent long-term value.

    Layer Example Comparison Possible Metrics
    Model Existing model vs candidate model Business outcome, latency, errors
    Ranking Existing ranking logic vs new objective Engagement, conversion, diversity
    Threshold Existing decision threshold vs proposed threshold Outcome value, review workload, harmful errors
    Interface Prediction hidden vs prediction shown Adoption, decision quality, overrides
    Fallback Default behavior vs alternative fallback Reliability, recovery, user impact
    Recommendation-system caution: A ranking change can alter future training data by changing which items users see and interact with. Monitor exposure, diversity, feedback loops, and delayed outcomes where relevant.

    Recommended Experiment Workflow

    1

    Define the Decision

    State what decision will be made from the result and who owns it.

    2

    Write the Hypothesis

    Define the treatment, population, mechanism, expected outcome, and direction before launch.

    3

    Define Metrics

    Specify the primary metric, guardrails, diagnostic metrics, units, windows, and calculation rules.

    4

    Plan the Experiment

    Choose the experimental unit, allocation, MDE, power, significance level, sample requirement, and stopping rule.

    5

    Validate Instrumentation

    Test assignment, exposure logging, metric pipelines, exclusions, and variant delivery before broad launch.

    6

    Launch Safely

    Increase exposure according to the operational plan while monitoring safety, reliability, and data-quality guardrails.

    7

    Analyze the Result

    Review assignment quality, metric validity, effect estimates, confidence intervals, guardrails, and sensitivity analyses.

    8

    Make and Record the Decision

    Document whether to ship, reject, modify, repeat, or investigate, together with the supporting evidence and limitations.

    9

    Monitor After Rollout

    Confirm that the effect and guardrails remain acceptable after broader deployment.

    Common Experimentation Mistakes

    Mistake Define the success metric after viewing results.
    Better Approach Predefine the primary metric and decision rule.
    Mistake Compare users who voluntarily adopted a feature with users who did not.
    Better Approach Use random assignment when a controlled experiment is feasible and appropriate.
    Mistake Stop when the conventional p-value first becomes favorable.
    Better Approach Follow the predefined fixed-horizon or valid sequential design.
    Mistake Report only relative improvement.
    Better Approach Report baseline, treatment value, absolute change, relative change, and uncertainty.
    Mistake Ignore a negative guardrail because the primary metric improved.
    Better Approach Apply the predefined guardrail policy and assess the complete impact.
    Mistake Treat every event from one user as an independent experimental unit.
    Better Approach Align analysis with assignment and account for repeated or clustered observations.
    Mistake Search many subgroups and present only the most positive result.
    Better Approach Predefine confirmatory subgroups and label unplanned findings as exploratory.

    Experiment Decision Record

    Information What to Record
    Problem Decision, opportunity, and affected population
    Hypothesis Treatment, mechanism, metric, and expected direction
    Variants Exact control and treatment definitions
    Assignment Experimental unit, allocation, persistence, and eligibility
    Metrics Primary, secondary, guardrail, and data-quality definitions
    Statistics MDE, significance level, power, sample plan, and test method
    Quality Checks Assignment, exposure, missingness, and sample-ratio validation
    Results Variant values, absolute effect, relative effect, interval, and p-value
    Decision Ship, reject, modify, repeat, or investigate
    Limitations Uncertainty, threats to validity, and open questions
    Follow-Up Rollout monitoring and future experiments

    Hands-On Practice

    1

    Write an Experiment Hypothesis

    Choose a product or model change and define the population, mechanism, primary outcome, and expected direction.

    2

    Define the Metrics

    Document the numerator, denominator, unit, window, exclusions, and guardrails.

    3

    Choose the Experimental Unit

    Determine whether randomization should occur by user, account, session, store, region, cluster, or time block.

    4

    Plan Sample Size

    Select the baseline, MDE, significance level, power, allocation, and analysis method.

    5

    Analyze Synthetic Results

    Calculate variant metrics, absolute change, relative change, confidence interval, and p-value.

    6

    Review Experiment Quality

    Check sample allocation, missing exposure records, variant delivery, exclusions, and guardrails.

    7

    Write the Decision

    State whether to ship, reject, repeat, modify, or investigate, and explain the evidence and uncertainty.

    Knowledge Check

    1

    What distinguishes an A/B test from an observational comparison?

    Explain the role of controlled random assignment.

    2

    What is an experimental unit?

    Explain how it relates to assignment, independence, and analysis.

    3

    Why should the primary metric be defined before launch?

    Explain how post-result metric selection can create misleading evidence.

    4

    What does a p-value measure?

    Explain its meaning under the null hypothesis without treating it as the probability that the null is true.

    5

    Why is a confidence interval useful?

    Explain how it communicates effect direction, magnitude, and uncertainty.

    6

    What is the minimum detectable effect?

    Explain how it connects business value with sample-size planning.

    7

    Why is repeatedly peeking at a fixed-horizon test dangerous?

    Explain how opportunistic stopping can increase false positives.

    8

    What is sample-ratio mismatch?

    Explain why unexplained allocation differences threaten trust in the experiment.

    9

    Why might an offline model improvement fail online?

    Consider user response, latency, error costs, proxy metrics, system interactions, and changing feedback.

    10

    Why should guardrails be reviewed before shipping?

    Explain why improving one metric does not justify unacceptable harm elsewhere.

    Lesson Summary

    Concept Main Point
    A/B Test Controlled comparison between randomly assigned experiences
    Control Current or baseline experience
    Treatment Proposed changed experience
    Experimental Unit Entity independently assigned to a variant
    Primary Metric Main outcome used for the experiment decision
    Guardrail Metric used to detect unacceptable harm
    Null Hypothesis Represents no treatment difference
    P-Value Measures result extremity under the null and assumptions
    Confidence Interval Communicates effect estimate and uncertainty
    Power Probability of detecting a specified effect when it exists
    MDE Smallest effect the experiment is planned to detect
    Sample-Ratio Mismatch Unexpected difference between planned and observed allocation
    Multiple Testing Testing many outcomes increases false-discovery risk
    Practical Significance Assesses whether the effect is valuable enough to act upon
    Online Model Test Measures real-system impact rather than offline score alone

    Key Takeaway

    A trustworthy A/B test starts with a clear decision, testable hypothesis, valid experimental unit, random assignment, predefined metrics, justified sample plan, and reliable instrumentation. Results should be interpreted using effect sizes, uncertainty, guardrails, practical value, and operational risks. Statistical significance alone is not enough to justify a rollout.

    Get Machine Learning updates by email

    Short, practical lessons and course updates from Rumman Ansari. No spam.