Bayesian 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.

# 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);

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.
data = RDatasets.dataset("datasets", "iris");

# Show twenty random rows.
data[rand(1:size(data, 1), 20), :]
20×5 DataFrame
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.
species = ["setosa", "versicolor", "virginica"]
data[!, :Species_index] = indexin(data[!, :Species], species)

# Show twenty random rows of the new species columns
data[rand(1:size(data, 1), 20), [:Species, :Species_index]]
20×2 DataFrame
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.
trainset, testset = splitobs(shuffleobs(data), 0.5)

# Define features and target.
features = [:SepalLength, :SepalWidth, :PetalLength, :PetalWidth]
target = :Species_index

# Turing requires data in matrix and vector form.
train_features = Matrix(trainset[!, features])
test_features = Matrix(testset[!, features])
train_target = trainset[!, target]
test_target = testset[!, 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, σ)
    n = size(x, 1)
    length(y) == n ||
        throw(DimensionMismatch("number of observations in `x` and `y` is not equal"))

    # Priors of intercepts and coefficients.
    intercept_versicolor ~ Normal(0, σ)
    intercept_virginica ~ Normal(0, σ)
    coefficients_versicolor ~ MvNormal(Zeros(4), σ^2 * I)
    coefficients_virginica ~ MvNormal(Zeros(4), σ^2 * I)

    # Compute the likelihood of the observations.
    values_versicolor = intercept_versicolor .+ x * coefficients_versicolor
    values_virginica = intercept_virginica .+ x * coefficients_virginica
    for i in 1:n
        # the 0 corresponds to the base category `setosa`
        v = softmax([0, values_versicolor[i], values_virginica[i]])
        y[i] ~ Categorical(v)
    end
end;

Sampling

Now we can run our sampler. This time we’ll use NUTS to sample from our posterior.

setprogress!(false)
m = logistic_regression(train_features, train_target, 1)
chain = sample(m, NUTS(), MCMCThreads(), 1_500, 3)
Chains MCMC chain (1500×22×3 Array{Float64, 3}):

Iterations        = 751:1:2250
Number of chains  = 3
Samples per chain = 1500
Wall duration     = 17.86 seconds
Compute duration  = 15.19 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.0197    0.5093    0.0079   4151.7875   3138. ⋯
         intercept_virginica   -0.4537    0.6572    0.0100   4324.9304   3128. ⋯
  coefficients_versicolor[1]    1.3010    0.6322    0.0096   4338.4762   3047. ⋯
  coefficients_versicolor[2]   -1.3414    0.4950    0.0077   4202.3218   3078. ⋯
  coefficients_versicolor[3]    0.8422    0.7394    0.0116   4069.5009   3179. ⋯
  coefficients_versicolor[4]    0.2813    0.7199    0.0113   4033.6926   3095. ⋯
   coefficients_virginica[1]    0.8265    0.6789    0.0100   4544.5867   3738. ⋯
   coefficients_virginica[2]   -0.7302    0.6302    0.0092   4687.5294   3260. ⋯
   coefficients_virginica[3]    2.4126    0.8284    0.0126   4325.6260   3296. ⋯
   coefficients_virginica[4]    2.7093    0.7620    0.0108   4929.5512   2554. ⋯
                                                               3 columns omitted

Quantiles
                  parameters      2.5%     25.0%     50.0%     75.0%     97.5% ⋯
                      Symbol   Float64   Float64   Float64   Float64   Float64 ⋯

        intercept_versicolor    0.0873    0.6619    1.0016    1.3607    2.0336 ⋯
         intercept_virginica   -1.7131   -0.9017   -0.4600   -0.0107    0.8378 ⋯
  coefficients_versicolor[1]    0.0611    0.8690    1.2992    1.7150    2.5497 ⋯
  coefficients_versicolor[2]   -2.3770   -1.6670   -1.3212   -1.0034   -0.4234 ⋯
  coefficients_versicolor[3]   -0.5649    0.3444    0.8497    1.3246    2.3456 ⋯
  coefficients_versicolor[4]   -1.1543   -0.1876    0.2794    0.7587    1.6952 ⋯
   coefficients_virginica[1]   -0.5080    0.3682    0.8238    1.2773    2.1707 ⋯
   coefficients_virginica[2]   -1.9374   -1.1675   -0.7336   -0.2995    0.5209 ⋯
   coefficients_virginica[3]    0.8167    1.8572    2.4096    2.9728    4.0142 ⋯
   coefficients_virginica[4]    1.2487    2.2088    2.6905    3.2251    4.2306 ⋯

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)

Looks good!

We can also use the corner function from MCMCChains to show the distributions of the various parameters of our multinomial logistic regression. The corner function requires MCMCChains and StatsPlots.

# Only plotting the first 3 coefficients due to a bug in Plots.jl
corner(
    chain,
    MCMCChains.namesingroup(chain, :coefficients_versicolor)[1:3];
)
# Only plotting the first 3 coefficients due to a bug in Plots.jl
corner(
    chain,
    MCMCChains.namesingroup(chain, :coefficients_virginica)[1:3];
)

Fortunately the corner plots appear to demonstrate unimodal distributions for each of our parameters, so it should be straightforward to take the means of each parameter’s sampled values to estimate our model to make predictions.

Making Predictions

How do we test how well the model actually predicts which of the three classes an iris flower belongs to? We need to build a prediction function that takes the test dataset and runs it through the average parameter calculated during sampling.

The prediction function below takes a Matrix and a Chains object. It computes the mean of the sampled parameters and calculates the species with the highest probability for each observation. Note that we do not have to evaluate the softmax function since it does not affect the order of its inputs.

function prediction(x::Matrix, chain)
    # Pull the means from each parameter's sampled values in the chain.
    intercept_versicolor = mean(chain, :intercept_versicolor)
    intercept_virginica = mean(chain, :intercept_virginica)
    coefficients_versicolor = [
        mean(chain, k) for k in MCMCChains.namesingroup(chain, :coefficients_versicolor)
    ]
    coefficients_virginica = [
        mean(chain, k) for k in MCMCChains.namesingroup(chain, :coefficients_virginica)
    ]

    # Compute the index of the species with the highest probability for each observation.
    values_versicolor = intercept_versicolor .+ x * coefficients_versicolor
    values_virginica = intercept_virginica .+ x * coefficients_virginica
    species_indices = [
        argmax((0, x, y)) for (x, y) in zip(values_versicolor, values_virginica)
    ]

    return species_indices
end;

Let’s see how we did! We run the test matrix through the prediction function, and compute the accuracy for our prediction.

# Make the predictions.
predictions = prediction(test_features, chain)

# Calculate accuracy for our test set.
mean(predictions .== testset[!, :Species_index])
0.9066666666666666

Perhaps more important is to see the accuracy per class.

for s in 1:3
    rows = testset[!, :Species_index] .== s
    println("Number of `", species[s], "`: ", count(rows))
    println(
        "Percentage of `",
        species[s],
        "` predicted correctly: ",
        mean(predictions[rows] .== testset[rows, :Species_index]),
    )
end
Number of `setosa`: 26
Percentage of `setosa` predicted correctly: 1.0
Number of `versicolor`: 26
Percentage of `versicolor` predicted correctly: 0.7692307692307693
Number of `virginica`: 23
Percentage of `virginica` predicted correctly: 0.9565217391304348

This tutorial has demonstrated how to use Turing to perform Bayesian multinomial logistic regression.

Back to top