# Import Turing.
using Turing
# Package for loading the data set.
using RDatasets
# Package for visualization.
using StatsPlots
# Functionality for splitting the data.
using MLUtils: splitobs
# Functionality for constructing arrays with identical elements efficiently.
using FillArrays
# Functionality for normalizing the data and evaluating the model predictions.
using StatsBase
# Functionality for working with scaled identity matrices.
using LinearAlgebra
# Set a seed for reproducibility.
using Random
Random.seed!(0);
Linear Regression
Turing is powerful when applied to complex hierarchical models, but it can also be put to task at common statistical procedures, like linear regression. This tutorial covers how to implement a linear regression model in Turing.
Set Up
We begin by importing all the necessary libraries.
setprogress!(false)
We will use the mtcars
dataset from the RDatasets package. mtcars
contains a variety of statistics on different car models, including their miles per gallon, number of cylinders, and horsepower, among others.
We want to know if we can construct a Bayesian linear regression model to predict the miles per gallon of a car, given the other statistics it has. Let us take a look at the data we have.
# Load the dataset.
= RDatasets.dataset("datasets", "mtcars")
data
# Show the first six rows of the dataset.
first(data, 6)
Row | Model | MPG | Cyl | Disp | HP | DRat | WT | QSec | VS | AM | Gear | Carb |
---|---|---|---|---|---|---|---|---|---|---|---|---|
String31 | Float64 | Int64 | Float64 | Int64 | Float64 | Float64 | Float64 | Int64 | Int64 | Int64 | Int64 | |
1 | Mazda RX4 | 21.0 | 6 | 160.0 | 110 | 3.9 | 2.62 | 16.46 | 0 | 1 | 4 | 4 |
2 | Mazda RX4 Wag | 21.0 | 6 | 160.0 | 110 | 3.9 | 2.875 | 17.02 | 0 | 1 | 4 | 4 |
3 | Datsun 710 | 22.8 | 4 | 108.0 | 93 | 3.85 | 2.32 | 18.61 | 1 | 1 | 4 | 1 |
4 | Hornet 4 Drive | 21.4 | 6 | 258.0 | 110 | 3.08 | 3.215 | 19.44 | 1 | 0 | 3 | 1 |
5 | Hornet Sportabout | 18.7 | 8 | 360.0 | 175 | 3.15 | 3.44 | 17.02 | 0 | 0 | 3 | 2 |
6 | Valiant | 18.1 | 6 | 225.0 | 105 | 2.76 | 3.46 | 20.22 | 1 | 0 | 3 | 1 |
size(data)
(32, 12)
The next step is to get our data ready for testing. We’ll split the mtcars
dataset into two subsets, one for training our model and one for evaluating our model. Then, we separate the targets we want to learn (MPG
, in this case) and standardize the datasets by subtracting each column’s means and dividing by the standard deviation of that column. The resulting data is not very familiar looking, but this standardization process helps the sampler converge far easier.
# Remove the model column.
select!(data, Not(:Model))
# Split our dataset 70%/30% into training/test sets.
= map(DataFrame, splitobs(data; at=0.7, shuffle=true))
trainset, testset
# Turing requires data in matrix form.
= :MPG
target = Matrix(select(trainset, Not(target)))
train = Matrix(select(testset, Not(target)))
test = trainset[:, target]
train_target = testset[:, target]
test_target
# Standardize the features.
= fit(ZScoreTransform, train; dims=1)
dt_features transform!(dt_features, train)
StatsBase.transform!(dt_features, test)
StatsBase.
# Standardize the targets.
= fit(ZScoreTransform, train_target)
dt_targets transform!(dt_targets, train_target)
StatsBase.transform!(dt_targets, test_target); StatsBase.
Model Specification
In a traditional frequentist model using OLS, our model might look like:
\[ \mathrm{MPG}_i = \alpha + \boldsymbol{\beta}^\mathsf{T}\boldsymbol{X_i} \]
where \(\boldsymbol{\beta}\) is a vector of coefficients and \(\boldsymbol{X}\) is a vector of inputs for observation \(i\). The Bayesian model we are more concerned with is the following:
\[ \mathrm{MPG}_i \sim \mathcal{N}(\alpha + \boldsymbol{\beta}^\mathsf{T}\boldsymbol{X_i}, \sigma^2) \]
where \(\alpha\) is an intercept term common to all observations, \(\boldsymbol{\beta}\) is a coefficient vector, \(\boldsymbol{X_i}\) is the observed data for car \(i\), and \(\sigma^2\) is a common variance term.
For \(\sigma^2\), we assign a prior of truncated(Normal(0, 100); lower=0)
. This is consistent with Andrew Gelman’s recommendations on noninformative priors for variance. The intercept term (\(\alpha\)) is assumed to be normally distributed with a mean of zero and a variance of three. This represents our assumptions that miles per gallon can be explained mostly by our assorted variables, but a high variance term indicates our uncertainty about that. Each coefficient is assumed to be normally distributed with a mean of zero and a variance of 10. We do not know that our coefficients are different from zero, and we don’t know which ones are likely to be the most important, so the variance term is quite high. Lastly, each observation \(y_i\) is distributed according to the calculated mu
term given by \(\alpha + \boldsymbol{\beta}^\mathsf{T}\boldsymbol{X_i}\).
# Bayesian linear regression.
@model function linear_regression(x, y)
# Set variance prior.
~ truncated(Normal(0, 100); lower=0)
σ²
# Set intercept prior.
~ Normal(0, sqrt(3))
intercept
# Set the priors on our coefficients.
= size(x, 2)
nfeatures ~ MvNormal(Zeros(nfeatures), 10.0 * I)
coefficients
# Calculate all the mu terms.
= intercept .+ x * coefficients
mu return y ~ MvNormal(mu, σ² * I)
end
linear_regression (generic function with 2 methods)
With our model specified, we can call the sampler. We will use the No U-Turn Sampler (NUTS) here.
= linear_regression(train, train_target)
model = sample(model, NUTS(), 5_000) chain
┌ Info: Found initial step size
└ ϵ = 0.4
Chains MCMC chain (5000×24×1 Array{Float64, 3}):
Iterations = 1001:1:6000
Number of chains = 1
Samples per chain = 5000
Wall duration = 10.52 seconds
Compute duration = 10.52 seconds
parameters = σ², intercept, coefficients[1], coefficients[2], coefficients[3], coefficients[4], coefficients[5], coefficients[6], coefficients[7], coefficients[8], coefficients[9], coefficients[10]
internals = lp, n_steps, is_accept, acceptance_rate, log_density, hamiltonian_energy, hamiltonian_energy_error, max_hamiltonian_energy_error, tree_depth, numerical_error, step_size, nom_step_size
Summary Statistics
parameters mean std mcse ess_bulk ess_tail ⋯
Symbol Float64 Float64 Float64 Float64 Float64 Flo ⋯
σ² 0.4877 0.2948 0.0072 1552.1152 1873.4523 1. ⋯
intercept 0.0018 0.1509 0.0020 5670.2468 3027.7918 1. ⋯
coefficients[1] -0.5497 0.6019 0.0103 3492.6352 3114.4466 0. ⋯
coefficients[2] 0.3350 0.7993 0.0194 1730.5839 2090.9083 0. ⋯
coefficients[3] -0.4347 0.5143 0.0099 2792.6329 2623.1141 0. ⋯
coefficients[4] 0.0033 0.2800 0.0049 3252.9778 2430.2451 1. ⋯
coefficients[5] -0.1910 0.5719 0.0138 1727.8299 2190.7356 0. ⋯
coefficients[6] -0.0605 0.4735 0.0110 1843.1737 2734.5008 0. ⋯
coefficients[7] -0.1274 0.4536 0.0100 2019.1325 2921.7519 1. ⋯
coefficients[8] 0.0833 0.4089 0.0099 1790.9440 2100.0857 1. ⋯
coefficients[9] 0.2439 0.3853 0.0080 2320.5137 2009.7651 0. ⋯
coefficients[10] -0.1618 0.5019 0.0136 1378.4670 1566.1604 1. ⋯
2 columns omitted
Quantiles
parameters 2.5% 25.0% 50.0% 75.0% 97.5%
Symbol Float64 Float64 Float64 Float64 Float64
σ² 0.1839 0.3037 0.4099 0.5742 1.2878
intercept -0.2900 -0.0933 0.0030 0.0971 0.3085
coefficients[1] -1.7505 -0.9185 -0.5542 -0.1794 0.6762
coefficients[2] -1.2628 -0.1769 0.3498 0.8422 1.8802
coefficients[3] -1.4557 -0.7577 -0.4307 -0.1248 0.6147
coefficients[4] -0.5635 -0.1654 0.0009 0.1736 0.5544
coefficients[5] -1.3284 -0.5538 -0.1858 0.1689 0.9643
coefficients[6] -0.9919 -0.3618 -0.0684 0.2411 0.9076
coefficients[7] -1.0377 -0.3987 -0.1243 0.1612 0.7667
coefficients[8] -0.7323 -0.1749 0.0863 0.3428 0.8865
coefficients[9] -0.5094 0.0018 0.2365 0.4848 1.0037
coefficients[10] -1.1307 -0.4789 -0.1524 0.1581 0.8142
We can also check the densities and traces of the parameters visually using the plot
functionality.
plot(chain)
It looks like all parameters have converged.
Comparing to OLS
A satisfactory test of our model is to evaluate how well it predicts. Importantly, we want to compare our model to existing tools like OLS. The code below uses the GLM.jl package to generate a traditional OLS multiple regression model on the same data as our probabilistic model.
# Import the GLM package.
using GLM
# Perform multiple regression OLS.
= hcat(ones(size(train, 1)), train)
train_with_intercept = lm(train_with_intercept, train_target)
ols
# Compute predictions on the training data set and unstandardize them.
= GLM.predict(ols)
train_prediction_ols reconstruct!(dt_targets, train_prediction_ols)
StatsBase.
# Compute predictions on the test data set and unstandardize them.
= hcat(ones(size(test, 1)), test)
test_with_intercept = GLM.predict(ols, test_with_intercept)
test_prediction_ols reconstruct!(dt_targets, test_prediction_ols); StatsBase.
The function below accepts a chain and an input matrix and calculates predictions. We use the samples of the model parameters in the chain starting with sample 200.
# Make a prediction given an input vector.
function prediction(chain, x)
= get_params(chain[200:end, :, :])
p = p.intercept' .+ x * reduce(hcat, p.coefficients)'
targets return vec(mean(targets; dims=2))
end
prediction (generic function with 1 method)
When we make predictions, we unstandardize them so they are more understandable.
# Calculate the predictions for the training and testing sets and unstandardize them.
= prediction(chain, train)
train_prediction_bayes reconstruct!(dt_targets, train_prediction_bayes)
StatsBase.= prediction(chain, test)
test_prediction_bayes reconstruct!(dt_targets, test_prediction_bayes)
StatsBase.
# Show the predictions on the test data set.
DataFrame(; MPG=testset[!, target], Bayes=test_prediction_bayes, OLS=test_prediction_ols)
Row | MPG | Bayes | OLS |
---|---|---|---|
Float64 | Float64 | Float64 | |
1 | 33.9 | 26.7121 | 26.804 |
2 | 21.0 | 22.3213 | 22.4669 |
3 | 21.4 | 20.4565 | 20.5666 |
4 | 26.0 | 29.115 | 28.9169 |
5 | 15.0 | 11.5385 | 11.584 |
6 | 10.4 | 13.5867 | 13.7006 |
7 | 30.4 | 27.1584 | 27.4661 |
8 | 10.4 | 14.3254 | 14.5346 |
9 | 18.7 | 17.2564 | 17.2897 |
10 | 17.3 | 14.7348 | 14.6084 |
Now let’s evaluate the loss for each method, and each prediction set. We will use the mean squared error to evaluate loss, given by \[ \mathrm{MSE} = \frac{1}{n} \sum_{i=1}^n {(y_i - \hat{y_i})^2} \] where \(y_i\) is the actual value (true MPG) and \(\hat{y_i}\) is the predicted value using either OLS or Bayesian linear regression. A lower SSE indicates a closer fit to the data.
println(
"Training set:",
"\n\tBayes loss: ",
msd(train_prediction_bayes, trainset[!, target]),
"\n\tOLS loss: ",
msd(train_prediction_ols, trainset[!, target]),
)
println(
"Test set:",
"\n\tBayes loss: ",
msd(test_prediction_bayes, testset[!, target]),
"\n\tOLS loss: ",
msd(test_prediction_ols, testset[!, target]),
)
Training set:
Bayes loss: 4.268762877292322
OLS loss: 4.264328587912453
Test set:
Bayes loss: 12.072277127410558
OLS loss: 11.920700014054287
As we can see above, OLS and our Bayesian model fit our training and test data set about the same.