Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to specify the axis when using the softmax activation in a Keras layer?

The Keras docs for the softmax Activation states that I can specify which axis the activation is applied to. My model is supposed to output an n by k matrix M where Mij is the probability that the ith letter is symbol j.

n = 7 # number of symbols in the ouput string (fixed)
k = len("0123456789") # the number of possible symbols

model = models.Sequential()
model.add(layers.Dense(16, activation='relu', input_shape=((N,))))
...
model.add(layers.Dense(n * k, activation=None))
model.add(layers.Reshape((n, k)))

model.add(layers.Dense(output_dim=n, activation='softmax(x, axis=1)'))

The last line of code doesn't compile as I don't know how to correctly specify the axis (the axis for k in my case) for the softmax activation.

like image 875
RobertJoseph Avatar asked Aug 29 '17 19:08

RobertJoseph


People also ask

What is softmax activation keras?

softmax function Softmax converts a vector of values to a probability distribution. The elements of the output vector are in range (0, 1) and sum to 1. Each vector is handled independently. The axis argument sets which axis of the input the function is applied along.

Which of the following will use softmax as activation for the output layer?

You can use softmax if you have 2,3,4,5,... mutually exclusive labels. Using 2,3,4,... sigmoid outputs produce a vector where each element is a probability.

Is Softmax activation function linear?

Softmax is a non-linear activation function, and is arguably the simplest of the set.

What is the output of a Softmax activation function?

Softmax is an activation function that scales numbers/logits into probabilities. The output of a Softmax is a vector (say v ) with probabilities of each possible outcome. The probabilities in vector v sums to one for all possible outcomes or classes.


1 Answers

You must use an actual function there, not a string.

Keras allows you to use a few strings for convenience.

The activation functions can be found in keras.activations, and they're listed in the help file.

from keras.activations import softmax

def softMaxAxis1(x):
    return softmax(x,axis=1)

..... 
......
model.add(layers.Dense(output_dim=n, activation=softMaxAxis1))

Or even a custom axis:

def softMaxAxis(axis):
    def soft(x):
        return softmax(x,axis=axis)
    return soft

...
model.add(layers.Dense(output_dim=n, activation=softMaxAxis(1)))
like image 129
Daniel Möller Avatar answered Oct 15 '22 09:10

Daniel Möller