Wikipedia has the following example code for softmax.
>>> import numpy as np
>>> z = [1.0, 2.0, 3.0, 4.0, 1.0, 2.0, 3.0]
>>> softmax = lambda x : np.exp(x)/np.sum(np.exp(x))
>>> softmax(z)
array([0.02364054, 0.06426166, 0.1746813 , 0.474833 , 0.02364054 , 0.06426166, 0.1746813 ])
When I run it, it runs successfully. I don't understand how to read the lambda
function. In particular, how can the parameter x
refer to an array element in the numerator and span all the elements in the denominator?
[Note: The question this question presumably duplicates is about lambdas
in general. This question is not necessarily about lambda
. It is about how to read the np
conventions. The answers by @Paul Panzer and @Mihai Alexandru-Ionut both answer my question. Too bad I can't check both simultaneously as answering the question.
To confirm that I understand their answers (and to clarify what my question was about):
x
is the entire array (as it should be since the array is passed as the argument).np.exp(x)
returns the array with each elementx[i]
replaced bynp.exp(x[i])
. Call that new arrayx_new
.x_new/np.sum(x_new)
divides each element ofx_new
by the sum ofx_new
.
]