简体   繁体   中英

Softmax function of 2d array

Hello guys i have the follown matrix of shape [5,3] and i would like to get the softmax function.

array([[340.        ,  59.33333333, 348.11111111],
       [292.5       ,  46.5       , 297.875     ],
       [301.14285714,  48.28571429, 307.71428571],
       [307.        ,  50.        , 319.28571429],
       [307.77777778,  48.44444444, 313.44444444]])

The name of the above matrix is e_l1, i tried this code i get a matrix but when i am trying to sum each row the result is not 1 so that means that my outcome is wrong.

e= np.exp(e_l1- np.max(e_l1))
S= np.sum(e,axis=0)
P= e/S

As result i get this:

 [[1.00000000e+00 9.99874329e-01 1.00000000e+00]
 [2.34969834e-21 2.66992811e-06 1.52312011e-22]
 [1.33216272e-17 1.59230195e-05 2.85681188e-18]
 [4.65888615e-15 8.84158760e-05 3.02892988e-13]
 [1.01406710e-14 1.86621235e-05 8.79949929e-16]]

and as result of the summation of the rows this:

[2.99987433e+00 2.66992811e-06 1.59230195e-05 8.84158763e-05

1.86621235e-05]

Does anybody know what happen here? I think the formula that i use is correct

It seems that you just used the wrong axis for your sum, because you are computing the probabilities for each row, you need to divide each element in the row by the sum of all elements within this same row

e = np.exp(e_l1- np.max(e_l1))
S = np.sum(e,axis=1)
P = e/np.expand_dims(S, 1)

print(P.sum(axis=1))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM