0% found this document useful (0 votes)
25 views7 pages

C2 W2 SoftMax

Uploaded by

Sobhan Behuria
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
25 views7 pages

C2 W2 SoftMax

Uploaded by

Sobhan Behuria
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 7

C2_W2_SoftMax

July 5, 2024

1 Optional Lab - Softmax Function

In this lab, we will explore the softmax function. This function is used in both Softmax Regression
and in Neural Networks when solving Multiclass Classification problems.
[1]: import numpy as np
import matplotlib.pyplot as plt
plt.style.use('./deeplearning.mplstyle')
import tensorflow as tf
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense
from IPython.display import display, Markdown, Latex
from sklearn.datasets import make_blobs
%matplotlib widget
from matplotlib.widgets import Slider
from lab_utils_common import dlc
from lab_utils_softmax import plt_softmax
import logging
logging.getLogger("tensorflow").setLevel(logging.ERROR)
tf.autograph.set_verbosity(0)

Note: Normally, in this course,


∑ −1 the notebooks use the convention of starting counts
∑N
with 0 and ending with N-1, N i=0 , while lectures start with 1 and end with N, i=1 .
This is because code will typically start iteration with 0 while in lecture, counting 1 to
N leads to cleaner, more succinct equations. This notebook has more equations than is
typical for a lab and thus will break with the convention and will count 1 to N.

1.1 Softmax Function

In both softmax regression and neural networks with Softmax outputs, N outputs are generated
and one output is selected as the predicted category. In both cases a vector z is generated by a
linear function which is applied to a softmax function. The softmax function converts z into a
probability distribution as described below. After applying softmax, each output will be between
0 and 1 and the outputs will add to 1, so that they can be interpreted as probabilities. The larger
inputs will correspond to larger output probabilities.

1
The softmax function can be written:
e zj
aj = ∑N (1)
zk
k=1 e

The output a is a vector of length N, so for softmax regression, you could also write:
   z 
P (y = 1|x; w, b) e1
 ..  1  . 
a(x) =  .  = ∑N z  ..  (2)
e k
P (y = N |x; w, b) k=1 e zN

Which shows the output is a vector of probabilities. The first entry is the probability the input is
the first category given the input x and parameters w and b.
Let’s create a NumPy implementation:
[3]: def my_softmax(z):
ez = np.exp(z) #element-wise exponenial
sm = ez/np.sum(ez)
return(sm)

Below, vary the values of the z inputs using the sliders.


[4]: plt.close("all")
plt_softmax(my_softmax)

