Artificial Intelligence • Mathematical Foundations • 23 min read

Descriptive and Inferential Statistics

An AI model is developed and tested using data, but the data available to its developers rarely describe every situation the model will encounter. A dataset may contain a few thousand examples while the deployed system will process millions of future inputs. Understanding what the observed data show and what can reasonably be concluded beyond them requires statistics.

Statistics is the discipline concerned with collecting, organizing, analyzing, and interpreting data, including the uncertainty involved in drawing conclusions. Two complementary branches are especially important:

  • Descriptive statistics organizes and summarizes observed data using numbers, tables, and visualizations.
  • Inferential statistics uses sample data, together with assumptions about how the data were obtained, to estimate population characteristics or evaluate hypotheses.

These methods support data preparation, machine-learning evaluation, and experiments involving AI systems. They build on the concepts of uncertainty introduced in Probability and Bayes’ Theorem.

Start with a small dataset

Suppose five students need 8, 9, 10, 11, and 32 minutes to finish a programming exercise. You can calculate the mean (14 minutes), but that single number hides something important: four students finish near 10 minutes while one takes much longer. The median, 10 minutes, describes the typical observation differently.

This is what descriptive statistics does: it helps us see the shape of data rather than relying on one number. Measures of center, spread, and distribution answer different questions about the same observations.

Now imagine you want to know how long all students at your university would take. Those five observations cannot tell you that exactly. They may not represent the larger group. Inferential statistics deals with the next step: estimating properties of a population from a sample, while acknowledging sampling uncertainty and the assumptions involved.

Keep these two questions separate throughout the article: What did we observe? and What can we reasonably infer beyond those observations? AI development depends on both. We describe training data, then use carefully designed evaluations to estimate how a model may behave on future inputs.

Descriptive statistics versus inferential statistics

Suppose an AI-powered learning platform records the time students spend completing an exercise. From a dataset of 500 recorded sessions, the platform can calculate the median completion time and identify unusually long sessions. Those calculations describe the 500 observations: they are descriptive statistics.

If the platform wants to estimate the average completion time for all future students, the observed 500 sessions are only a sample of the larger population of interest. Estimating that population quantity requires inferential reasoning about sampling, variability, and possible bias.

QuestionStatistical approachExample
What is in the dataset?DescriptiveThe median observed completion time is 12 minutes.
How much do observations vary?DescriptiveCompletion times have a wide spread.
What might be true of the larger population?InferentialEstimate the population mean with an uncertainty interval.
Could an observed difference reflect sampling variation?InferentialCompare two teaching methods with a statistical test.
Does a new feature cause an improvement?Study design and inferenceUse an appropriately randomized experiment, then analyze its results.

An inferential result cannot repair poor data collection. A precise calculation based on an unrepresentative dataset may still lead to a misleading conclusion.

Populations, samples, parameters, and statistics

A population is the complete set of units about which a study aims to make a conclusion. A sample is a subset of units selected or observed from that population.

A population does not always mean every person in a country. It might mean all transactions processed next month, all images captured by a particular device, or all requests received by a deployed model during a defined period.

TermMeaningExample
PopulationAll units in the defined group of interestAll requests that a deployed chatbot will receive next week
SampleObserved subset of the population1,000 selected requests
ParameterNumerical property of the populationTrue average response time over all requests
StatisticNumerical property calculated from the sampleAverage response time of the 1,000 selected requests
EstimatorA rule for calculating an estimate from sample dataThe sample mean as an estimator of the population mean
EstimateThe numerical result produced by an estimatorA sample mean of 0.84 seconds

A sample statistic can be used to estimate a population parameter. Its accuracy depends on factors such as how observations were collected, sample size, natural variation, and whether the assumptions behind the estimation method are appropriate.

Common mathematical notation

For numerical observations x1,x2,…,xnx_1,x_2,\ldots,x_n:

  • nn is the number of sample observations.
  • μ\mu (mu) commonly represents the population mean.
  • xˉ\bar{x} (x-bar) represents the sample mean.
  • σ2\sigma^2 represents the population variance.
  • s2s^2 represents the usual sample variance.
  • σ\sigma and ss are the corresponding standard deviations.

