来自陈云 深度学习框架书中的练习,这本书不是很严谨易读不推荐购买
import torch as t
from torch.autograd import Variable as V
from matplotlib import pyplot as plt
from IPython import display
t.manual_seed(1000)
def get_fake_data(batch_size=8):
x = t.randn(batch_size, 1) * 20
y = x * 2 + (1 + t.randn(batch_size, 1)) * 3
return x, y
w = V(t.rand(1, 1), requires_grad=True)
b = V(t.zeros(1, 1), requires_grad=True)
print(f'start:w={w}')
lr = 0.0001
for ii in range(10000):
x, y = get_fake_data()
x, y = V(x), V(y)
y_pred = x.mm(w) + b.expand_as(y)
loss = 0.5 * (y_pred - y) ** 2
loss = loss.sum()
# print(f'loss={loss.data}')
loss.backward(retain_graph=True)
# 手动求导对比
dloss = 1
dy_pred = dloss * (y_pred - y)
dw = x.t().mm(dy_pred)
db = dy_pred.sum()
# print(f'dw={dw},db={db}')
# print(f'w.grad={w.grad.data},b.grad={b.grad.data}')
w.data.sub_(lr * w.grad.data)
b.data.sub_(lr * b.grad.data)
# print(f'w={w.data}')
# print('\n')
w.grad.data = t.zeros(1, 1)
b.grad.data = t.zeros(1, 1)
if ii % 1000 == 0:
display.clear_output(wait=True)
x = t.arange(0, 20, dtype=t.float).view(-1, 1)
y = x.mm(w.data) + b.data.expand_as(x)
plt.plot(x.numpy(), y.numpy())
x2, y2 = get_fake_data(batch_size=20)
plt.scatter(x2.numpy(), y2.numpy())
plt.xlim(0, 20)
plt.ylim(0, 41)
plt.show()
plt.pause(0.5)
print(f"w={w.data.data},b={b.data.data}")
第一次运行的时候w和b的值太大无法显示了,一开始我以为是autogard的问题,加上了一个手动求导对比,发现求导没有问题,看第一次更新,w更新的方向没有问题,但是更新的值超过了正值,怀疑是学习率太高(0.001),就相当于一个步子很大的人,想要到一条很近的线,只能反复横跳,离线越来越远,所以把学习率调成了0.0001,发现效果非常好,问题解决。