1. 调整线性回归模型停止条件以及y = 2*x + (5 + torch.randn(20, 1))中的斜率,训练一个线性回归模型;
"""
作者:Aidan
时间:18/01/2020
功能:线性回归
"""
import torch
import matplotlib.pyplot as plt
def main():
torch.manual_seed(10)
# 学习率
lr = 0.05
# 创建训练数据
x = torch.rand(20, 1) * 10
y = 5*x + (5 + torch.randn(20, 1)) # y值随机加入扰动
#构建线性回归模型
w = torch.randn((1), requires_grad=True)
b = torch.zeros((1), requires_grad=True)
for iteration in range(1000):
# 前向传播
wx = torch.mul(w, x)
y_pred = torch.add(wx, b)
# 计算损失函数MSE
loss = (0.5 * (y - y_pred)**2).mean()
# 反向传播
loss.backward()
#更新参数
b.data.sub_(lr * b.grad)
w.data.sub_(lr * w.grad)
# 清零张量的梯度 20191015增加
w.grad.zero_()
b.grad.zero_()
# 绘图
if iteration % 20 == 0:
plt.scatter(x.data.numpy(), y.data.numpy())
plt.plot(x.data.numpy(), y_pred.data.numpy(), 'r-', lw=5)
plt.text(2, 20, 'loss=%.4f' % loss.data.numpy(), fontdict={'size': 20, 'color': 'red'})
plt.xlim(1.5, 10)
plt.ylim(8, 45)
plt.title('Iteratiion:{}\nw:{} b:{}'.format(iteration, w.data.numpy(), b.data.numpy()))
plt.pause(0.5)
if loss.data.numpy() < 0.8:
break
if __name__ == '__main__':
main()
2. 计算图的两个主要概念是什么?
- 结点:表示数据,如向量,矩阵,张量。
- 边:表示运算,如加减乘除卷积等。
3. 动态图与静态图的区别是什么?
两者的搭建方式不同
-
动态图
- 运算与搭建同时进行,典型代表是pytorch
- 特点:灵活、易调节
-
静态图
- 先搭建图,后运算,典型代表TensorFlow
- 特点:高效、不灵活