The symbols distinguish the property we want to know from the quantity we can calculate directly.

Diagram showing a population, a selected sample, a calculated sample statistic, and an estimate of a population parameter with uncertainty.
Descriptive statistics are computed from the sample. Inferential statistics uses a statistical model and study assumptions to draw conclusions about the population.

Understanding the kinds of data

Before selecting a statistic, determine what the values represent.

Data typeDescriptionExamplesTypical description
Numerical, discreteCountable numerical valuesNumber of clicks, error countsCounts, mean, median
Numerical, continuousMeasurements on a numerical scaleLatency, temperatureMean, median, spread
Categorical, nominalCategories with no intrinsic orderingDevice type, predicted classFrequency counts, proportions
Categorical, ordinalOrdered categories without fixed numerical spacingLow, medium, high riskCounts, proportions, median category where appropriate

A model’s numeric class labels may still be categorical. For example, labels 0, 1, and 2 for cat, dog, and bird do not imply that a dog is numerically halfway between a cat and a bird. Calculating a mean of those labels would generally not be meaningful.

Measures of central tendency

A measure of central tendency describes a typical or central value in numerical data. Three common measures are the mean, median, and mode.

Mean

The arithmetic mean is the sum of all observations divided by their number:

xˉ=1n∑i=1nxi\bar{x}=\frac{1}{n}\sum_{i=1}^{n}x_i

Consider five task completion times, in minutes:

2,  3,  3,  4,  182,\;3,\;3,\;4,\;18

Their mean is:

xˉ=2+3+3+4+185=6\bar{x}=\frac{2+3+3+4+18}{5}=6

The mean accounts for every value, but it can be strongly affected by unusually large or small observations.

Median

The median is the middle value after observations are sorted. If there are two middle values, their arithmetic mean is commonly used for numerical data.

For the same dataset, the median is 33. It better reflects the typical short completion time because the single 18-minute session has less influence on the median than on the mean.

Mode

The mode is the most frequently occurring value or category. Here, the mode is 33, which appears twice. A dataset can have multiple modes or no uniquely most frequent value.

MeasureResult for 2,3,3,4,182,3,3,4,18Useful when
Mean66All numerical values should contribute to the center
Median33Data are skewed or contain outliers
Mode33Identifying common values or categories

Important: There is no universally best measure of center. A useful statistic must match the data type, distribution, and question being asked.

Measures of variability

Two datasets can have the same average and very different patterns. Measures of variability describe how dispersed the observations are.

Range

The range is the maximum value minus the minimum:

Range=max⁡(xi)−min⁡(xi)\text{Range}=\max(x_i)-\min(x_i)

For 2,3,3,4,182,3,3,4,18, the range is 18−2=1618-2=16 minutes. It is easy to calculate but depends entirely on two extreme observations.

Variance and standard deviation

Variance measures average squared deviation from the mean. For a population of NN values, the population variance is:

σ2=1N∑i=1N(xi−μ)2\sigma^2=\frac{1}{N}\sum_{i=1}^{N}(x_i-\mu)^2

For a sample, the usual sample variance is:

s2=1n−1∑i=1n(xi−xˉ)2,n>1s^2=\frac{1}{n-1}\sum_{i=1}^{n}(x_i-\bar{x})^2,\qquad n>1

The denominator n−1n-1 gives an unbiased estimator of population variance when observations are independent and identically distributed with finite variance. It also reflects that one degree of freedom was used to estimate the mean. It is not simply a rule that all datasets must use n−1n-1.

For the five completion times above, the deviations from the mean 66 are −4,−3,−3,−2,12-4,-3,-3,-2,12. Their squared deviations add to 182182, so:

s2=1824=45.5 minutes2s^2=\frac{182}{4}=45.5\ \text{minutes}^2

The standard deviation is the square root of variance:

