*Note: This is based on Andrew Ng’s course at Stanford University, but I culled information from other sources that I’ve attributed appropriately as well.*

Alright, we’ve talked about a one-vs-rest implementation for multi-class classification using logistic regression, now we’ll look at the other method, softmax regression. If you recall, we specified an additional parameter, *multi_class=’ovr’* while training a multi-class logistic regression model in *sklearn*. That’s because the default algorithm used is softmax regression, which is based on the multinomial distribution. In this post, I’ll try to explain how exactly this algorithm works. This post is pretty much all math, but hopefully I’m lucid enough to be understood.

This method is heavily based on statistical concepts, but I’ll try to go slow and explain everything one by one (this might turn out to be a long post).

## Recap: probability distributions

I can’t think of a better way to explain *what* a probability distribution is than the way Wikipedia has phrased it:

…a

probability density function(densityof a continuous random variable, is a function, whose value at any given sample (or point) in the sample space (the set of possible values taken by the random variable) can be interpreted as providing arelative likelihoodthat the value of the random variable would equal that sample.

Easy, right? It’s a function of a “random variable”, which gives the likelihood of that variable taking on specific values. There are several distributions–binomial, exponential, Gaussian, it’s a huge list. You may have encountered these in a probability class.

Let’s now look at one particular example, the Gaussian (this is just an example, really). The Gaussian is a function parameterized by its mean, , and its variance, . If we vary these parameters, we get different Gaussian distributions, as shown below:

Clearly, the Gaussian is a whole family of probability distributions. This is the case with other distributions as well. Let’s now generalize this.

## Exponential family distributions

There’s a class of distributions called **exponential family distributions**. A distribution is belongs to this class of distributions if it can be written in the form:

Let’s talk about all these variables:

- is called the
**natural parameter**. When proving that a certain distribution (such as the Gaussian) belongs to the exponential family, it becomes convenient to change the parameters of the original distribution to new parameters. The new natural parameters are different for different distributions. For example, in the Gaussian example, the original parameters were and , but the natural parameters are and . For those of you interested in the derivation, these notes from Princeton University provide it for a few common distributions. The natural parameter is also called the**canonical parameter**. - is the
**sufficient statistic**. This is one of those tricky terms that’s easy conceptually, but you need to read it over and over to get it. A sufficient statistic of a*sample*of data about a parameter is a*statistic*(like the mean and the variance) that provides as much as information as we can possibly get about that parameter from that data. As an example, say we use the sample mean to get an estimate the population mean. For example, given a sample of data distributed according to the Gaussian, it can be proved using maximum likelihood estimation that the sample mean is the best estimate of the population mean. Thus, for a Gaussian distribution, the sample mean is the sufficient statistic of the population mean. - is called the
**log partition function**or the**cumulant generating function**. The quantity normalizes the distribution so that the area under the curve is 1; that is, it sums (in case of a discrete distribution) or integrates (in case of a continuous distribution) to 1. This has the additional property that its first derivative yields the mean, and its second derivative yields the variance.

Many common distributions such as the Binomial, Gaussian, Weibull, and Poisson are examples of distributions that belong to the exponential family. More importantly to our discussion, the **multinomial distribution**, an extension of the Bernoulli distribution, also belongs to this class.

## Generalized Linear Models (GLMs)

Consider some models we’ve seen so far. In logistic regression, the output was either 0 or 1. Thus, in logistic regression, followed a Bernoulli distribution. Similarly, although not mentioned, the linear regression, which used a least-squares cost function, assumed that followed a Gaussian distribution.

More generally, we can have a model that assumes that the output variable follows a distribution that belongs to the exponential family of distributions. Such a model is called a **generalized linear model**. Apart from the distribution of the output variable belonging to the exponential family, GLMs have some other assumptions:

- Given input , we would like to predict (the
*expected value*of ). - The natural parameter . If, as in the Gaussian example, is a vector, then we have .

## Deriving the softmax regression model

Let’s now work towards a (generalized linear) model for multi-class classification. Since we have, in general, classes, our predictor variable follows a **multinomial** distribution, that is, .

To decide on parameters, we could choose parameters . However, this leads to a problem. To understand why, let’s first look at the Bernoulli distribution (the one we used for logistic regression), and then come back to the multinomial. Recall that

for logistic regression. We define this value as a parameter. Thus, we have:

The second equation follows from that there are only two possible outcomes, 0 and 1. Here, we have one parameter, , and

That is, the sum of the probability values for each possible output value should sum to 1. We could certainly do this for our multinomial model:

The issue is easier to see now. With all these parameters, we have

But now, the parameters aren’t independent. That is, one parameter is redundant, because we can get the last parameter by subtracting the sum of the others from 1. The fix is easy: we simply remove one parameter, and like the Bernoulli model, the last “parameter” is

Thus, we have parameters. Remember: these **aren’t** the natural parameters. We’ll work towards that. So now we need to get an exponential family distribution. Let’s work on , and define the *vectors* as follows:

Since is a vector, we use our usual notation and denote the th element by . With this framework in place, we can prove that the multinomial distribution is a member of the exponential family of distributions.

This is in the form of an exponential family distribution, with

Let’s go over the steps above:

- We formed the first step in the same way that we formed a similar equation for logistic regression. This is merely an extension, but it works very well. To check for yourself, notice that is 1 only for the th position, and 0 elsewhere. Hence, when you substitute any value, all the multiplicands except the th become 1 (because they’re raised to the 0th power).
- In the second step we simply used the equation for our parameters.
- In the third step, we simply used the property of logarithms:

- Next, we expanded the last term, and used the property of logarithms:

Now, note that . For convenience, let’s also define .

Before we proceed further, take a moment to notice how is a vector. As we discussed way back in GLMs, when is a vector, we have . But wait, this means that there’s not just one vector, there are *multiple* of them. In fact, we have of them, from through . For convenience, let’s throw in that last one as well, and define it as so that just as before. You should make sure you understand well that we have parameter vectors denoted by . In logistic regression (with 2 classes), we had only one (2 – 1 = 1), here (with classes) we have (but we defined an extra so we have of them).

Continuing from where we left off,

And so,

Substituting this in the second equation above gives us

Let’s look at what we have here. Given a vector with elements, we have a function that takes this vector and gives us *another vector*, , also with values, defined by the above equation, and subject to the conditions

.

This function is a generalization of the logistic function, and is called the **softmax function**. The case is similar to that of logistic regression, where we were actually performing *regression*, but cleverly choosing a bounded function. It’s harder to see in this case because it’s multidimensional.

Finally, let’s use the last assumption stated waay back in the GLMs section. You don’t need to scroll all the way up, I’ll restate it here: we assumed that

Each of these s is a vector of dimensions. And thus, our final softmax regression model is

The model will output a vector:

Notice that the above only outputs a dimension vector. We can find

.

With our model finally defined, all that’s left to do is figure out how to find the optimal values of the parameters .

## Finding the optimal parameter values

*Credits: I got stuck myself in the last part of this derivation, and this answer at CrossValidated helped me proceed.*

To find the optimal values of to fit the data, we use the now-familiar technique of maximum likelihood estimation. As always, we’ll start with the log-likelihood function. Here, we’ll just directly write it down without writing the likelihood first.

To find the derivative of this, let’s first find the derivative of the softmax function.

Let’s review the steps.

- We first employ the chain rule to make the computation significantly less confusing. To do this, we first find the derivative with respect to the power, and then with respect to .
- I then used the quotient rule for derivatives. This gets long because each term is long, but bear with me.

- In the next step, I introduce the
**Iverson notation**, denoted by , which is equal to if , and otherwise. To understand how I got the result there, note that we’re finding the (partial) derivative with respect to . If the exponent were anything else (that is, if the exponent were say and ), then the derivative of that term would be 0, because the term would be treated as a constant. You might want to re-read and make sure you understand why. The Iverson term there says that that term exists only when . - The next step is simply obtained by simplifying and splitting the big fraction into two smaller fractions, and canceling out common terms in the numerator and the denominator.
- Finally, we note that except the delta term, everything else is the softmax function, and use the concise notation to denote the softmax for the vector .

Now we have the derivative of the softmax function. If you look at the log-likelihood function again, you’ll see that we have a double summation and a log as well. Let’s take care of one summation and the logarithm now:

The steps here should be fairly easy to follow, it’s just a simple application of the chain rule. However, the original log-likelihood function also has a exponent. This really isn’t a problem:

At this point, let’s note that only when , and so we can use the Iverson notation again. This will be useful for us in a minute:

I’ve done quite a bit of shuffling of terms here, so let’s take things step by step.

- I first converted the to the Iverson notation.
- To make terms cleaner, I took the term outside the summations, since that term isn’t dependent on the summation variable .
- Similarly, the term is also not dependent on the summation variable, so it can be taken outside.
- Then, I multiplied the Iverson function throughout (using the distribution rule of multiplication), and split the summation into two summations.

You should work these steps out if this seems like a big jump. Next, let’s simplify some terms.

- Take the first summation and let’s intuitively understand what the two Iverson terms mean. The first term is 1 only if . The second one is 1 only if . Clearly, we can see that this term is 1 only when . Thus, this summation reduces to . Intuitively, what does this summation represent? If we sum up all these terms, effectively, we’re
*counting*the number of terms such that . Since these are two constant values, the summation doesn’t really matter, because either they’re equal, or they’re not. If they are, then the value of the summation is 1, otherwise, it’s 0. Why? Because is the*output variable*, which in multi-class classification is the class (remember, this is what we’re trying to do), and is what we’re finding the derivative with respect to. Obviously, both these values lie between 1 and . With this understanding, you should now see that this summation term is simply equal to . - The second summation has a very similar reasoning. can equal only one value of (because is constant and in the range of . This time, though, we’re sure that will definitely equal
*some*class, so we don’t require an Iverson term here: the summation will always equal 1.

And finally, computing the gradient of the log-likelihood function,

Unfortunately, we can’t really do much analytically here. It doesn’t lead us very far towards finding the maximum likelihood estimates. However, this expression is nice and simple, and we can use a computational method to find the minimum values of the parameters .

Instead of maximizing the log-likelihood, we can minimize the negative log-likelihood, and a simple way to do that is to use the familiar gradient descent. We found the gradient of the log-likelihood, so we just have to pick an initial guess and repeatedly move in the opposite direction of the gradient.

Let’s now recap what we’ve seen in this blog post.

## Summary

We’ve covered a lot of ground in this post. Let’s review.

- We started by saying that softmax regression was an alternate way of using logistic regression for multi-class classification. In fact, it’s a generalization of logistic regression.
- Then, we laid the foundations for generalized linear models (GLM) by briefly discussing exponential family distributions, of which the multinomial distribution is a member.
- We then saw that softmax regression is an example of a generalized linear model (GLM) using the multinomial distribution.
- Then, we started talking about the math and showed how softmax regression is, in fact, a GLM. We did this by first finding , and showing that each of our parameters are softmax functions, hence the name of the algorithm.
- We went on to define our hypothesis function for the model, which simply gave as output, a vector with the probabilities of the input being in each of the classes.
- Last, we tried finding the maximum likelihood estimates for the model. It was significantly longer than previous derivations, involving a new Iverson notation and the derivative of a rather complicated function. We formulated the log-likelihood function and found its derivative, and saw that it wasn’t steering us in the right direction, concluding that computational methods like gradient descent are better suited to this.