Skip to content

Softmax Regression Implementation from Scratch

Because softmax regression is so fundamental, we believe that you ought to know how to implement it yourself. Here, we limit ourselves to defining the softmax-specific aspects of the model and reuse the other components from our linear regression section, including the training loop.

julia
using Pkg;
Pkg.activate("../../d2lai")
using d2lai, Flux, Plots, Statistics
using Distributions
  Activating project at `/workspace/workspace/d2l-julia/d2lai`

The Softmax

Let's begin with the most important part: the mapping from scalars to probabilities. For a refresher, recall the operation of the sum operator along specific dimensions in a tensor, as discussed in :numref:subsec_lin-alg-reduction and :numref:subsec_lin-alg-non-reduction. Given a matrix X we can sum over all elements (by default) or only over elements in the same axis. The axis variable lets us compute row and column sums:

Computing the softmax requires three steps: (i) exponentiation of each term; (ii) a sum over each row to compute the normalization constant for each example; (iii) division of each row by its normalization constant, ensuring that the result sums to 1:

softmax(X)ij=exp(Xij)kexp(Xik).

The (logarithm of the) denominator is called the (log) partition function. It was introduced in statistical physics to sum over all possible states in a thermodynamic ensemble. The implementation is straightforward:

julia
function softmax(o)
    return exp.(o) ./ sum(exp.(o), dims = 1)
end
softmax (generic function with 1 method)
julia
X = rand(5, 2)
X_prob = softmax(X)
X_prob, sum(X_prob, dims = 1)
([0.18117506870593342 0.1320529047784991; 0.24739251918615013 0.2387184813952434; … ; 0.1465060090769004 0.14550354373976027; 0.20560534251721646 0.283534812827121], [1.0 0.9999999999999999])

The Model

We now have everything that we need to implement the softmax regression model. As in our linear regression example, each instance will be represented by a fixed-length vector. Since the raw data here consists of 28×28 pixel images, we flatten each image, treating them as vectors of length 784. In later chapters, we will introduce convolutional neural networks, which exploit the spatial structure in a more satisfying way.

In softmax regression, the number of outputs from our network should be equal to the number of classes. Since our dataset has 10 classes, our network has an output dimension of 10. Consequently, our weights constitute a 784×10 matrix plus a 1×10 row vector for the biases. As with linear regression, we initialize the weights W with Gaussian noise. The biases are initialized as zeros.

julia
struct SoftmaxRegressionScratch{A} <: d2lai.AbstractClassifier 
    w::AbstractArray
    b::AbstractArray
    args::A
end
function SoftmaxRegressionScratch(num_inputs::Int64, num_outputs::Int64, lr, sigma=0.01)
    w = rand(Normal(0, sigma), (num_outputs, num_inputs))
    b = zeros(num_outputs, 1)
    args = (num_inputs = num_inputs, num_outputs = num_outputs, lr = lr, sigma = sigma)
    SoftmaxRegressionScratch(w, b, args)
end

Flux.@layer SoftmaxRegressionScratch trainable=(w,b)

The code below defines how the network maps each input to an output. Note that we flatten each 28×28 pixel image in the batch into a vector using reshape before passing the data through our model.

julia
function d2lai.forward(model::SoftmaxRegressionScratch, x)
    softmax(model.w * x  .+ model.b)
end

The Cross-Entropy Loss

Next we need to implement the cross-entropy loss function (introduced in :numref:subsec_softmax-regression-loss-func). This may be the most common loss function in all of deep learning. At the moment, applications of deep learning easily cast as classification problems far outnumber those better treated as regression problems.

Recall that cross-entropy takes the negative log-likelihood of the predicted probability assigned to the true label. For efficiency we avoid Python for-loops and use indexing instead. In particular, the one-hot encoding in y allows us to select the matching terms in y^.

To see this in action we create sample data y_hat with 2 examples of predicted probabilities over 3 classes and their corresponding labels y. The correct labels are 0 and 2 respectively (i.e., the first and third class). Using y as the indices of the probabilities in y_hat, we can pick out terms efficiently.

julia
y = [1, 3]
y_hat = [[0.1 0.3 0.6]; [0.3 0.2 0.5]]' |> Matrix
getindex.(eachcol(y_hat), y)
2-element Vector{Float64}:
 0.1
 0.5

Now we can implement the cross-entropy loss function by averaging over the logarithms of the selected probabilities.

julia
function cross_entropy(y_pred, y)
    actual_class_prob = getindex.(eachcol(y_pred), y)
    return mean(-1*log.(actual_class_prob))
end

cross_entropy(y_hat, y)
1.4978661367769954
julia
function d2lai.loss(model::AbstractClassifier, y_pred, y)
    # cross entropy 
    actual_class_prob = getindex.(eachcol(y_pred), y .+ 1)
    return mean(-1*log.(actual_class_prob))
end

Training

We reuse the fit method defined in :numref:sec_linear_scratch to train the model with 10 epochs. Note that the number of epochs (max_epochs), the minibatch size (batch_size), and learning rate (lr) are adjustable hyperparameters. That means that while these values are not learned during our primary training loop, they still influence the performance of our model, both vis-à-vis training and generalization performance. In practice you will want to choose these values based on the validation split of the data and then, ultimately, to evaluate your final model on the test split. As discussed in :numref:subsec_generalization-model-selection, we will regard the test data of Fashion-MNIST as the validation set, thus reporting validation loss and validation accuracy on this split.

