Data science is often associated with predictions, statistics, dashboards, and machine learning models. However, one important question is sometimes overlooked: How certain are we that our results are correct?
Imagine that you build a machine learning model to predict monthly sales for an online business. Your model forecasts revenue of ₦15 million for December.
That sounds useful, but should the business expect exactly ₦15 million?
Probably not.
The actual revenue could be ₦13 million, ₦16 million, or even ₦18 million depending on customer behaviour, market conditions, pricing changes, and other factors.
A prediction without an indication of uncertainty can create a misleading impression of precision.
This is where uncertainty quantification becomes important.
Uncertainty quantification helps data scientists measure, communicate, and interpret how much confidence they should place in data, statistical estimates, and model predictions. It is particularly useful in forecasting, risk analysis, scientific research, financial modelling, healthcare, and machine learning.
In this guide, you will learn what uncertainty means in data science, the different types of uncertainty, how to measure it using statistical techniques, and how to implement practical uncertainty quantification methods with Python.
1. What Is Uncertainty Quantification in Data Science?
Uncertainty quantification (UQ) is the process of measuring and describing the uncertainty associated with data, statistical estimates, predictions, and analytical results.
It helps answer questions such as:
- How reliable is this prediction?
- How much could the actual value differ from the forecast?
- How confident are we in this statistical estimate?
- Does the available dataset provide enough evidence?
- How sensitive are the results to changes in the input data?
- What is the probability that a particular outcome will occur?
Consider a data analyst estimating the average monthly spending of customers.
A sample of 500 customers produces an estimated average spending of ₦45,000.
However, this estimate is based on a sample rather than every customer in the population. Another sample might produce ₦43,500 or ₦46,200.
Uncertainty quantification helps describe how much the estimate could vary and how confidently it represents the wider population.
Instead of presenting only a single number, you can provide additional information about its reliability.
For example:
Estimated average monthly spending: ₦45,000
95% confidence interval: ₦42,800–₦47,200
The interval provides more context than the estimate alone. Its correct interpretation depends on the statistical method and assumptions used to construct it.
Uncertainty quantification does not eliminate uncertainty. It makes uncertainty visible enough to support better decisions.
2. Understanding the Different Types of Uncertainty
Before measuring uncertainty, it is important to understand where it comes from.
In data science, uncertainty is commonly divided into two broad categories: aleatoric uncertainty and epistemic uncertainty.
2.1 Aleatoric Uncertainty
Aleatoric uncertainty is the natural randomness or variability present in a system.
It exists because real-world processes are not always predictable, even when we have a good understanding of the underlying system.
For example, an e-commerce company may observe that customers with similar purchasing histories sometimes spend different amounts during the same promotional period.
This variation may result from:
- Individual preferences.
- Random purchasing behaviour.
- Changes in demand.
- Unpredictable external events.
- Natural variation in the process being studied.
More training data does not necessarily eliminate aleatoric uncertainty.
For example, collecting millions of customer transactions may help estimate spending patterns more accurately, but individual purchasing behaviour will still contain natural variation.
2.2 Epistemic Uncertainty
Epistemic uncertainty comes from a lack of knowledge about the system being studied.
It can arise because the dataset is too small, the model is too simple, important variables are missing, or the training data does not represent the environment where the model will be used.
Consider a machine learning model trained to predict house prices in Lagos.
If the model has never encountered properties in a newly developed neighbourhood, its predictions for that area may be unreliable.
The uncertainty exists partly because the model has insufficient knowledge of that part of the housing market.
Unlike natural randomness, epistemic uncertainty can often be reduced by:
- Collecting more representative data.
- Improving feature selection.
- Using a more suitable model.
- Incorporating relevant domain knowledge.
- Improving data quality.
- Expanding the training dataset.
Aleatoric vs Epistemic Uncertainty
| Feature | Aleatoric uncertainty | Epistemic uncertainty |
|---|---|---|
| Main source | Natural randomness | Limited knowledge |
| Can more data eliminate it? | Not necessarily | Often helps |
| Example | Random customer spending | Insufficient housing data |
| Main response | Model the variability | Improve knowledge and data |
| Common application | Forecasting | Model reliability |
Understanding the difference matters because the solution depends on the source of uncertainty.
Collecting more data may help with epistemic uncertainty, but it will not necessarily eliminate the natural randomness in customer behaviour.
3. Why Uncertainty Quantification Matters
A prediction without uncertainty information can lead to poor decisions.
Businesses, researchers, and data scientists need to understand not only what a model predicts but also how reliable that prediction is.
Here are some important reasons to quantify uncertainty.
3.1 Better Decision-Making
Business decisions often involve financial risks.
For example, a retailer planning inventory for the festive season needs more than a single sales forecast.
Suppose the model predicts that demand will reach 10,000 units.
Knowing whether demand is likely to fall between 9,000 and 11,000 units or between 5,000 and 15,000 units can significantly influence purchasing decisions.
The second forecast has much greater uncertainty and may require a different inventory strategy.
3.2 Improved Risk Management
Uncertainty quantification helps organisations understand the range of possible outcomes.
Banks can use uncertainty estimates when assessing financial risks. Healthcare researchers can evaluate the reliability of estimated treatment effects. Supply chain managers can plan for fluctuations in demand.
It does not remove risk, but it helps decision-makers understand it.
3.3 More Reliable Machine Learning Models
A model may produce accurate predictions on historical data but perform poorly when applied to new observations.
Quantifying uncertainty can help identify predictions that require additional review.
For example, an automated loan assessment system may flag cases where the model has limited knowledge of the applicant’s circumstances.
3.4 Better Communication of Analytical Results
Data analysts frequently present findings to managers and other stakeholders.
Reporting that sales increased by 12% may sound conclusive.
However, explaining that the estimated increase is 12%, with a confidence interval of 8% to 16%, provides additional context.
It communicates that the reported figure is an estimate rather than an exact measurement.
3.5 Detecting Unreliable Predictions
Uncertainty estimates can help identify observations that differ significantly from the training data.
For example, a model trained on transactions from Nigeria may be uncertain when evaluating transactions from a country with substantially different payment patterns.
This can trigger additional checks or human review.
4. Statistical Methods for Quantifying Uncertainty
Several statistical methods can be used to quantify uncertainty.
The appropriate method depends on the question, the type of data, and the assumptions that can reasonably be made.
4.1 Confidence Intervals
A confidence interval provides a range of plausible values for an unknown population parameter based on sample data.
Suppose a company wants to estimate the average amount customers spend per transaction.
A sample produces an average of ₦12,000.
Instead of reporting only the sample average, you can calculate a confidence interval.
A 95% confidence interval is generated by a procedure that, under its assumptions, would contain the true population parameter in approximately 95% of repeated samples.
It does not mean there is a 95% probability that a fixed population mean lies inside one particular frequentist confidence interval.
The general confidence interval formula for a sample mean, when the population standard deviation is unknown, is:
[
\bar{x} \pm t_{\alpha/2,n-1}
\left(\frac{s}{\sqrt{n}}\right)
]
Where:
- (\bar{x}) = sample mean.
- (t_{\alpha/2,n-1}) = critical value from the t-distribution.
- (s) = sample standard deviation.
- (n) = sample size.
A narrower interval generally indicates greater precision, although the validity of the interval depends on the sampling design and statistical assumptions.
4.2 Prediction Intervals
A prediction interval estimates a range within which a future individual observation is expected to fall, under the model’s assumptions.
This is different from a confidence interval.
A confidence interval for a mean describes uncertainty about the average value.
A prediction interval describes uncertainty about a future observation.
For example:
- Estimated average monthly sales: ₦5 million.
- 95% confidence interval for average sales: ₦4.8 million–₦5.2 million.
- 95% prediction interval for next month’s sales: ₦3.9 million–₦6.1 million.
The prediction interval is wider because it includes both uncertainty about the estimated average and natural variation in individual future outcomes.
Prediction intervals are particularly useful in sales forecasting, inventory management, demand planning, and financial analysis.
4.3 Bootstrapping
Bootstrapping is a statistical resampling technique used to estimate the variability of a statistic.
It works by repeatedly drawing samples with replacement from the original dataset and calculating the statistic of interest.
For example, imagine that you want to estimate the average spending of customers.
Instead of relying on one sample average, you can generate hundreds or thousands of bootstrap samples.
Each sample produces a slightly different average.
The distribution of these averages helps estimate the uncertainty around the original estimate.
Bootstrapping is useful when:
- The theoretical distribution of a statistic is difficult to derive.
- You want to estimate standard errors.
- You need confidence intervals for complex statistics.
- The available dataset is reasonably representative of the population.
However, bootstrapping cannot correct a biased or unrepresentative sample. It also requires care when observations are dependent, such as time series or clustered data.
4.4 Bayesian Statistics
Bayesian statistics provides another approach to uncertainty quantification.
It combines prior information with observed data to update beliefs about unknown parameters.
Bayes’ theorem is expressed as:
[
P(\theta \mid D) =
\frac{P(D \mid \theta)P(\theta)}{P(D)}
]
Where:
- (P(\theta \mid D)) = posterior probability.
- (P(D \mid \theta)) = likelihood.
- (P(\theta)) = prior probability.
- (P(D)) = evidence.
For example, a business may have historical information about customer churn.
When new customer data becomes available, Bayesian analysis can update the estimated probability of churn.
The result is a posterior distribution that represents uncertainty about the unknown parameter.
Bayesian credible intervals can then be calculated from this distribution.
A 95% credible interval has a direct probability interpretation under the specified Bayesian model: the posterior probability that the parameter lies inside the interval is 95%.
Bayesian methods are particularly useful when prior knowledge is relevant, data is limited, or a full probability distribution is required.
5. Measuring Uncertainty in Machine Learning
Machine learning models frequently produce predictions without explaining how uncertain those predictions are.
For example, a classification model may predict that a customer will churn with a probability of 0.82.
That number alone does not guarantee that the model is well calibrated or that its prediction is reliable.
Several methods can help quantify uncertainty in machine learning.
5.1 Prediction Probabilities
Many classification algorithms provide probability estimates.
For example, a model might return:
| Customer | Predicted churn probability |
|---|---|
| Customer A | 0.92 |
| Customer B | 0.76 |
| Customer C | 0.51 |
| Customer D | 0.14 |
These probabilities indicate the model’s estimated likelihood of the positive class.
However, prediction probabilities are not automatically reliable uncertainty estimates.
A model may produce probabilities close to 1.0 even when its predictions are frequently incorrect.
This is why probability calibration is important.
5.2 Model Calibration
A well-calibrated classification model produces probabilities that correspond reasonably well to observed frequencies.
For example, among observations assigned a predicted probability of approximately 0.80, around 80% should belong to the positive class over a sufficiently large representative group.
Calibration is important in applications such as:
- Medical risk prediction.
- Credit scoring.
- Fraud detection.
- Customer churn prediction.
- Insurance pricing.
You can evaluate calibration using reliability diagrams and metrics such as the Brier score.
The Brier score for binary classification is:
[
BS = \frac{1}{N}\sum_{i=1}^{N}(p_i-y_i)^2
]
Where:
- (p_i) = predicted probability.
- (y_i) = actual outcome.
- (N) = number of observations.
A lower Brier score indicates better probabilistic accuracy, although comparisons should account for class prevalence and the specific evaluation dataset.
5.3 Ensemble Methods
Ensemble methods combine predictions from multiple models.
Examples include:
- Random Forest.
- Gradient Boosting.
- Bagging.
- Bayesian model averaging.
The variation between predictions from different models or ensemble members can provide information about uncertainty.
For example, if multiple models produce similar predictions, the result may be more stable than when their predictions differ substantially.
However, disagreement is not a complete measure of uncertainty. Ensemble members can share the same biases and still agree on an incorrect prediction.
5.4 Monte Carlo Dropout
Monte Carlo Dropout is a technique used with neural networks.
Dropout is normally used during training to reduce overfitting by randomly disabling some network units.
With Monte Carlo Dropout, dropout remains active during prediction.
The model generates multiple predictions for the same input, and the variation between those predictions can be used as an approximate measure of epistemic uncertainty.
For example, a neural network might generate the following predictions for one observation:
0.72, 0.75, 0.69, 0.78, 0.73.
The variation suggests that the model’s prediction is not completely stable.
Monte Carlo Dropout is useful in certain deep learning applications, although its uncertainty estimates depend on the model architecture and assumptions.
6. How to Quantify Uncertainty Using Python
Python provides several libraries for statistical analysis and uncertainty quantification.
Some commonly used options include:
- NumPy for numerical calculations and simulations.
- Pandas for data manipulation.
- SciPy for statistical distributions and tests.
- Scikit-learn for machine learning evaluation.
- Statsmodels for statistical modelling.
- PyMC for Bayesian modelling.
- MAPIE for prediction intervals and conformal prediction workflows.
Let’s explore practical examples.
Example 1: Calculate a Confidence Interval Using SciPy
Suppose you have a dataset containing customer transaction values.
You want to estimate the average transaction value and calculate a 95% confidence interval.
import numpy as np
from scipy import stats
transactions = np.array([
12000, 15000, 18000, 11000, 22000,
17000, 14000, 19000, 16000, 21000,
13000, 20000, 17500, 15500, 18500
])
mean_value = np.mean(transactions)
confidence_interval = stats.t.interval(
confidence=0.95,
df=len(transactions) - 1,
loc=mean_value,
scale=stats.sem(transactions)
)
print("Average transaction value:", mean_value)
print(
"95% Confidence Interval:",
confidence_interval
)
The code calculates the sample mean and uses the t-distribution to estimate the confidence interval.
The interval relies on assumptions about the sampling process and the suitability of the t-based method. For small samples, the shape of the underlying population distribution matters.
Example 2: Estimate Uncertainty Through Bootstrapping
Now, let’s estimate the uncertainty around the average transaction value using bootstrapping.
import numpy as np
transactions = np.array([
12000, 15000, 18000, 11000, 22000,
17000, 14000, 19000, 16000, 21000,
13000, 20000, 17500, 15500, 18500
])
bootstrap_means = []
for _ in range(10000):
sample = np.random.choice(
transactions,
size=len(transactions),
replace=True
)
bootstrap_means.append(np.mean(sample))
lower = np.percentile(bootstrap_means, 2.5)
upper = np.percentile(bootstrap_means, 97.5)
print("Original mean:", np.mean(transactions))
print("Bootstrap interval:", lower, upper)
This example generates 10,000 bootstrap samples.
Each sample produces a new average transaction value. The 2.5th and 97.5th percentiles provide a percentile-based 95% bootstrap interval.
For reproducible results, set a random seed before generating the samples.
np.random.seed(42)
Example 3: Quantify Prediction Uncertainty With an Ensemble
Let’s use a Random Forest model to demonstrate how prediction variation can be examined.
Random Forest consists of multiple decision trees trained using different bootstrap samples and feature subsets.
Their predictions can be compared to understand how much individual trees disagree.
import numpy as np
from sklearn.datasets import make_regression
from sklearn.ensemble import RandomForestRegressor
from sklearn.model_selection import train_test_split
X, y = make_regression(
n_samples=1000,
n_features=5,
noise=15,
random_state=42
)
X_train, X_test, y_train, y_test = train_test_split(
X,
y,
test_size=0.2,
random_state=42
)
model = RandomForestRegressor(
n_estimators=200,
random_state=42
)
model.fit(X_train, y_train)
tree_predictions = np.array([
tree.predict(X_test)
for tree in model.estimators_
])
mean_prediction = tree_predictions.mean(axis=0)
prediction_variation = tree_predictions.std(axis=0)
print("Predictions:", mean_prediction[:5])
print("Tree disagreement:", prediction_variation[:5])
The code calculates the average prediction and standard deviation across individual trees.
A larger standard deviation indicates greater disagreement between the trees.
However, this standard deviation should not automatically be interpreted as a calibrated prediction interval. Random Forest tree disagreement is only a proxy for some forms of uncertainty and does not fully capture natural outcome variability.
Example 4: Build Prediction Intervals With Conformal Prediction
Conformal prediction provides a framework for generating prediction sets or intervals with finite-sample coverage guarantees under exchangeability assumptions.
For regression, a common approach is to reserve separate training, calibration, and test datasets.
The model is trained on the training data, and prediction errors on the calibration data are used to determine an interval width.
The following example demonstrates a simple split conformal prediction procedure.
import numpy as np
from sklearn.datasets import make_regression
from sklearn.ensemble import RandomForestRegressor
from sklearn.model_selection import train_test_split
X, y = make_regression(
n_samples=1500,
n_features=5,
noise=20,
random_state=42
)
X_train, X_remaining, y_train, y_remaining = train_test_split(
X,
y,
test_size=0.4,
random_state=42
)
X_cal, X_test, y_cal, y_test = train_test_split(
X_remaining,
y_remaining,
test_size=0.5,
random_state=42
)
model = RandomForestRegressor(
n_estimators=200,
random_state=42
)
model.fit(X_train, y_train)
cal_predictions = model.predict(X_cal)
cal_errors = np.abs(y_cal - cal_predictions)
alpha = 0.05
n = len(cal_errors)
# Finite-sample conformal quantile
rank = min(
n,
int(np.ceil((n + 1) * (1 - alpha)))
)
q = np.sort(cal_errors)[rank - 1]
test_predictions = model.predict(X_test)
lower = test_predictions - q
upper = test_predictions + q
coverage = np.mean(
(y_test >= lower) & (y_test <= upper)
)
print("Prediction interval width:", 2 * q)
print("Observed test coverage:", coverage)
This example produces a prediction interval for each test observation.
Under the exchangeability assumption and with an independent calibration set, split conformal prediction provides marginal coverage of at least the nominal level, subject to the finite-sample construction.
It does not guarantee that every subgroup or individual observation receives equally accurate coverage.
Conformal prediction is useful when you need prediction intervals without relying heavily on a particular parametric error distribution.
7. Understanding Uncertainty in Data Visualisation
Uncertainty should not only appear in statistical calculations. It can also be communicated through visualisations.
A chart showing a single forecast line may suggest that the future is completely predictable.
Adding uncertainty intervals helps viewers understand the range of possible outcomes.
Common visualisation techniques include:
Error Bars
Error bars show the variability or uncertainty associated with individual measurements.
They are commonly used in scientific charts, experimental results, and statistical comparisons.
However, always explain whether the error bars represent standard deviations, standard errors, or confidence intervals.
Confidence Bands
Confidence bands display uncertainty around an estimated relationship or curve.
They are particularly useful for regression models and time series analysis.
Prediction Bands
Prediction bands show a range of plausible future observations around a forecast.
They are useful for demand forecasting, revenue predictions, and inventory planning.
Box Plots
Box plots display the distribution of a dataset through its median, quartiles, and potential outliers.
They help analysts understand variation rather than focusing exclusively on averages.
Example: Visualising a Confidence Interval
import matplotlib.pyplot as plt
import numpy as np
from scipy import stats
data = np.array([
12000, 15000, 18000, 11000, 22000,
17000, 14000, 19000, 16000, 21000,
13000, 20000, 17500, 15500, 18500
])
mean = np.mean(data)
ci = stats.t.interval(
confidence=0.95,
df=len(data) - 1,
loc=mean,
scale=stats.sem(data)
)
plt.errorbar(
x=["Average Transaction"],
y=[mean],
yerr=[[mean - ci[0]], [ci[1] - mean]],
fmt="o",
capsize=8
)
plt.ylabel("Transaction Value")
plt.title("Average Transaction Value With 95% Confidence Interval")
plt.show()
The chart presents the estimated average alongside its confidence interval.
For business reporting, clearly label the interval and its interpretation so stakeholders do not mistake it for the range of every individual transaction.
8. Common Mistakes When Quantifying Uncertainty
Uncertainty quantification is useful, but incorrect interpretation can produce misleading conclusions.
Here are some mistakes to avoid.
1. Treating a Confidence Interval as a Prediction Interval
A confidence interval for the mean does not describe the range within which every future observation will fall.
Use prediction intervals when estimating the range of future individual outcomes.
2. Assuming More Data Eliminates All Uncertainty
Larger datasets can reduce uncertainty caused by limited information.
However, natural randomness and unpredictable events may remain.
3. Reporting Probabilities Without Checking Calibration
A model that predicts a 90% probability does not necessarily have a 90% success rate for those predictions.
Evaluate calibration before relying on predicted probabilities.
4. Ignoring Data Quality
Missing values, measurement errors, biased samples, and incorrect records can undermine uncertainty estimates.
The quality of the underlying data matters.
5. Using Inappropriate Statistical Assumptions
Some methods assume independent observations, normal distributions, or exchangeability.
Applying them without checking their assumptions can produce unreliable intervals.
6. Confusing Model Disagreement With Total Uncertainty
Different models may produce similar predictions while sharing the same weaknesses.
Ensemble disagreement is useful, but it does not capture every source of uncertainty.
7. Presenting Uncertainty Without Explaining Its Meaning
A chart containing a 95% interval is not automatically useful to a business stakeholder.
Explain what the interval represents, how it was calculated, and what decisions it should influence.
9. Best Practices for Uncertainty Quantification
To make uncertainty quantification a reliable part of your data science workflow, consider the following practices.
Identify the source of uncertainty. Determine whether uncertainty comes from natural variation, limited knowledge, data quality, model assumptions, or measurement errors.
Choose an appropriate statistical method. Use confidence intervals for population parameters, prediction intervals for future observations, and Bayesian methods when posterior probability distributions are useful.
Use representative data. Uncertainty estimates cannot compensate for a dataset that does not represent the population or environment of interest.
Validate your model. Test whether uncertainty estimates behave as expected using held-out observations and suitable calibration or coverage checks.
Communicate uncertainty clearly. Explain what an interval means instead of simply presenting a numerical range.
Monitor uncertainty over time. Data distributions can change. A model that was reliable during training may become less reliable when new patterns emerge.
Consider the cost of incorrect decisions. A prediction with moderate uncertainty may be acceptable in one application but require human review in another.
Document assumptions. Record the method, data, assumptions, and limitations used to produce uncertainty estimates.
Conclusion
Uncertainty is an unavoidable part of data science.
Datasets contain natural variation, statistical estimates are based on limited observations, and machine learning models can struggle when they encounter unfamiliar patterns.
The goal is not to eliminate uncertainty but to measure and communicate it accurately.
Methods such as confidence intervals, prediction intervals, bootstrapping, Bayesian statistics, ensemble analysis, and conformal prediction help data scientists understand the reliability of their results.
Python libraries such as NumPy, SciPy, Scikit-learn, Statsmodels, and PyMC make these methods accessible for practical applications.
Whether you are forecasting sales, developing machine learning models, analysing customer behaviour, or conducting scientific research, uncertainty quantification can help you move beyond predictions and make better-informed decisions.
A good data scientist does not only ask what the data says. They also ask how certain they can be about it.
Frequently Asked Questions
1. What is uncertainty quantification in data science?
Uncertainty quantification is the process of measuring and describing uncertainty in datasets, statistical estimates, and machine learning predictions. It helps data scientists understand how reliable their results are.
2. What are the two main types of uncertainty in machine learning?
The two main types are aleatoric and epistemic uncertainty. Aleatoric uncertainty comes from natural randomness in the data, while epistemic uncertainty comes from limited knowledge or insufficient information about the problem.
3. What is the difference between a confidence interval and a prediction interval?
A confidence interval estimates uncertainty around a population parameter, such as an average. A prediction interval estimates a range in which a future individual observation is expected to fall. Prediction intervals are generally wider because they account for additional observation-level variation.
4. Which Python libraries can be used for uncertainty quantification?
Common libraries include NumPy, SciPy, Pandas, Scikit-learn, Statsmodels, PyMC, and MAPIE. They support statistical analysis, bootstrapping, Bayesian modelling, probabilistic predictions, and conformal prediction.
5. Why is uncertainty quantification important in machine learning?
It helps identify potentially unreliable predictions, supports better risk management, improves decision-making, and provides more information about model reliability. It is particularly useful in high-impact applications such as finance, healthcare, and fraud detection.