np.sum在Numpy中按行轴操作不工作

我编写了一个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,),这将正确地进行广播运算。另外,请注意括号关闭的更正。

Related Posts

L1-L2正则化的不同系数

我想对网络的权重同时应用L1和L2正则化。然而,我找不…

使用scikit-learn的无监督方法将列表分类成不同组别,有没有办法?

我有一系列实例,每个实例都有一份列表,代表它所遵循的不…

f1_score metric in lightgbm

我想使用自定义指标f1_score来训练一个lgb模型…

通过相关系数矩阵进行特征选择

我在测试不同的算法时,如逻辑回归、高斯朴素贝叶斯、随机…

可以将机器学习库用于流式输入和输出吗?

已关闭。此问题需要更加聚焦。目前不接受回答。 想要改进…

在TensorFlow中,queue.dequeue_up_to()方法的用途是什么?

我对这个方法感到非常困惑,特别是当我发现这个令人费解的…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注