s=s2=45.5≈6.75 minutess=\sqrt{s^2}=\sqrt{45.5}\approx6.75\ \text{minutes}

Unlike variance, standard deviation has the same units as the observations. Both measures are sensitive to extreme values.

Quartiles and interquartile range

Quartiles describe the positions of observations in an ordered dataset. The interquartile range (IQR) is the difference between the third and first quartiles:

IQR⁡=Q3−Q1\operatorname{IQR}=Q_3-Q_1

It describes the spread of the middle half of the data and is often less sensitive to extremes than the full range or standard deviation. Software packages can use different conventions for calculating quartiles from small datasets, so an analysis should use a consistent definition.

StatisticDescribesSensitive to outliers?
RangeFull observed spanVery
VarianceMean squared deviationYes
Standard deviationTypical scale of deviation around the meanYes
Interquartile rangeSpread of the middle halfLess sensitive

Distributions and data visualization

A distribution describes which values occur and how frequently, or how probability is assigned across possible values. Studying its shape can reveal information that a single average hides.

Common characteristics include:

  • Symmetry: Whether the left and right sides have similar shapes.
  • Skewness: Whether observations extend farther toward one side.
  • Modality: Whether the data have one prominent peak, several peaks, or no clear peak.
  • Outliers: Observations that are unusually far from the main pattern; they may represent genuine cases or measurement problems.

Useful displays include histograms for numerical measurements, box plots for center and spread, bar charts for categories, and scatter plots for relationships between two numerical variables.

For instance, a histogram of inference latency might show most responses arriving quickly and a long right tail of slow requests. Reporting only the mean would hide the experience of users who encounter those delays.

Describing relationships: correlation and causation

Correlation measures the strength and direction of association between variables. The commonly used Pearson correlation coefficient, rr, measures their linear association in a sample and ranges from −1-1 to 11 when defined:

−1≤r≤1-1\leq r\leq1
  • r>0r>0: a positive linear association.
  • r<0r<0: a negative linear association.
  • r≈0r\approx0: little linear association, though a nonlinear relationship may still exist.
  • ∣r∣|r| close to 11: a strong linear association, not necessarily a causal relationship.

Correlation does not establish causation. If students who practice more tend to score higher, practice might contribute to higher scores, but prior knowledge, motivation, and other variables could influence both.

A confounder is a factor associated with both an explanatory variable and an outcome that can distort the apparent relationship between them. Establishing causal effects generally needs careful study design and assumptions, often supported by randomized experiments where feasible.

Sampling: how data are selected

Sampling is the process of selecting observations from a population. Sampling design determines how confidently results can be generalized beyond the collected data.

ApproachBasic ideaMain consideration
Simple random samplingSelect units by a known random processEach unit has an equal selection probability under the standard design
Stratified samplingDivide into relevant groups and sample within eachHelps represent important subgroups
Cluster samplingSelect groups or clusters of unitsInference must account for similarity within clusters
Convenience samplingUse units that are easy to accessOften produces selection bias

Sampling bias occurs when the selection process systematically favors some units over others, potentially making the sample unrepresentative of the intended population. Increasing the size of a biased sample does not automatically eliminate that bias.

For example, evaluating a voice-recognition model only on audio recorded in quiet rooms may overstate its performance for users in noisy public places. The missing environmental conditions create a gap between the evaluation sample and the actual deployment population.

Other sources of misleading data include nonresponse, measurement error, incorrect labels, duplicate records, and changes in the population over time.

Random sampling versus random assignment

These ideas serve different goals:

  • Random sampling concerns which units enter a study; it can support generalization to a population.
  • Random assignment concerns which treatment or version a participant receives; it can help identify causal effects by balancing potential confounders between experimental groups.

A study can use one, both, or neither. Random assignment alone does not guarantee that its participants represent every intended user.

Sampling variability and standard error

Even with a sound sampling design, two samples from the same population will generally give different statistics. This variation is called sampling variability.

