Last active
March 30, 2019 21:13
-
-
Save Hasil-Sharma/df9c8ed3591232a4afd646ca61ed4d27 to your computer and use it in GitHub Desktop.
Vectorized softmax calculation using numpy
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import numpy as np | |
def softmax(x): | |
""" Compute the softmax for each row of the input x | |
Arguments: | |
x -- A N dimensional veector or M X N dimensional numpy matrix. | |
Return: | |
x -- modified x in-place | |
""" | |
if len(x.shape) > 1: | |
#Matrix | |
max_element = np.max(x, axis = 1) | |
x -= max_element[:, None] #Broadcasting | |
x = np.exp(x) | |
x = x / np.sum(x, axis = 1)[:, None] | |
else: | |
#Vector | |
max_element = np.max(x) | |
x -= max_element | |
x = np.exp(x) | |
x = x / np.sum(x) | |
return x |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment