我编写了一个StftMax回归函数def softmax_1(x),它本质上采用了m x n矩阵,对矩阵求幂,然后对每个列的指数进行求和。

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))

把它转换成数据帧
DF_activation_1 = pd.DataFrame(softmax_1(scores).T,index=x,columns=["x","1.0","0.2"])

所以我想尝试制作一个版本的softmax函数,它接受转置后的版本并计算softmax函数
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"])

然后我得到这个错误:
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,)

当我转置并在np.sum方法中转换轴时,为什么不这样做呢?

最佳答案

改变

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


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

这意味着np.sum将返回一个形状(80, 1)的数组,而不是(80,),该数组将为除法正确广播。还要注意括号闭合的校正。

09-30 15:47
查看更多