深度学习框架Pytorch——学习笔记(二)线性回归
参考书籍《pytorch入门与实践》 进行实战练习,动手编写代码,了解每一个过程。
1.numpy和pytorch实现梯度下降法
2.设定初始值
3.求取梯度
4.在梯度方向上进行参数的更新
5. 实现线性回归
6. pytorch实现一个简单的神经网络
下面是线性回归的代码实现,备注中有说明
import torch as t
from torch.autograd import Variable as V
from matplotlib import pyplot as plt
t.manual_seed(1000)
# 设定初始值 随机产生
def get_fake_data(batch_size=8):
x = t.rand(batch_size, 1) * 20
y = x * 2 + (1 + t.randn(batch_size, 1)) * 3
return x, y
# x, y = get_fake_data()
# plt.scatter(x.squeeze().numpy(), y.squeeze().numpy())
# plt.show()
w = t.rand(1, 1, requires_grad = True)
b = t.zeros(1, 1, requires_grad = True)
lr = 0.001
for ii in range(8000):
x, y = get_fake_data()
# 计算图过程,可以理解是网络的计算图
y_pred = x.mm(w) + b.expand_as(y)
loss = 0.5 * (y_pred - y) ** 2
loss = loss.sum()
# 自动计算梯度
loss.backward()
# 参数进行更新
w.data.sub_(lr * w.grad.data)
b.data.sub_(lr * b.grad.data)
# 每次更新前需要将梯度清空
w.grad.data.zero_()
b.grad.data.zero_()
# 验证结果
if ii%1000 == 0:
x = t.arange(0, 20.0).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(w.data.squeeze(), b.data.squeeze())