1499_作业2

1、调整线性回归模型停止条件以及y=2*x+(5+torch.randn(20,1))中的斜率,训练一个线性回归模型

import torch
import matplotlib.pyplot as plt
torch.manual_seed(10)

lr = 0.01  # 学习率
best_loss = float("inf")   #先定义为正无穷

# 创建训练数据
x = torch.rand(200, 1) * 10  # x data (tensor), shape=(20, 1)
y = 3*x + (5 + torch.randn(200, 1))  # y data (tensor), shape=(20, 1)

# 构建线性回归参数
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
    loss = (0.5 * (y - y_pred) ** 2).mean()

    # 反向传播
    loss.backward()

    #保存最低的损失和最好的斜率和截距w、b
    current_loss = loss.item()  #item()以列表的形式返回可遍历的(键, 值) 元组数组
    if current_loss < best_loss:
        best_loss = current_loss
        best_w = w
        best_b = b

    # 绘图
    # if iteration % 20 == 0:
    if loss.data.numpy() < 3:
        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, 40)
        plt.title("Iteration: {}\nw: {} b: {}".format(iteration, w.data.numpy(), b.data.numpy()))
        plt.pause(0.5)

        if loss.data.numpy() < 1:
            break
        # 更新参数
    b.data.sub_(lr * b.grad)
    w.data.sub_(lr * w.grad)
    # 清零张量的梯度
    # w.grad.zero_()
    # b.grad.zero_()

print(best_loss,'\n',best_w,'\n',best_b)

输出

0.8262379169464111 
 tensor([2.8406], requires_grad=True) 
 tensor([5.0676], requires_grad=True)

2、计算图的两个主要概念

计算图是用来描述运算的有向无环图,有两个主要的元素:结点(Node)和边(Edge),其中结点表示数据,如向量矩阵张量,边表示运算,如加减乘除卷积

《转载自深度之眼平台余霆嵩老师的课堂》

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值