You can try to use np.apply_along_axis
, where you have to specify which axis to execute your code (in your case axis=1
).
Here's a working example:
In [1]: import numpy as np
In [2]: def softmax(x):
...: orig_shape = x.shape
...:
...: # Matrix
...: if len(x.shape) > 1:
...: softmax = np.zeros(orig_shape)
...: for i,col in enumerate(x):
...: softmax[i] = np.exp(col - np.max(col))/np.sum(np.exp(col - np.max(col)))
...: # Vector
...: else:
...: softmax = np.exp(x - np.max(x))/np.sum(np.exp(x - np.max(x)))
...: return softmax
...:
In [3]: def softmax_vectorize(x):
...: return np.exp(x - np.max(x))/np.sum(np.exp(x - np.max(x)))
...:
In [4]: X = np.array([[1, 0, 0, 4, 5, 0, 7],
...: [1, 0, 0, 4, 5, 0, 7],
...: [1, 0, 0, 4, 5, 0, 7]])
In [5]: print softmax(X)
[[ 2.08239574e-03 7.66070581e-04 7.66070581e-04 4.18260365e-02
1.13694955e-01 7.66070581e-04 8.40098401e-01]
[ 2.08239574e-03 7.66070581e-04 7.66070581e-04 4.18260365e-02
1.13694955e-01 7.66070581e-04 8.40098401e-01]
[ 2.08239574e-03 7.66070581e-04 7.66070581e-04 4.18260365e-02
1.13694955e-01 7.66070581e-04 8.40098401e-01]]
In [6]: print np.apply_along_axis(softmax_vecorize, axis=1, arr=X)
[[ 2.08239574e-03 7.66070581e-04 7.66070581e-04 4.18260365e-02
1.13694955e-01 7.66070581e-04 8.40098401e-01]
[ 2.08239574e-03 7.66070581e-04 7.66070581e-04 4.18260365e-02
1.13694955e-01 7.66070581e-04 8.40098401e-01]
[ 2.08239574e-03 7.66070581e-04 7.66070581e-04 4.18260365e-02
1.13694955e-01 7.66070581e-04 8.40098401e-01]]