Skip to content

Instantly share code, notes, and snippets.

@Hasil-Sharma
Last active March 30, 2019 21:13
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save Hasil-Sharma/df9c8ed3591232a4afd646ca61ed4d27 to your computer and use it in GitHub Desktop.
Save Hasil-Sharma/df9c8ed3591232a4afd646ca61ed4d27 to your computer and use it in GitHub Desktop.
Vectorized softmax calculation using numpy
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