julia

function d2lai.fit_epoch(model::SoftmaxRegressionScratch, opt; train_dataloader = nothing, val_dataloader = nothing, gradient_clip_val = 0.)
    losses = (train_losses = [], val_losses = [], val_acc = [])
    state = Flux.setup(opt, model)
    for batch in train_dataloader
        gs = gradient(model) do m
            training_step(m, batch)
        end
        Flux.Optimise.update!(state, model, gs[1])
        train_loss = training_step(trainer.model, batch)
        push!(losses.train_losses, train_loss)
    end
    for batch in val_dataloader
        loss, acc = validation_step(trainer.model, batch)
        push!(losses.val_losses , loss)
        push!(losses.val_acc, acc)
    end
    return losses
end
julia
model = SoftmaxRegressionScratch(784, 10, 0.1)
opt = Descent(0.01)
data = d2lai.FashionMNISTData(; batchsize = 256, flatten = true)
trainer = Trainer(model, data, opt; max_epochs = 10)
d2lai.fit(trainer)
    [ Info: Train Loss: 0.9744505899322733, Val Loss: 0.9459513653103493, Val Acc: 0.75
    [ Info: Train Loss: 0.857556675666966, Val Loss: 0.701497704394115, Val Acc: 0.8125
    [ Info: Train Loss: 0.6600560679149684, Val Loss: 0.586742316206024, Val Acc: 0.875
    [ Info: Train Loss: 0.6611845959614387, Val Loss: 0.5228459546142031, Val Acc: 0.875
    [ Info: Train Loss: 0.719965036150105, Val Loss: 0.4808186144074479, Val Acc: 0.875
    [ Info: Train Loss: 0.7226191125527701, Val Loss: 0.4522466632336129, Val Acc: 0.875
    [ Info: Train Loss: 0.5812198798524878, Val Loss: 0.42927084792834885, Val Acc: 0.9375
    [ Info: Train Loss: 0.5280942875767, Val Loss: 0.41469051986271566, Val Acc: 0.875
    [ Info: Train Loss: 0.6031487317898956, Val Loss: 0.4031099984548729, Val Acc: 0.875
    [ Info: Train Loss: 0.6575735590717978, Val Loss: 0.39428948561702787, Val Acc: 0.875
(SoftmaxRegressionScratch{@NamedTuple{num_inputs::Int64, num_outputs::Int64, lr::Float64, sigma::Float64}}([0.0012527126549554087 -0.003995983014698948 … 0.00024316815799139098 -0.010835742813268167; 0.010946987929790661 0.0007470507029887345 … 0.0037590020962039155 -0.001693456098599236; … ; -0.015148689989682912 0.00949050201467524 … -0.0029877327424057427 -0.00926534942949869; -0.002231184659765448 0.005786080370085332 … -0.011037629493372747 0.0038252662240478713], [0.021358851696887688; -0.010785774908621088; … ; -0.1387041380893096; -0.21438382105760126;;], (num_inputs = 784, num_outputs = 10, lr = 0.1, sigma = 0.01)), (val_loss = [0.5727241634986047, 0.5631760557383434, 0.6818548302699166, 0.589491698927436, 0.6573814641095722, 0.5667704315775226, 0.55887327005933, 0.6143094496749374, 0.535628902610172, 0.5898786127425825  …  0.6309338430578103, 0.6671986139663917, 0.5781126253850449, 0.5628897635900775, 0.6685902149846591, 0.6375603918786804, 0.5918919543446521, 0.6520028844786065, 0.5883492237570637, 0.39428948561702787], val_acc = [0.81640625, 0.8359375, 0.78125, 0.81640625, 0.78125, 0.81640625, 0.8359375, 0.80078125, 0.8203125, 0.796875  …  0.79296875, 0.78125, 0.8125, 0.828125, 0.7578125, 0.79296875, 0.79296875, 0.8125, 0.828125, 0.875]))

Summary

By now we are starting to get some experience with solving linear regression and classification problems. With it, we have reached what would arguably be the state of the art of 1960–1970s of statistical modeling. In the next section, we will show you how to leverage deep learning frameworks to implement this model much more efficiently.

Exercises

  1. In this section, we directly implemented the softmax function based on the mathematical definition of the softmax operation. As discussed in :numref:sec_softmax this can cause numerical instabilities.

  2. Test whether softmax still works correctly if an input has a value of 100.

  3. Test whether softmax still works correctly if the largest of all inputs is smaller than 100.

  4. Implement a fix by looking at the value relative to the largest entry in the argument.

  5. Implement a cross_entropy function that follows the definition of the cross-entropy loss function iyilogy^i.

  6. Try it out in the code example of this section.

  7. Why do you think it runs more slowly?

  8. Should you use it? When would it make sense to?

  9. What do you need to be careful of? Hint: consider the domain of the logarithm.

  10. Is it always a good idea to return the most likely label? For example, would you do this for medical diagnosis? How would you try to address this?

  11. Assume that we want to use softmax regression to predict the next word based on some features. What are some problems that might arise from a large vocabulary?

  12. Experiment with the hyperparameters of the code in this section. In particular:

  13. Plot how the validation loss changes as you change the learning rate.

  14. Do the validation and training loss change as you change the minibatch size? How large or small do you need to go before you see an effect?

julia