我编写了一个softmax回归函数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))
将其转换为DataFrame时,我需要进行转置
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,)
,这将正确地进行广播运算。另外,请注意括号关闭的更正。