[deeplearning.ai]2_Improving Deep Neural Networks——Gradient Checking

本文介绍了一个简单的线性模型的前向传播和反向传播实现,并通过梯度检查验证了反向传播的正确性。该模型计算J(theta)=theta*x,并详细展示了如何计算损失函数关于参数theta的导数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >



# GRADED FUNCTION: forward_propagation

def forward_propagation(x, theta):
    """
    Implement the linear forward propagation (compute J) presented in Figure 1 (J(theta) = theta * x)
    """

    J = theta * x
    
    return J
# GRADED FUNCTION: backward_propagation

def backward_propagation(x, theta):
    """
    Computes the derivative of J with respect to theta (see Figure 1).
    """

    dtheta = x
    
    return dtheta
# GRADED FUNCTION: gradient_check

def gradient_check(x, theta, epsilon = 1e-7):
    
    thetaplus = theta + epsilon                               # Step 1
    thetaminus = theta - epsilon                              # Step 2
    J_plus = thetaplus * x                                  # Step 3
    J_minus = thetaminus * x                                 # Step 4
    gradapprox = (J_plus - J_minus)/(2 * epsilon)                              # Step 5

    # Check if gradapprox is close enough to the output of backward_propagation()
    grad = backward_propagation(x, theta)
    
    numerator = np.linalg.norm(grad - gradapprox)                               # Step 1'计算分母
    denominator = np.linalg.norm(grad) + np.linalg.norm(gradapprox)              # Step 2'计算分子
    difference = numerator / denominator                              # Step 3'
    
    if difference < 1e-7:
        print ("The gradient is correct!")
    else:
        print ("The gradient is wrong!")
    
    return difference




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值