Np.sum for row axis not working in Numpy

I wrote a softmax regression function def softmax_1(x)that essentially takes in a matrix m x n, expresses the degree of the matrix, then sums the exponents of each column.

x = np.arange(-2.0, 6.0, 0.1)
scores = np.vstack([x, np.ones_like(x), 0.2 * np.ones_like(x)])
#scores shape is (3, 80)

def softmax_1(x):
    """Compute softmax values for each sets of scores in x."""
    return(np.exp(x)/np.sum(np.exp(x),axis=0))

Converting it to a DataFrame, I need to transpose

DF_activation_1 = pd.DataFrame(softmax_1(scores).T,index=x,columns=["x","1.0","0.2"])

So, I wanted to try and make a version of the softmax function, which takes in the transposed version and calculates the softmax function

scores_T = scores.T
#scores_T shape is (80,3)

def softmax_2(y):
    return(np.exp(y/np.sum(np.exp(y),axis=1)))

DF_activation_2 = pd.DataFrame(softmax_2(scores_T),index=x,columns=["x","1.0","0.2"])

Then I get this error:

Traceback (most recent call last):
  File "softmax.py", line 22, in <module>
    DF_activation_2 = pd.DataFrame(softmax_2(scores_T),index=x,columns=["x","1.0","0.2"])
  File "softmax.py", line 18, in softmax_2
    return(np.exp(y/np.sum(np.exp(y),axis=1)))
ValueError: operands could not be broadcast together with shapes (80,3) (80,) 

Why doesn't this work when I transpose and switch the axis in a method np.sum?

+4
source share
1 answer

Edit

np.exp(y/np.sum(np.exp(y),axis=1))

to

np.exp(y)/np.sum(np.exp(y),axis=1, keepdims=True)

, np.sum (80, 1), (80,), . .

+4

All Articles