import numpy as np
x_1 = 40.0 x_2 = 80.0
expected_output = 60.0
w_1 = np.full((2,3),0.5) w_2 = np.full((3,1),1.0)
def back_forward(x_1, x_2, w_1, w_2, expected_output, loop_num, print_num): for i in range(1,loop_num): z_1 = x_1 * w_1[0][0] + x_2 * w_1[1][0] z_2 = x_1 * w_1[0][1] + x_2 * w_1[1][1] z_3 = x_1 * w_1[0][2] + x_2 * w_1[1][2]
y_pred = z_1 * w_2[0][0] + z_2 * w_2[1][0] + z_3 * w_2[2][0] loss = 0.5 * (expected_output - y_pred) ** 2
if(i%print_num == 0): print(f"前向结果:{y_pred}") print(f"Loss:{loss}")
d_loss_predict_output = -(expected_output - y_pred)
d_loss_w_2 = np.multiply(d_loss_predict_output,[z_1, z_2, z_3]) d_loss_w_1 = np.multiply(np.multiply(w_2,[x_1,x_2]),d_loss_predict_output)
learning_rate = 1e-5 w_2 -= np.multiply(d_loss_w_2, learning_rate).reshape(3,1)
w_1 -= np.multiply(d_loss_w_1, learning_rate).reshape(2,3)
print(f"expected_output:{expected_output}") back_forward(x_1, x_2, w_1, w_2, expected_output, 100, 10)
|