Canvas(toolbar=Toolbar(toolitems=[('Home', 'Reset original view', 'home', 'home'), ('Back', 'Ba

As you are varying the values of the z’s above, there are a few things to note: * the exponential in
the numerator of the softmax magnifies small differences in the values * the output values sum to
one * the softmax spans all of the outputs. A change in z0 for example will change the values of
a0-a3. Compare this to other activations such as ReLU or Sigmoid which have a single input and
single output.

1.2 Cost

The loss function associated with Softmax, the cross-entropy loss, is:


−log(a1 ), if y = 1.

..
L(a, y) = . (3)


−log(a ), if y = N
N

Where y is the target category for this example and a is the output of a softmax function. In
particular, the values in a are probabilities that sum to one. >Recall: In this course, Loss is for
one example while Cost covers all examples.
Note in (3) above, only the line that corresponds to the target contributes to the loss, other lines
are zero. To write the cost equation we need an ‘indicator function’ that will be 1 when the index

2
matches the target and zero otherwise.
{
1, if y == n.
1{y == n} ==
0, otherwise.

Now the cost is:


 
1 ∑m ∑
N { } e
(i)
zj
J(w, b) = −  1 y (i) == j log ∑ (i)
 (4)
m N
e zk
i=1 j=1 k=1

Where m is the number of examples, N is the number of outputs. This is the average of all the
losses.

1.3 Tensorflow

This lab will discuss two ways of implementing the softmax, cross-entropy loss in Tensorflow, the
‘obvious’ method and the ‘preferred’ method. The former is the most straightforward while the
latter is more numerically stable.
Let’s start by creating a dataset to train a multiclass classification model.
[5]: # make dataset for example
centers = [[-5, 2], [-2, -2], [1, 2], [5, -2]]
X_train, y_train = make_blobs(n_samples=2000, centers=centers, cluster_std=1.
,→0,random_state=30)

1.3.1 The Obvious organization

The model below is implemented with the softmax as an activation in the final Dense layer. The
loss function is separately specified in the compile directive.
The loss function is SparseCategoricalCrossentropy. This loss is described in (3) above. In this
model, the softmax takes place in the last layer. The loss function takes in the softmax output
which is a vector of probabilities.
[6]: model = Sequential(
[
Dense(25, activation = 'relu'),
Dense(15, activation = 'relu'),
Dense(4, activation = 'softmax') # < softmax activation here
]
)
model.compile(
loss=tf.keras.losses.SparseCategoricalCrossentropy(),
optimizer=tf.keras.optimizers.Adam(0.001),
)

3
model.fit(
X_train,y_train,
epochs=10
)

Epoch 1/10
63/63 [==============================] - 0s 1ms/step - loss: 1.0103
Epoch 2/10
63/63 [==============================] - 0s 985us/step - loss: 0.4756
Epoch 3/10
63/63 [==============================] - 0s 1ms/step - loss: 0.2118
Epoch 4/10
63/63 [==============================] - 0s 1ms/step - loss: 0.1183
Epoch 5/10
63/63 [==============================] - 0s 1ms/step - loss: 0.0846
Epoch 6/10
63/63 [==============================] - 0s 1ms/step - loss: 0.0685
Epoch 7/10
63/63 [==============================] - 0s 1ms/step - loss: 0.0595
Epoch 8/10
63/63 [==============================] - 0s 1ms/step - loss: 0.0531
Epoch 9/10
63/63 [==============================] - 0s 1ms/step - loss: 0.0489
Epoch 10/10
63/63 [==============================] - 0s 1ms/step - loss: 0.0455

[6]: <keras.callbacks.History at 0x70fae33486d0>

Because the softmax is integrated into the output layer, the output is a vector of probabilities.
[7]: p_nonpreferred = model.predict(X_train)
print(p_nonpreferred [:2])
print("largest value", np.max(p_nonpreferred), "smallest value", np.
,→min(p_nonpreferred))

[[4.65e-03 2.56e-03 9.64e-01 2.88e-02]


[9.98e-01 6.75e-04 8.14e-04 1.50e-04]]
largest value 0.99999726 smallest value 8.3186236e-10

1.3.2 Preferred

Recall from lecture, more stable and accurate results can be obtained if the softmax and loss are
combined during training. This is enabled by the ‘preferred’ organization shown here.
In the preferred organization the final layer has a linear activation. For historical reasons, the
outputs in this form are referred to as logits. The loss function has an additional argument:

4
from_logits = True. This informs the loss function that the softmax operation should be included
in the loss calculation. This allows for an optimized implementation.
[8]: preferred_model = Sequential(
[
Dense(25, activation = 'relu'),
Dense(15, activation = 'relu'),
Dense(4, activation = 'linear') #<-- Note
]
)
preferred_model.compile(
loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True), #<--␣
,→Note

optimizer=tf.keras.optimizers.Adam(0.001),
)

preferred_model.fit(
X_train,y_train,
epochs=10
)

Epoch 1/10
63/63 [==============================] - 0s 1ms/step - loss: 0.9516
Epoch 2/10
63/63 [==============================] - 0s 1ms/step - loss: 0.3630
Epoch 3/10
63/63 [==============================] - 0s 1ms/step - loss: 0.1602
Epoch 4/10
63/63 [==============================] - 0s 1ms/step - loss: 0.0934
Epoch 5/10
63/63 [==============================] - 0s 1ms/step - loss: 0.0698
Epoch 6/10
63/63 [==============================] - 0s 1ms/step - loss: 0.0581
Epoch 7/10
63/63 [==============================] - 0s 1ms/step - loss: 0.0502
Epoch 8/10
63/63 [==============================] - 0s 1ms/step - loss: 0.0447
Epoch 9/10
63/63 [==============================] - 0s 1ms/step - loss: 0.0407
Epoch 10/10
63/63 [==============================] - 0s 1ms/step - loss: 0.0378

[8]: <keras.callbacks.History at 0x70fae325c150>

Output Handling Notice that in the preferred model, the outputs are not probabilities, but can
range from large negative numbers to large positive numbers. The output must be sent through a

5
softmax when performing a prediction that expects a probability. Let’s look at the preferred model
outputs:
[9]: p_preferred = preferred_model.predict(X_train)
print(f"two example output vectors:\n {p_preferred[:2]}")
print("largest value", np.max(p_preferred), "smallest value", np.
,→min(p_preferred))

two example output vectors:


[[-2.05 -2.07 3.89 -0.25]
[ 6.44 1.58 -2.1 -2.55]]
largest value 15.827776 smallest value -5.897096
The output predictions are not probabilities! If the desired output are probabilities, the output
should be be processed by a softmax.
[10]: sm_preferred = tf.nn.softmax(p_preferred).numpy()
print(f"two example output vectors:\n {sm_preferred[:2]}")
print("largest value", np.max(sm_preferred), "smallest value", np.
,→min(sm_preferred))

two example output vectors:


[[2.59e-03 2.54e-03 9.79e-01 1.56e-02]
[9.92e-01 7.71e-03 1.95e-04 1.24e-04]]
largest value 0.9999993 smallest value 7.162702e-10
To select the most likely category, the softmax is not required. One can find the index of the largest
output using np.argmax().

[11]: for i in range(5):


print( f"{p_preferred[i]}, category: {np.argmax(p_preferred[i])}")

[-2.05 -2.07 3.89 -0.25], category: 2


[ 6.44 1.58 -2.1 -2.55], category: 0
[ 4.63 1.69 -1.58 -2.24], category: 0
[-1.52 4.3 -0.94 -1.71], category: 1
[-0.39 -2.92 5.51 -2.53], category: 2

1.4 SparseCategorialCrossentropy or CategoricalCrossEntropy

Tensorflow has two potential formats for target values and the selection of the loss defines which
is expected. - SparseCategorialCrossentropy: expects the target to be an integer corresponding to
the index. For example, if there are 10 potential target values, y would be between 0 and 9. -
CategoricalCrossEntropy: Expects the target value of an example to be one-hot encoded where the
value at the target index is 1 while the other N-1 entries are zero. An example with 10 potential
target values, where the target is 2 would be [0,0,1,0,0,0,0,0,0,0].

6
1.5 Congratulations!

In this lab you - Became more familiar with the softmax function and its use in softmax regres-
sion and in softmax activations in neural networks. - Learned the preferred model construction
in Tensorflow: - No activation on the final layer (same as linear activation) - SparseCategorical-
Crossentropy loss function - use from_logits=True - Recognized that unlike ReLU and Sigmoid,
the softmax spans multiple outputs.
[ ]:

[ ]:

You might also like