Prediction intervals provide a range of values within which the true value is likely to fall. They give a sense of the uncertainty in our predictions, which is very important in many business applications.
There are several ways to generate prediction intervals for machine learning models, but one of the most common methods is based on the concept of Bootstrapping.
Bootstrapping is a powerful statistical method for estimating a quantity from a data sample. This is done by repeatedly sampling subsets of the data, estimating the quantity for each subset, and then taking the average of these estimates.
Here's a basic bootstrap approach to generate prediction intervals:
- Fit your model on the original dataset.
- Generate a large number of bootstrap samples from the original dataset (with replacement).
- For each bootstrap sample, fit the model and make a prediction.
- Sort the predictions and extract the desired prediction interval.
Now, let's implement this in Python, using Scikit-learn for the machine learning model:
import numpy as np
from sklearn.utils import resample
from sklearn.tree import DecisionTreeRegressor
from sklearn.model_selection import train_test_split
# assume X and y are your data
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)
# fit the model
model = DecisionTreeRegressor()
model.fit(X_train, y_train)
# number of bootstrap samples to generate
n_iterations = 1000
# size of a bootstrap sample (70% of the training set)
n_size = int(len(y_train) * 0.7)
# run bootstrap
stats = list()
for i in range(n_iterations):
# prepare train and test sets
X_train_resample, y_train_resample = resample(X_train, y_train, n_samples=n_size)
# fit model
model = DecisionTreeRegressor()
model.fit(X_train_resample, y_train_resample)
# evaluate model on test set
y_pred = model.predict(X_test)
# store stats
stats.append(np.abs(y_pred - y_test))
# create 95% prediction interval for y
y_interval = np.percentile(stats, (2.5, 97.5))
In the above code, we first fit a DecisionTreeRegressor model to our training data. Then, we generate 1000 bootstrap samples of the training data and fit a new model to each sample. We then predict the test