Skip to content

Instantly share code, notes, and snippets.

@aroraakshit
Forked from Hasil-Sharma/softmax.py
Created March 30, 2019 21:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aroraakshit/43346824cf7da80d34bda842a485375f to your computer and use it in GitHub Desktop.
Save aroraakshit/43346824cf7da80d34bda842a485375f 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