You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

多层神经网络log loss代价函数代码输出不符预期,求排查bug

多层神经网络Log Loss代价函数计算错误排查

你的compute_cost函数中的Log Loss公式存在括号与符号逻辑错误,导致计算结果偏离预期。

问题根源

标准二分类交叉熵(Log Loss)的计算公式为:
$$ \text{cost} = -\frac{1}{m} \sum_{i=1}^{m} \left[ y^{(i)} \log(a^{(i)}) + (1-y^{(i)}) \log(1-a^{(i)}) \right] $$

你的代码中错误地将公式组合为:

logloss = np.multiply((Y*(-1)) , (np.log(A2))- np.multiply( np.log(1 - A2),(1 - Y)))

展开后逻辑为:
$$ \text{logloss} = -Y \cdot \log(A2) + Y(1-Y) \cdot \log(1-A2) $$
这与标准公式的核心差异在于第二项的符号:标准公式要求减去$(1-Y)\log(1-A2)$,而你的代码中是加上$Y(1-Y)\log(1-A2)$,直接导致计算逻辑错误。

针对你提供的测试用例(Y全为1),理论上该错误不会影响结果,但实际输出为预期的一半,可能是代码执行过程中存在未提及的变量干扰,但核心公式错误必须修正。

修正后的代码

def compute_cost(A2, Y):
    """
    Computes the cost function as a log loss
    
    Arguments:
    A2 -- The output of the neural network of shape (1, number of examples)
    Y -- "true" labels vector of shape (1, number of examples)
    
    Returns:
    cost -- log loss
    
    """
    # Number of examples.
    m = Y.shape[1]
    
    ### START CODE HERE ### (~ 2 lines of code)
    print(f"{A2.shape}  {Y.shape}")
    # 正确Log Loss计算:将两个交叉熵项相加后整体取负
    logloss = - (np.multiply(Y, np.log(A2)) + np.multiply(1 - Y, np.log(1 - A2)))
    cost = (1/m) * np.sum(logloss)
    ### END CODE HERE ###

    assert(np.isscalar(cost))
    
    return cost

更简洁的等价写法:

cost = -np.sum(Y * np.log(A2) + (1 - Y) * np.log(1 - A2)) / m

验证结果

当A2全为0.5、Y全为1时,每个样本的损失为$-\log(0.5) \approx 0.6931$,平均后结果与预期值0.6931477703826823完全一致。

内容的提问来源于stack exchange,提问作者MZimmadKhan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.15 17:34:52