The sampling distribution of an estimator is the distribution of the values it would produce across repeated samples under a specified sampling process.

The standard error (SE) is the standard deviation of that sampling distribution. For the mean of nn independent, identically distributed observations with population standard deviation σ\sigma:

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

When σ\sigma is unknown, a common estimate is:

SE⁡^(Xˉ)=sn\widehat{\operatorname{SE}}(\bar{X})=\frac{s}{\sqrt{n}}

This shows an important difference:

  • Standard deviation describes variation among individual observations.
  • Standard error describes uncertainty in an estimate arising from the sampling process.

For a sample mean, doubling the sample size reduces the standard error by a factor of 1/21/\sqrt{2} under the stated assumptions, not by a factor of two. Dependent observations, clustering, or systematic bias require more careful analysis.

Law of large numbers and central limit theorem

The law of large numbers says, under suitable conditions, that sample averages converge toward their expected value as more observations are collected.

The central limit theorem says that the distribution of suitably standardized averages approaches a normal distribution for large samples under conditions such as independent, identically distributed observations with finite variance. This helps explain why normal-based methods are common in statistical inference.

Neither principle says that the original data must be normally distributed. Neither guarantees that a large sample is unbiased, nor does a fixed rule such as "n≥30n\geq30" make every inference automatically valid.

Estimation and confidence intervals

A point estimate gives one numerical estimate of a population parameter. The sample mean xˉ\bar{x}, for example, estimates the population mean μ\mu.

An interval estimate provides a range calculated from the data. A confidence interval is constructed using a procedure designed to contain the fixed population parameter at a specified frequency across repeated samples, assuming the model and sampling conditions hold.

A 95% confidence-interval procedure, for instance, has a long-run coverage rate of 95% under its assumptions. For a particular computed interval, the usual frequentist interpretation is not that the fixed parameter has a 95% probability of falling inside the interval.

Worked example: a confidence interval for the mean

Suppose an independent random sample of 2525 observations gives:

  • Sample mean: xˉ=80\bar{x}=80.
  • Sample standard deviation: s=10s=10.
  • Sample size: n=25n=25.

The estimated standard error is:

SE⁡^=1025=2\widehat{\operatorname{SE}}=\frac{10}{\sqrt{25}}=2

When individual measurements are approximately normally distributed and the population standard deviation is unknown, the conventional two-sided 95% confidence interval for the mean uses a Student tt critical value with n−1=24n-1=24 degrees of freedom:

xˉ±t0.975,24sn\bar{x}\pm t_{0.975,24}\frac{s}{\sqrt{n}}

Using t0.975,24≈2.064t_{0.975,24}\approx2.064:

80±2.064(2)=80±4.12880\pm 2.064(2)=80\pm4.128

The resulting interval is approximately:

[75.87, 84.13]\boxed{[75.87,\ 84.13]}

This is an illustration of the method, not a guarantee of correct coverage for every dataset. Random selection, independence, the distribution of the data, and other assumptions determine whether the interval is appropriate.

Confidence intervals are not prediction intervals

A confidence interval for a population mean estimates uncertainty about that mean. A prediction interval aims to cover a future individual observation. Because individuals vary around the population mean, prediction intervals are generally wider than confidence intervals for the mean under comparable conditions.

This distinction matters in AI: uncertainty in an estimated average accuracy is different from uncertainty about whether one new prediction will be correct.

Hypothesis testing

Hypothesis testing evaluates how compatible observed data are with a specified statistical claim or model.

A conventional test begins with two statements:

  • Null hypothesis (H0H_0): The statistical claim evaluated by the test, commonly no difference or no effect.
  • Alternative hypothesis (H1H_1 or HaH_a): A competing claim, such as a difference or effect.

For example, suppose a model-serving change is being tested for its effect on average latency. The hypotheses might be:

H0:μ=75,H1:μ≠75H_0:\mu=75,\qquad H_1:\mu\neq75

Here, μ\mu represents the population mean latency under the conditions being studied. A two-sided alternative is used because the mean could differ in either direction.

