Sign in

Sampling

Sampling and sampling distributions

Ways of choosing a subset of a population so that statistics computed on it say something reliable about the whole, and the distribution those statistics follow.

Overview

A population is every unit you care about. A sample is the part you actually measure. Because the sample is chosen by chance, any statistic computed from it, such as the mean, would come out differently with a different draw. The spread of those possible values is the sampling distribution, and its standard deviation is the standard error. How you draw matters. Simple random sampling gives every subset the same chance. Systematic sampling takes every kk-th unit. Stratified sampling draws separately inside each subgroup so none is missed. Cluster sampling takes whole groups because that is cheaper. The bootstrap redraws with replacement from a sample you already have, to imitate drawing fresh samples.

A short history

Anders Kiaer of Norway argued for representative sampling in place of a full census in the 1890s. Jerzy Neyman's 1934 paper set probability sampling on firm ground and showed the value of stratification. The 1936 United States election made the point publicly: the Literary Digest's huge but biased poll failed, while George Gallup's much smaller quota sample called the result. The central limit theorem explains why sample means follow a nearly normal distribution.

How it works

  1. Define the population of NN units and the statistic you want, for example the mean.
  2. Choose a method: simple, systematic, stratified, cluster or bootstrap, and a sample_size.
  3. Draw the indices: a random subset, a random start then every kk-th unit, a proportional random draw inside each stratum, whole random clusters, or draws with replacement.
  4. Compute the statistic on the chosen units.
  5. Repeat the draw n_samples times and collect the statistic each time. The collection approximates the sampling distribution.
  6. Take its standard deviation as the standard error and compare it with the theoretical value from standard_error_of_mean.

Watch out for

  • Systematic sampling goes wrong when the list has a cycle whose period matches the step, because the sample then hits the same phase every time.
  • Cluster sampling gives a larger standard error than a simple random sample with the same number of units when units inside a cluster resemble each other.
  • A sample drawn by convenience, not by chance, has an unknown bias that no formula here can correct or measure.
  • The formula σ/n\sigma/\sqrt{n} assumes independent draws. Sampling a large share of a finite population without replacement needs the finite population correction or the error is overstated.
  • The bootstrap resamples the sample, not the population, so it cannot repair a sample that is too small or unrepresentative.

Use cases

When to use it

Planning how to collect or subsample data, and whenever you need to know how much a statistic would change from one sample to the next.

In industry

Official statistics
Labour force surveys interview a stratified random sample of households each month to estimate national unemployment.
Auditing
Auditors examine a random sample of transactions and project the error rate to the whole ledger.
Machine learning
Engineers draw stratified samples so that training and test sets keep the class proportions, and subsample very large logs to make analysis affordable.

Choosing it: what must hold

  • A defined target population and a sampling frame that lists or reaches its members.
  • A random mechanism for selection, so that every unit has a known chance of being chosen.
  • A sample size large enough for the precision you need.
  • For stratified sampling, a known variable that splits the population into groups that differ on the outcome.

When to choose something else

IfUse instead
The population is small or already fully recordedA census: analyse every record
No sampling frame exists, as with hidden populationsRespondent driven or other network sampling, with its biases stated
The sampling distribution of your statistic has no formulaThe bootstrap, resampling from the sample itself

Math foundations

  1. The sample mean is unbiased

    E[Xˉ]=μ\mathbb{E}[\bar{X}] = \mu

    Under simple random sampling the sample mean is correct on average: it neither overshoots nor undershoots the population mean in the long run. Single samples still miss, which is what the next formula measures.

  2. Standard error of the mean

    SE(Xˉ)=σnSE(\bar{X}) = \frac{\sigma}{\sqrt{n}}

    The standard deviation of the sampling distribution of the mean, for independent draws. Quadrupling the sample size halves it.

  3. Finite population correction

    SE(Xˉ)=σnN−nN−1SE(\bar{X}) = \frac{\sigma}{\sqrt{n}}\sqrt{\frac{N-n}{N-1}}

    When sampling without replacement, every unit drawn removes some uncertainty about what is left. The extra factor shrinks the standard error, down to zero when n=Nn = N and the whole population has been measured.

  4. Central limit theorem

    Xˉ−μσ/n → d  N(0,1)as n→∞\frac{\bar{X}-\mu}{\sigma/\sqrt{n}} \ \xrightarrow{\ d\ }\ N(0,1) \quad \text{as } n \to \infty

    For independent draws from a population with finite variance, the sampling distribution of the mean approaches a normal shape whatever the population looks like. This is why normal-based intervals and tests work for means.

  5. Proportional allocation and systematic step

    nh=n NhN,k=Nnn_h = n\,\frac{N_h}{N}, \qquad k = \frac{N}{n}

    Stratified sampling gives each stratum a share of the sample equal to its share of the population, rounded so the sizes add to nn. Systematic sampling starts at a random point in the first kk units and then steps by kk.

