def simple_loss(w1, w2, b): x, y_true = 2.0, 1.0 y_pred = w1 * x + w2 * x**2 + b return (y_pred - y_true)**2def partial_derivative(w1, w2, b, param='w1', h=1e-6): if param == 'w1': return (simple_loss(w1+h, w2, b) - simple_loss(w1-h, w2, b)) / (2*h) elif param ==
'w2': return (simple_loss(w1, w2+h, b) - simple_loss(w1, w2-h, b)) / (2*h) else: return (simple_loss(w1, w2, b+h) - simple_loss(w1, w2, b-h)) / (2*h)w1, w2, b = 0.5, -0.1, 0.2print(f"当前损失: {simple_loss(w1, w2, b):.4f}")print(f"∂Loss/∂w1 = {partial_derivative(w1, w2, b, 'w1'):.4f}")print(f"∂Loss/∂w2 = {partial_derivative(w1, w2, b, 'w2'):.4f}") print(f"∂Loss/∂b = {partial_derivative(w1, w2, b, 'b'):.4f}")