Test statistic and p-value

A test statistic summarizes how far the observed data depart from what the null hypothesis predicts. For a conventional one-sample tt-test:

t=xˉ−μ0s/nt=\frac{\bar{x}-\mu_0}{s/\sqrt{n}}

Using the sample above and a null value μ0=75\mu_0=75:

t=80−7510/25=2.5t=\frac{80-75}{10/\sqrt{25}}=2.5

For a two-sided test with 2424 degrees of freedom, this gives a p-value of approximately 0.0200.020.

A p-value measures how unusual the observed test statistic, or one more extreme according to the test definition, would be if the null model and the test assumptions were true. It does not give the probability that H0H_0 is true.

Significance levels and errors

A significance level, commonly written α\alpha, is a prespecified threshold for a test’s false-rejection rate under the null model. If α=0.05\alpha=0.05 and the calculated p-value is approximately 0.0200.020, a conventional decision rule rejects H0H_0.

ConceptMeaning
Type I errorRejecting a true null hypothesis
Type II errorFailing to reject a false null hypothesis
Significance level α\alphaIntended long-run probability of a Type I error under the specified test assumptions
Statistical powerProbability of rejecting the null under a specified alternative when it is false
Effect sizeMagnitude of the difference or relationship of interest

Rejecting the null is not proof that the alternative is true, and failing to reject the null does not establish that it is true. Results must be interpreted together with estimated effect sizes, uncertainty intervals, study design, and practical consequences.

Statistical significance versus practical significance

With enough observations, even a very small performance difference can produce a low p-value. A reduction of 0.1 milliseconds in model latency might be statistically detectable but irrelevant to users. Conversely, a potentially important improvement might not reach a conventional threshold in a small study.

For an AI product, consider both how certain the evidence is and how valuable the measured difference would be. A decision should not rely on crossing a single threshold.

Calculating statistics with Python

Python libraries make it straightforward to compute descriptive statistics and common inferential procedures. The following code uses NumPy and SciPy; the example summaries match the calculations in this article.

import numpy as np
from scipy import stats

# Descriptive statistics for five observations.
times = np.array([2, 3, 3, 4, 18], dtype=float)

print(f"Mean: {np.mean(times):.2f}")
print(f"Median: {np.median(times):.2f}")
print(f"Sample variance: {np.var(times, ddof=1):.2f}")
print(f"Sample standard deviation: {np.std(times, ddof=1):.2f}")

# Inferential example using the sample's sufficient summaries.
mean = 80.0
sample_std = 10.0
n = 25
null_mean = 75.0

degrees_of_freedom = n - 1
standard_error = sample_std / np.sqrt(n)
t_critical = stats.t.ppf(0.975, df=degrees_of_freedom)

ci_lower = mean - t_critical * standard_error
ci_upper = mean + t_critical * standard_error

t_statistic = (mean - null_mean) / standard_error
p_value = 2 * stats.t.sf(abs(t_statistic), df=degrees_of_freedom)

print(f"95% CI: [{ci_lower:.2f}, {ci_upper:.2f}]")
print(f"t statistic: {t_statistic:.2f}")
print(f"Two-sided p-value: {p_value:.3f}")

Expected output (rounded):

Mean: 6.00
Median: 3.00
Sample variance: 45.50
Sample standard deviation: 6.75
95% CI: [75.87, 84.13]
t statistic: 2.50
Two-sided p-value: 0.020

The code demonstrates calculations, not whether a real dataset satisfies their assumptions. In practical analysis, inspect the data and study design before choosing a procedure. The ddof=1 argument requests division by n−1n-1 for sample variance and sample standard deviation.

Why statistics matters in artificial intelligence

Statistics appears throughout the machine-learning lifecycle:

