# Load Turing.
using Turing
# Load RDatasets.
using RDatasets
# Load StatsPlots for visualizations and diagnostics.
using StatsPlots
# Functionality for splitting and normalizing the data.
using MLDataUtils: shuffleobs, splitobs, rescale!
# We need a softmax function which is provided by NNlib.
using NNlib: softmax
# Functionality for constructing arrays with identical elements efficiently.
using FillArrays
# Functionality for working with scaled identity matrices.
using LinearAlgebra
# Set a seed for reproducibility.
using Random
Random.seed!(0);
Multinomial Logistic Regression
Multinomial logistic regression is an extension of logistic regression. Logistic regression is used to model problems in which there are exactly two possible discrete outcomes. Multinomial logistic regression is used to model problems in which there are two or more possible discrete outcomes.
In our example, we’ll be using the iris dataset. The iris multiclass problem aims to predict the species of a flower given measurements (in centimeters) of sepal length and width and petal length and width. There are three possible species: Iris setosa, Iris versicolor, and Iris virginica.
To start, let’s import all the libraries we’ll need.
Data Cleaning & Set Up
Now we’re going to import our dataset. Twenty rows of the dataset are shown below so you can get a good feel for what kind of data we have.
# Import the "iris" dataset.
= RDatasets.dataset("datasets", "iris");
data
# Show twenty random rows.
rand(1:size(data, 1), 20), :] data[
Row | SepalLength | SepalWidth | PetalLength | PetalWidth | Species |
---|---|---|---|---|---|
Float64 | Float64 | Float64 | Float64 | Cat… | |
1 | 5.0 | 2.0 | 3.5 | 1.0 | versicolor |
2 | 5.4 | 3.7 | 1.5 | 0.2 | setosa |
3 | 7.2 | 3.0 | 5.8 | 1.6 | virginica |
4 | 4.8 | 3.0 | 1.4 | 0.1 | setosa |
5 | 5.7 | 2.8 | 4.1 | 1.3 | versicolor |
6 | 5.1 | 3.5 | 1.4 | 0.3 | setosa |
7 | 5.4 | 3.9 | 1.3 | 0.4 | setosa |
8 | 7.6 | 3.0 | 6.6 | 2.1 | virginica |
9 | 5.0 | 3.5 | 1.6 | 0.6 | setosa |
10 | 5.0 | 3.6 | 1.4 | 0.2 | setosa |
11 | 5.5 | 2.4 | 3.8 | 1.1 | versicolor |
12 | 6.1 | 2.6 | 5.6 | 1.4 | virginica |
13 | 4.4 | 3.0 | 1.3 | 0.2 | setosa |
14 | 7.0 | 3.2 | 4.7 | 1.4 | versicolor |
15 | 6.1 | 2.9 | 4.7 | 1.4 | versicolor |
16 | 7.7 | 3.0 | 6.1 | 2.3 | virginica |
17 | 6.4 | 2.7 | 5.3 | 1.9 | virginica |
18 | 5.1 | 3.3 | 1.7 | 0.5 | setosa |
19 | 6.7 | 3.1 | 4.7 | 1.5 | versicolor |
20 | 6.2 | 2.2 | 4.5 | 1.5 | versicolor |
In this data set, the outcome Species
is currently coded as a string. We convert it to a numerical value by using indices 1
, 2
, and 3
to indicate species setosa
, versicolor
, and virginica
, respectively.
# Recode the `Species` column.
= ["setosa", "versicolor", "virginica"]
species :Species_index] = indexin(data[!, :Species], species)
data[!,
# Show twenty random rows of the new species columns
rand(1:size(data, 1), 20), [:Species, :Species_index]] data[
Row | Species | Species_index |
---|---|---|
Cat… | Union… | |
1 | setosa | 1 |
2 | versicolor | 2 |
3 | versicolor | 2 |
4 | setosa | 1 |
5 | versicolor | 2 |
6 | versicolor | 2 |
7 | versicolor | 2 |
8 | versicolor | 2 |
9 | virginica | 3 |
10 | versicolor | 2 |
11 | virginica | 3 |
12 | setosa | 1 |
13 | setosa | 1 |
14 | versicolor | 2 |
15 | setosa | 1 |
16 | setosa | 1 |
17 | virginica | 3 |
18 | versicolor | 2 |
19 | virginica | 3 |
20 | virginica | 3 |
After we’ve done that tidying, it’s time to split our dataset into training and testing sets, and separate the features and target from the data. Additionally, we must rescale our feature variables so that they are centered around zero by subtracting each column by the mean and dividing it by the standard deviation. Without this step, Turing’s sampler will have a hard time finding a place to start searching for parameter estimates.
# Split our dataset 50%/50% into training/test sets.
= splitobs(shuffleobs(data), 0.5)
trainset, testset
# Define features and target.
= [:SepalLength, :SepalWidth, :PetalLength, :PetalWidth]
features = :Species_index
target
# Turing requires data in matrix and vector form.
= Matrix(trainset[!, features])
train_features = Matrix(testset[!, features])
test_features = trainset[!, target]
train_target = testset[!, target]
test_target
# Standardize the features.
= rescale!(train_features; obsdim=1)
μ, σ rescale!(test_features, μ, σ; obsdim=1);
Model Declaration
Finally, we can define our model logistic_regression
. It is a function that takes three arguments where
x
is our set of independent variables;y
is the element we want to predict;σ
is the standard deviation we want to assume for our priors.
We select the setosa
species as the baseline class (the choice does not matter). Then we create the intercepts and vectors of coefficients for the other classes against that baseline. More concretely, we create scalar intercepts intercept_versicolor
and intersept_virginica
and coefficient vectors coefficients_versicolor
and coefficients_virginica
with four coefficients each for the features SepalLength
, SepalWidth
, PetalLength
and PetalWidth
. We assume a normal distribution with mean zero and standard deviation σ
as prior for each scalar parameter. We want to find the posterior distribution of these, in total ten, parameters to be able to predict the species for any given set of features.
# Bayesian multinomial logistic regression
@model function logistic_regression(x, y, σ)
= size(x, 1)
n length(y) == n ||
throw(DimensionMismatch("number of observations in `x` and `y` is not equal"))
# Priors of intercepts and coefficients.
~ Normal(0, σ)
intercept_versicolor ~ Normal(0, σ)
intercept_virginica ~ MvNormal(Zeros(4), σ^2 * I)
coefficients_versicolor ~ MvNormal(Zeros(4), σ^2 * I)
coefficients_virginica
# Compute the likelihood of the observations.
= intercept_versicolor .+ x * coefficients_versicolor
values_versicolor = intercept_virginica .+ x * coefficients_virginica
values_virginica for i in 1:n
# the 0 corresponds to the base category `setosa`
= softmax([0, values_versicolor[i], values_virginica[i]])
v ~ Categorical(v)
y[i] end
end;
Sampling
Now we can run our sampler. This time we’ll use NUTS
to sample from our posterior.
setprogress!(false)
= logistic_regression(train_features, train_target, 1)
m = sample(m, NUTS(), MCMCThreads(), 1_500, 3) chain
Chains MCMC chain (1500×22×3 Array{Float64, 3}):
Iterations = 751:1:2250
Number of chains = 3
Samples per chain = 1500
Wall duration = 18.39 seconds
Compute duration = 15.45 seconds
parameters = intercept_versicolor, intercept_virginica, coefficients_versicolor[1], coefficients_versicolor[2], coefficients_versicolor[3], coefficients_versicolor[4], coefficients_virginica[1], coefficients_virginica[2], coefficients_virginica[3], coefficients_virginica[4]
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_ ⋯
Symbol Float64 Float64 Float64 Float64 Flo ⋯
intercept_versicolor 1.0136 0.5040 0.0077 4402.2990 3403. ⋯
intercept_virginica -0.4724 0.6369 0.0095 4462.7478 2810. ⋯
coefficients_versicolor[1] 1.2784 0.6487 0.0103 3992.0133 3303. ⋯
coefficients_versicolor[2] -1.3313 0.4978 0.0074 4542.7151 3565. ⋯
coefficients_versicolor[3] 0.8515 0.7542 0.0113 4433.9939 3239. ⋯
coefficients_versicolor[4] 0.2894 0.7344 0.0107 4715.5647 2771. ⋯
coefficients_virginica[1] 0.8123 0.6765 0.0104 4197.4091 2897. ⋯
coefficients_virginica[2] -0.7359 0.6227 0.0088 5038.5643 3463. ⋯
coefficients_virginica[3] 2.4230 0.8319 0.0122 4683.9963 3071. ⋯
coefficients_virginica[4] 2.7146 0.8004 0.0118 4604.1265 3165. ⋯
3 columns omitted
Quantiles
parameters 2.5% 25.0% 50.0% 75.0% 97.5% ⋯
Symbol Float64 Float64 Float64 Float64 Float64 ⋯
intercept_versicolor 0.0798 0.6704 1.0010 1.3483 2.0118 ⋯
intercept_virginica -1.7571 -0.8866 -0.4649 -0.0399 0.7377 ⋯
coefficients_versicolor[1] 0.0160 0.8378 1.2794 1.7064 2.5311 ⋯
coefficients_versicolor[2] -2.3114 -1.6649 -1.3104 -0.9902 -0.3879 ⋯
coefficients_versicolor[3] -0.6337 0.3452 0.8371 1.3381 2.3505 ⋯
coefficients_versicolor[4] -1.1713 -0.2085 0.2818 0.7794 1.7530 ⋯
coefficients_virginica[1] -0.4744 0.3401 0.8036 1.2695 2.1830 ⋯
coefficients_virginica[2] -1.9817 -1.1467 -0.7240 -0.3236 0.4872 ⋯
coefficients_virginica[3] 0.8285 1.8478 2.4270 2.9553 4.0803 ⋯
coefficients_virginica[4] 1.1537 2.1665 2.7079 3.2690 4.2738 ⋯
The sample()
call above assumes that you have at least nchains
threads available in your Julia instance. If you do not, the multiple chains will run sequentially, and you may notice a warning. For more information, see the Turing documentation on sampling multiple chains.
Since we ran multiple chains, we may as well do a spot check to make sure each chain converges around similar points.
plot(chain)