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.3 3.3 1.0 versicolor
2 7.1 3.0 5.9 2.1 virginica
3 6.2 3.4 5.4 2.3 virginica
4 6.1 2.8 4.7 1.2 versicolor
5 5.9 3.0 5.1 1.8 virginica
6 6.8 3.2 5.9 2.3 virginica
7 5.5 4.2 1.4 0.2 setosa
8 5.0 3.5 1.3 0.3 setosa
9 4.9 3.1 1.5 0.2 setosa
10 5.4 3.0 4.5 1.5 versicolor
11 5.1 3.8 1.6 0.2 setosa
12 5.7 3.0 4.2 1.2 versicolor
13 6.0 3.0 4.8 1.8 virginica
14 5.0 3.4 1.6 0.4 setosa
15 7.6 3.0 6.6 2.1 virginica
16 6.3 2.9 5.6 1.8 virginica
17 7.7 3.8 6.7 2.2 virginica
18 5.0 3.6 1.4 0.2 setosa
19 6.5 2.8 4.6 1.5 versicolor
20 6.0 2.9 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 virginica 3
3 versicolor 2
4 virginica 3
5 virginica 3
6 versicolor 2
7 versicolor 2
8 versicolor 2
9 virginica 3
10 setosa 1
11 versicolor 2
12 versicolor 2
13 versicolor 2
14 setosa 1
15 versicolor 2
16 setosa 1
17 virginica 3
18 setosa 1
19 setosa 1
20 versicolor 2

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     = 18.02 seconds
Compute duration  = 15.27 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    0.9372    0.5101    0.0075   4699.3533   3310. ⋯
         intercept_virginica   -0.8625    0.6762    0.0094   5237.7467   2994. ⋯
  coefficients_versicolor[1]    1.2431    0.6317    0.0101   3925.2721   3200. ⋯
  coefficients_versicolor[2]   -1.5064    0.5318    0.0082   4222.4197   3365. ⋯
  coefficients_versicolor[3]    0.9330    0.7888    0.0117   4501.3715   3369. ⋯
  coefficients_versicolor[4]    0.2018    0.7255    0.0108   4551.3468   3266. ⋯
   coefficients_virginica[1]    0.9401    0.6753    0.0105   4181.7490   3529. ⋯
   coefficients_virginica[2]   -0.9279    0.6319    0.0094   4531.1590   3471. ⋯
   coefficients_virginica[3]    2.0981    0.8492    0.0115   5449.0609   3433. ⋯
   coefficients_virginica[4]    2.7085    0.7665    0.0108   5017.5679   3251. ⋯
                                                               3 columns omitted

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

        intercept_versicolor    0.0002    0.5787    0.9263    1.2800    1.9502 ⋯
         intercept_virginica   -2.2055   -1.3045   -0.8549   -0.4155    0.4819 ⋯
  coefficients_versicolor[1]    0.0316    0.8019    1.2474    1.6733    2.4697 ⋯
  coefficients_versicolor[2]   -2.6046   -1.8554   -1.4886   -1.1378   -0.5018 ⋯
  coefficients_versicolor[3]   -0.6230    0.4008    0.9336    1.4663    2.4807 ⋯
  coefficients_versicolor[4]   -1.2092   -0.2849    0.1974    0.6810    1.6344 ⋯
   coefficients_virginica[1]   -0.3542    0.4784    0.9388    1.3941    2.2864 ⋯
   coefficients_virginica[2]   -2.1512   -1.3621   -0.9342   -0.4915    0.3258 ⋯
   coefficients_virginica[3]    0.4219    1.5372    2.0850    2.6683    3.8012 ⋯
   coefficients_virginica[4]    1.2170    2.1735    2.7027    3.2339    4.2347 ⋯

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)