AI activityStatistical questionRelevant concepts
Dataset explorationWhat patterns and outliers are present?Distributions, medians, variance, visualizations
Data collectionWill the observations represent actual users?Sampling, selection bias, measurement error
Feature analysisWhich variables are associated with the target?Correlation, confounding, variability
Model evaluationIs performance reliable beyond the test sample?Estimates, confidence intervals, sample size
Comparing modelsIs the observed performance difference meaningful?Paired comparisons, hypothesis testing, effect size
Production monitoringHave input or outcome patterns changed?Distribution comparisons, uncertainty, drift
A/B experimentsDid a changed product feature cause an improvement?Random assignment, effect estimation, statistical power

The test dataset is still a sample

A model’s test accuracy is calculated on a finite collection of examples. It is a sample performance estimate, not a guarantee that the same accuracy will hold for every future input. Its credibility depends on representative test data, independence where needed, and a stable relationship between evaluation conditions and deployment.

Comparing many models repeatedly on the same test set can lead to overoptimistic results because test-set information influences model development. Separate training, validation, and test sets help manage that problem.

Performance uncertainty needs a suitable method

Not all AI metrics follow the same sampling distribution. A confidence interval for a classification proportion is different from one for a mean latency; correlated or grouped observations also require special treatment. Time-series forecasting, repeated measurements from the same user, and multiple images from the same subject cannot always be analyzed as if each observation were independent.

The purpose of statistical inference is not to decorate every metric with a p-value. It is to represent what the evidence can and cannot justify.

Frequent mistakes to avoid

  1. Reporting only the mean. A skewed latency distribution can conceal severe delays. Examine the median, spread, and shape as well.
  2. Confusing a sample statistic with a population fact. A calculated mean is exact for the observed sample, but uncertain as an estimate of a wider population.
  3. Assuming a large dataset is representative. A million biased observations can still give misleading conclusions.
  4. Treating correlation as proof of causation. Confounders and selection effects can explain an apparent relationship.
  5. Confusing standard deviation with standard error. One describes individual variation; the other describes estimator uncertainty.
  6. Reading a 95% confidence interval as a 95% probability statement about the fixed parameter. The usual frequentist coverage interpretation concerns the procedure across repeated samples.
  7. Interpreting a p-value as the probability a hypothesis is true. It is computed conditionally on a statistical model, including the null hypothesis.
  8. Equating statistical significance with usefulness. Practical impact depends on the size, context, and cost of an effect.
  9. Ignoring multiple comparisons. Testing many hypotheses increases the opportunity for chance findings; appropriate methods or study designs may be necessary.
  10. Using inferential formulas without checking assumptions. Dependence, sampling bias, outliers, and changes in the data-generating process can undermine a result.

Practice problems

  1. A dataset contains 5,6,7,8,245,6,7,8,24. Calculate its mean and median. Which measure is more affected by the unusually high value?
  2. Explain why the mean of a random sample can differ from the population mean even when sampling is unbiased.
  3. A study reports a sample standard deviation of 1212 and has n=36n=36 independent observations. Estimate the standard error of the sample mean.
  4. A reported p-value is 0.030.03. Does this mean the null hypothesis has a 3% probability of being true? Explain.
  5. A model is evaluated on images from one hospital, but will be deployed across many hospitals. Identify a possible source of bias.
  6. What is the difference between random sampling and random assignment in a model-related experiment?
Show worked answers
  1. Mean =(5+6+7+8+24)/5=10=(5+6+7+8+24)/5=10. Median =7=7. The mean is more affected by the high value.
  2. Random sampling reduces systematic selection bias under its design, but which observations happen to be selected still varies. The sample mean therefore varies across samples.
  3. Estimated standard error =s/n=12/36=2=s/\sqrt{n}=12/\sqrt{36}=2.
  4. No. A p-value describes how unusual the test result would be under the specified null model and assumptions. It does not assign a probability to the truth of the null hypothesis.
  5. The hospital’s patients, imaging equipment, clinical workflow, or labeling practices may differ from those at deployment sites, making the evaluation sample unrepresentative.
  6. Random sampling determines who enters a study and supports generalization; random assignment determines which treatment or product version participants receive and can support causal comparisons.

References and further reading

Related articles in

Image preview

Fit