作业要求:
- 阅读线性反向传播,用python实现迭代过程
- 考虑重新计算贡献值的影响
实现
target_z = 150.0
e = 1e-5
w = 3.0
b = 4.0
z = 162.0
count = 0
while (abs(target_z - z) > e):
x = 2 * w + 3 * b
y = 2 * b + 1
z = x * y
delta_b = ((z - target_z) / ((2 * x + 3 * y) * 2))
delta_w = ((z - target_z) / ((2 * y) * 2))
w = w - delta_w
b = b - delta_b
count += 1
print("Iteration : %d -- w = %f, b = %f, z = %.8f, error = %.8f" % (count, w, b, z, abs(target_z - z)))
print("---------------------------------")
print("Total iteration times : %d" %(count))
print("w = %f, b = %f, z = %.8f, error = %.8f" % (w, b, z, abs(target_z - z)))
结果
Iteration : 1 -- w = 2.666667, b = 3.904762, z = 162.00000000, error = 12.00000000
Iteration : 2 -- w = 2.661519, b = 3.903263, z = 150.18140590, error = 0.18140590
Iteration : 3 -- w = 2.661517, b = 3.903263, z = 150.00004434, error = 0.00004434
Iteration : 4 -- w = 2.661517, b = 3.903263, z = 150.00000000, error = 0.00000000
---------------------------------
Total iteration times : 4
w = 2.661517, b = 3.903263, z = 150.00000000, error = 0.00000000
重新计算贡献值的作用
- 反向传播的迭代过程是在输出变量关于输入变量曲面上找到一条最快下降的路径,重新计算贡献值更接近梯度下降过程(步长无限小的情况下是理想梯度下降过程),故会收敛得更快。