Symbols

N, nN,\ n
population size and sample size
μ, σ\mu,\ \sigma
population mean and standard deviation
Xˉ\bar{X}
the sample mean, viewed as a random quantity
SESE
standard error: the standard deviation of a statistic across samples
Nh, nhN_h,\ n_h
population size of stratum h and the number sampled from it
kk
step of systematic sampling
→ d \xrightarrow{\ d\ }
converges in distribution

Worked by hand

A population of N=100N = 100 units has standard deviation σ=10\sigma = 10. Draw n=25n = 25 units. The population has three strata of sizes 50, 30 and 20, and a stratified sample of 10 is also planned.

SEwith replacement=1025=2SE_{\text{with replacement}} = \frac{10}{\sqrt{25}} = 2
SEwithout=2×100−25100−1=2×0.870=1.74SE_{\text{without}} = 2 \times \sqrt{\frac{100-25}{100-1}} = 2 \times 0.870 = 1.74
nh=10×(50100, 30100, 20100)=(5, 3, 2)n_h = 10 \times \left(\tfrac{50}{100},\ \tfrac{30}{100},\ \tfrac{20}{100}\right) = (5,\ 3,\ 2)

Sampling a quarter of the population without replacement cuts the standard error from 2 to 1.74. The stratified sample takes 5, 3 and 2 units from the three strata.

Visual example

Loading the example.

Try this

  • Raise n from 30 to 120 and watch the pile of sample means narrow to about half its width.
  • Switch to cluster sampling: the same number of units now gives a much wider pile.
  • Compare simple sampling with and without replacement at n = 120.

Code sample

import numpy as np
from impl import Sampler
from config import SamplingConfig

population = np.random.default_rng(0).exponential(2.0, 5000)
sampler = Sampler(SamplingConfig(method="simple", sample_size=40, n_samples=2000, seed=0))
sample = sampler.sample(population)                      # 40 values
means = sampler.sampling_distribution(population)        # 2000 sample means
print(sample.mean(), means.std(), sampler.standard_error_of_mean(population))
Read the implementation (118 lines)
"""Sampling: drawing a sample from a population, and the sampling distribution of a statistic.

NumPy and the standard library only.
"""
from __future__ import annotations

import math
from typing import Callable

import numpy as np

try:
    from .config import SamplingConfig
except ImportError:  # run from the template's own folder
    from config import SamplingConfig


