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.
| Question | Statistical approach | Example |
|---|---|---|
| What is in the dataset? | Descriptive | The median observed completion time is 12 minutes. |
| How much do observations vary? | Descriptive | Completion times have a wide spread. |
| What might be true of the larger population? | Inferential | Estimate the population mean with an uncertainty interval. |
| Could an observed difference reflect sampling variation? | Inferential | Compare two teaching methods with a statistical test. |
| Does a new feature cause an improvement? | Study design and inference | Use 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.
| Term | Meaning | Example |
|---|---|---|
| Population | All units in the defined group of interest | All requests that a deployed chatbot will receive next week |
| Sample | Observed subset of the population | 1,000 selected requests |
| Parameter | Numerical property of the population | True average response time over all requests |
| Statistic | Numerical property calculated from the sample | Average response time of the 1,000 selected requests |
| Estimator | A rule for calculating an estimate from sample data | The sample mean as an estimator of the population mean |
| Estimate | The numerical result produced by an estimator | A 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 :
- is the number of sample observations.
- (mu) commonly represents the population mean.
- (x-bar) represents the sample mean.
- represents the population variance.
- represents the usual sample variance.
- and are the corresponding standard deviations.
The symbols distinguish the property we want to know from the quantity we can calculate directly.
Understanding the kinds of data
Before selecting a statistic, determine what the values represent.
| Data type | Description | Examples | Typical description |
|---|---|---|---|
| Numerical, discrete | Countable numerical values | Number of clicks, error counts | Counts, mean, median |
| Numerical, continuous | Measurements on a numerical scale | Latency, temperature | Mean, median, spread |
| Categorical, nominal | Categories with no intrinsic ordering | Device type, predicted class | Frequency counts, proportions |
| Categorical, ordinal | Ordered categories without fixed numerical spacing | Low, medium, high risk | Counts, 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:
Consider five task completion times, in minutes:
Their mean is:
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 . 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 , which appears twice. A dataset can have multiple modes or no uniquely most frequent value.
| Measure | Result for | Useful when |
|---|---|---|
| Mean | All numerical values should contribute to the center | |
| Median | Data are skewed or contain outliers | |
| Mode | Identifying 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:
For , the range is 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 values, the population variance is:
For a sample, the usual sample variance is:
The denominator 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 .
For the five completion times above, the deviations from the mean are . Their squared deviations add to , so:
The standard deviation is the square root of variance:
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:
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.
| Statistic | Describes | Sensitive to outliers? |
|---|---|---|
| Range | Full observed span | Very |
| Variance | Mean squared deviation | Yes |
| Standard deviation | Typical scale of deviation around the mean | Yes |
| Interquartile range | Spread of the middle half | Less 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, , measures their linear association in a sample and ranges from to when defined:
- : a positive linear association.
- : a negative linear association.
- : little linear association, though a nonlinear relationship may still exist.
- close to : 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.
| Approach | Basic idea | Main consideration |
|---|---|---|
| Simple random sampling | Select units by a known random process | Each unit has an equal selection probability under the standard design |
| Stratified sampling | Divide into relevant groups and sample within each | Helps represent important subgroups |
| Cluster sampling | Select groups or clusters of units | Inference must account for similarity within clusters |
| Convenience sampling | Use units that are easy to access | Often 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 independent, identically distributed observations with population standard deviation :
When is unknown, a common estimate is:
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 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 "" make every inference automatically valid.
Estimation and confidence intervals
A point estimate gives one numerical estimate of a population parameter. The sample mean , for example, estimates the population mean .
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 observations gives:
- Sample mean: .
- Sample standard deviation: .
- Sample size: .
The estimated standard error is:
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 critical value with degrees of freedom:
Using :
The resulting interval is approximately:
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 (): The statistical claim evaluated by the test, commonly no difference or no effect.
- Alternative hypothesis ( or ): 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:
Here, 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 -test:
Using the sample above and a null value :
For a two-sided test with degrees of freedom, this gives a p-value of approximately .
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 is true.
Significance levels and errors
A significance level, commonly written , is a prespecified threshold for a test’s false-rejection rate under the null model. If and the calculated p-value is approximately , a conventional decision rule rejects .
| Concept | Meaning |
|---|---|
| Type I error | Rejecting a true null hypothesis |
| Type II error | Failing to reject a false null hypothesis |
| Significance level | Intended long-run probability of a Type I error under the specified test assumptions |
| Statistical power | Probability of rejecting the null under a specified alternative when it is false |
| Effect size | Magnitude 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 for sample variance and sample standard deviation.
Why statistics matters in artificial intelligence
Statistics appears throughout the machine-learning lifecycle:
| AI activity | Statistical question | Relevant concepts |
|---|---|---|
| Dataset exploration | What patterns and outliers are present? | Distributions, medians, variance, visualizations |
| Data collection | Will the observations represent actual users? | Sampling, selection bias, measurement error |
| Feature analysis | Which variables are associated with the target? | Correlation, confounding, variability |
| Model evaluation | Is performance reliable beyond the test sample? | Estimates, confidence intervals, sample size |
| Comparing models | Is the observed performance difference meaningful? | Paired comparisons, hypothesis testing, effect size |
| Production monitoring | Have input or outcome patterns changed? | Distribution comparisons, uncertainty, drift |
| A/B experiments | Did 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
- Reporting only the mean. A skewed latency distribution can conceal severe delays. Examine the median, spread, and shape as well.
- 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.
- Assuming a large dataset is representative. A million biased observations can still give misleading conclusions.
- Treating correlation as proof of causation. Confounders and selection effects can explain an apparent relationship.
- Confusing standard deviation with standard error. One describes individual variation; the other describes estimator uncertainty.
- 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.
- Interpreting a p-value as the probability a hypothesis is true. It is computed conditionally on a statistical model, including the null hypothesis.
- Equating statistical significance with usefulness. Practical impact depends on the size, context, and cost of an effect.
- Ignoring multiple comparisons. Testing many hypotheses increases the opportunity for chance findings; appropriate methods or study designs may be necessary.
- Using inferential formulas without checking assumptions. Dependence, sampling bias, outliers, and changes in the data-generating process can undermine a result.
Practice problems
- A dataset contains . Calculate its mean and median. Which measure is more affected by the unusually high value?
- Explain why the mean of a random sample can differ from the population mean even when sampling is unbiased.
- A study reports a sample standard deviation of and has independent observations. Estimate the standard error of the sample mean.
- A reported p-value is . Does this mean the null hypothesis has a 3% probability of being true? Explain.
- A model is evaluated on images from one hospital, but will be deployed across many hospitals. Identify a possible source of bias.
- What is the difference between random sampling and random assignment in a model-related experiment?
Show worked answers
- Mean . Median . The mean is more affected by the high value.
- 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.
- Estimated standard error .
- 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.
- The hospital’s patients, imaging equipment, clinical workflow, or labeling practices may differ from those at deployment sites, making the evaluation sample unrepresentative.
- 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.
Related concepts
- Probability and Bayes’ Theorem introduces probability distributions, conditional probabilities, and uncertainty.
- Vector and Matrix Operations explains the numerical representations used in data analysis.
- Entropy, Cross-Entropy, and KL Divergence connects probability distributions to loss functions and information measures.
- Data Types and Data Collection for AI develops data collection and dataset characteristics.
- Data Splitting, Labeling, and Leakage explains how training and evaluation data should be separated.
- Evaluating Machine Learning Models applies statistics to classification and regression metrics.
- Monitoring, Data Drift, and Concept Drift explains changing data distributions in production.
- AI Knowledge Map places statistics within the complete AI learning path.
References and further reading
- OpenIntro Statistics — accessible coverage of descriptive statistics, sampling, confidence intervals, inference, and experiments.
- NIST/SEMATECH Engineering Statistics Handbook — statistical methods, assumptions, and engineering applications.
- American Statistical Association: Statement on p-Values — interpretation and common misuses of statistical significance.
- SciPy Statistical Functions — Python methods for probability distributions and statistical inference.
- NumPy Statistical Functions — numerical computation of descriptive statistics.
Related articles in
- AI Agents and Tool-Using Workflows — Learn agent goals, tool invocation, planning, state, permissions, and how to evaluate multi-step AI workflows.
- AI Development Tools: Git, Jupyter, and APIs — Learn how Git, Jupyter notebooks, Python environments, and APIs fit together in reproducible, secure artificial intelligence workflows.
- How AI Is Changing Theoretical Computer Science — AI is beginning to help researchers explore algorithms, mathematical structures, and formal proofs. Here is what it can do, what still needs human judgment, and why verification matters.