# Good Articles to learn how to implement a neural network 1

Tags: deep learning, Machine Learning, neural network# How to implement a neural network Intermezzo 2

This page is part of a 5 (+2) parts tutorial on how to implement a simple neural network model. You can find the links to the rest of the tutorial here:

## Softmax classification function

This intermezzo will cover:

- The softmax function
- Cross-entropy cost function

The previous intermezzo described how to do a classification of 2 classes with the help of the logistic function . For multiclass classification there exists an extension of this logistic function called the softmax function which is used in multinomial logistic regression . The following section will explain the softmax function and how to derive it.

1 2 3 4 5 6 7 8 |
# Python imports import numpy as np # Matrix and vector computation package import matplotlib.pyplot as plt # Plotting library from matplotlib.colors import colorConverter, ListedColormap # some plotting functions from mpl_toolkits.mplot3d import Axes3D # 3D plots from matplotlib import cm # Colormaps # Allow matplotlib to plot inside this notebook %matplotlib inline |

## Softmax function

The logistic output function described in the previous intermezzo can only be used for the classification between two target classes t=1

and t=0. This logistic function can be generalized to output a multiclass categorical probability distribution by the softmax function . This softmax function ς takes as input a C-dimensional vector z and outputs a C-dimensional vector y of real values between 0 and 1

. This function is a normalized exponential and is defined as:

The denominator ∑Cd=1ezd

acts as a regularizer to make sure that ∑Cc=1yc=1. As the output layer of a neural network, the softmax function can be represented graphically as a layer with C

neurons.

We can write the probabilities that the class is t=c

for c=1…C given input z

as:

Where P(t=c|z)

is thus the probability that that the class is c given the input z

.

These probabilities of the output P(t=1|z)

for an example system with 2 classes (t=1, t=2) and input z=[z1,z2] is shown in the figure below. The other probability P(t=2|z)

will be complementary.

1 2 3 |
# Define the softmax function def softmax(z): return np.exp(z) / np.sum(np.exp(z)) |

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
# Plot the softmax output for 2 dimensions for both classes # Plot the output in function of the weights # Define a vector of weights for which we want to plot the ooutput nb_of_zs = 200 zs = np.linspace(-10, 10, num=nb_of_zs) # input zs_1, zs_2 = np.meshgrid(zs, zs) # generate grid y = np.zeros((nb_of_zs, nb_of_zs, 2)) # initialize output # Fill the output matrix for each combination of input z's for i in range(nb_of_zs): for j in range(nb_of_zs): y[i,j,:] = softmax(np.asarray([zs_1[i,j], zs_2[i,j]])) # Plot the cost function surfaces for both classes fig = plt.figure() # Plot the cost function surface for t=1 ax = fig.gca(projection='3d') surf = ax.plot_surface(zs_1, zs_2, y[:,:,0], linewidth=0, cmap=cm.coolwarm) ax.view_init(elev=30, azim=70) cbar = fig.colorbar(surf) ax.set_xlabel('$z_1$', fontsize=15) ax.set_ylabel('$z_2$', fontsize=15) ax.set_zlabel('$y_1$', fontsize=15) ax.set_title ('$P(t=1|\mathbf{z})$') cbar.ax.set_ylabel('$P(t=1|\mathbf{z})$', fontsize=15) plt.grid() plt.show() |

### Derivative of the softmax function

To use the softmax function in neural networks, we need to compute its derivative. If we define ΣC=∑Cd=1ezdforc=1⋯C

so that yc=ezc/ΣC, then this derivative ∂yi/∂zj of the output y of the softmax function with respect to its input z

can be calculated as:

Note that if i=j

this derivative is similar to the derivative of the logistic function.

### Cross-entropy cost function for the softmax function

To derive the cost function for the softmax function we start out from the likelihood function that a given set of parameters θ

of the model can result in prediction of the correct class of each input sample, as in the derivation for the logistic cost function. The maximization of this likelihood can be written as:

The likelihood (θ|t,z)

can be rewritten as the joint probability of generating t and z given the parameters θ: P(t,z|θ)

. Which can be written as a conditional distribution:

Since we are not interested in the probability of z

we can reduce this to: (θ|t,z)=P(t|z,θ). Which can be written as P(t|z) for fixed θ. Since each ti is dependent on the full z, and only 1 class can be activated in the t

we can write

As was noted during the derivation of the cost function of the logistic function, maximizing this likelihood can also be done by minimizing the negative log-likelihood:

Which is the cross-entropy error function ξ

. Note that for a 2 class system output t2=1−t1 and this results in the same error function as for logistic regression: ξ(t,y)=−tclog(yc)−(1−tc)log(1−yc)

.

The cross-entropy error function over a batch of multiple samples of size n

can be calculated as:

Where tic

is 1 if and only if sample i belongs to class c, and yic is the output probability that sample i belongs to class c

.

#### Derivative of the cross-entropy cost function for the softmax function

The derivative ∂ξ/∂zi

of the cost function with respect to the softmax input zi

can be calculated as:

Note that we already derived ∂yj/∂zi

for i=j and i≠j

above.

The result that ∂ξ/∂zi=yi−ti

for all i∈C

is the same as the derivative of the cross-entropy for the logistic function which had only one output node.

This post at peterroelants.github.io is generated from an IPython notebook file. Link to the full IPython notebook file