class Sampler:
    """Draws index sets from a population of N units with the configured technique."""

    def __init__(self, config: SamplingConfig | None = None) -> None:
        self.config = config or SamplingConfig()
        self.rng = np.random.default_rng(self.config.seed)

    def sample_indices(self, population_size: int, groups=None) -> np.ndarray:
        """Indices of the sampled units, as a sorted integer array (bootstrap: in draw order).

        population_size: N, the number of units in the population.
        groups: label of every unit, shape (N,). Required for `stratified` (the labels are the strata)
                and `cluster` (the labels are the clusters), ignored otherwise.

        simple:     every subset of `sample_size` units is equally likely.
        systematic: a random start, then every k-th unit, with k = N / sample_size.
        stratified: a simple random sample inside every stratum, sized in proportion to the stratum
                    (largest-remainder rounding, so the sizes add up to `sample_size`).
        cluster:    `sample_size` whole clusters chosen at random; all their units are taken.
        bootstrap:  `sample_size` draws with replacement.
        """
        c, n_pop = self.config, int(population_size)
        if n_pop < 1:
            raise ValueError("the population is empty")
        if c.method == "bootstrap" or (c.method == "simple" and c.replace):
            return self.rng.integers(0, n_pop, size=c.sample_size)
        if c.method == "cluster":
            return self._cluster(n_pop, groups)
        if c.sample_size > n_pop:
            raise ValueError(f"cannot draw {c.sample_size} units without replacement from {n_pop}")
        if c.method == "simple":
            return np.sort(self.rng.choice(n_pop, size=c.sample_size, replace=False))
        if c.method == "systematic":
            step = n_pop / c.sample_size
            start = self.rng.uniform(0.0, step)
            return np.minimum(np.floor(start + step * np.arange(c.sample_size)).astype(int), n_pop - 1)
        return self._stratified(n_pop, groups)

    def _labels(self, n_pop: int, groups) -> np.ndarray:
        if groups is None:
            raise ValueError(f"method {self.config.method!r} needs the `groups` labels")
        labels = np.asarray(groups)
        if labels.shape != (n_pop,):
            raise ValueError(f"groups must have shape ({n_pop},), got {labels.shape}")
        return labels

    def stratum_sizes(self, groups) -> dict:
        """Proportional allocation: how many units `stratified` draws from each stratum."""
        labels = np.asarray(groups)
        values, counts = np.unique(labels, return_counts=True)
        quota = self.config.sample_size * counts / counts.sum()
        sizes = np.floor(quota).astype(int)
        leftover = self.config.sample_size - int(sizes.sum())
        for i in np.argsort(-(quota - sizes), kind="stable")[:leftover]:  # largest remainders first
            sizes[i] += 1
        return {v.item(): int(s) for v, s in zip(values, sizes)}

    def _stratified(self, n_pop: int, groups) -> np.ndarray:
        labels = self._labels(n_pop, groups)
        chosen = []
        for value, size in self.stratum_sizes(labels).items():
            members = np.flatnonzero(labels == value)
            chosen.append(self.rng.choice(members, size=size, replace=False))
        return np.sort(np.concatenate(chosen))

    def _cluster(self, n_pop: int, groups) -> np.ndarray:
        labels = self._labels(n_pop, groups)
        clusters = np.unique(labels)
        if self.config.sample_size > clusters.size:
            raise ValueError(f"cannot draw {self.config.sample_size} clusters from {clusters.size}")
        picked = self.rng.choice(clusters, size=self.config.sample_size, replace=False)
        return np.flatnonzero(np.isin(labels, picked))

    def sample(self, population, groups=None) -> np.ndarray:
        """The sampled values. population: (N,) or (N, d); returns the chosen rows."""
        population = np.asarray(population)
        return population[self.sample_indices(population.shape[0], groups)]

    def sampling_distribution(self, population, statistic: Callable = np.mean, groups=None) -> np.ndarray:
        """Values of `statistic` over `n_samples` independent samples, shape (n_samples,).

        This is the sampling distribution: how the statistic varies from sample to sample. Its standard
        deviation is the standard error of the statistic.
        """
        population = np.asarray(population)
        return np.array([statistic(self.sample(population, groups)) for _ in range(self.config.n_samples)], dtype=float)

    def standard_error_of_mean(self, population) -> float:
        """Theoretical standard error of the mean of a simple random sample of `sample_size` units.

        sigma / sqrt(n), times the finite population correction sqrt((N - n) / (N - 1)) when sampling
        without replacement. sigma is the population standard deviation (divisor N).
        """
        population = np.asarray(population, dtype=float).ravel()
        n, n_pop = self.config.sample_size, population.size
        se = float(population.std()) / math.sqrt(n)
        if self.config.method == "simple" and not self.config.replace:
            if n > n_pop:
                raise ValueError("sample_size exceeds the population size")
            se *= math.sqrt((n_pop - n) / (n_pop - 1)) if n_pop > 1 else 0.0
        return se
Repository
Not published yet
Needs
Python 3.10 and NumPy
Tests
10, run with python3 -m unittest -v

Practice

Build a skewed population of 1000 values, for example exponential. With Sampler(SamplingConfig(sample_size=25)) call sampling_distribution(population) and compare its standard deviation with standard_error_of_mean(population). Plot a histogram of the result. Then add a groups array and compare method="stratified" with method="cluster".

Check on learning

  1. The population is strongly skewed, yet the histogram of sample means looks close to a bell curve at n=25n = 25. Why, and would the same happen for the sample maximum?
    A way to think about it

    The central limit theorem is about sums and averages. Ask whether the maximum is built by adding many small independent contributions.

  2. When does stratified sampling give a smaller standard error than simple random sampling of the same size, and when does it give no gain?
    A way to think about it

    Split the population variance into variation between strata and variation inside them. Proportional stratification removes one of the two from the error.

  3. Daily sales are listed in date order and you sample every 7th day. What could go wrong, and how would the simple method avoid it?
    A way to think about it

    Think about which weekday every sampled unit shares, and whether sales depend on the weekday.

  4. A bootstrap sample of size nn drawn from a sample of size nn leaves out some original values. Roughly what share, and does that make the bootstrap wasteful?
    A way to think about it

    The chance that one value is missed in a single draw is 1−1/n1 - 1/n. Raise it to the power nn and compare with e−1e^{-1}.