pytorch实现线性回归

转大佬笔记

代码:

python 复制代码
# -*- coding: utf-8 -*-
# @Time    : 2023-07-14 14:57
# @Author  : yuer
# @FileName: exercise05.py
# @Software: PyCharm
import matplotlib.pyplot as plt
import torch

# x,y是3行1列的矩阵,所以在[]中要分为3个[]
x_data = torch.tensor([[1.0], [2.0], [3.0]])
y_data = torch.tensor([[2.0], [4.0], [6.0]])


class LinearModel(torch.nn.Module):
    def __init__(self):
        super(LinearModel, self).__init__()
        self.linear = torch.nn.Linear(1, 1)
        # 1,1分别代表x,y的维度(列数)

    def forward(self, x):
        y_pred = self.linear(x)
        return y_pred


model = LinearModel()
criterion = torch.nn.MSELoss(True)  # 计算loss
optimizer = torch.optim.Rprop(model.parameters(), lr=0.01)  # 计算最优w,b

epoch_list = []
loss_list = []

for epoch in range(100):
    y_pred = model(x_data)
    loss = criterion(y_pred, y_data)
    print(epoch, loss.item())
    epoch_list.append(epoch)
    loss_list.append(loss.item())

    optimizer.zero_grad()  # 清空梯度
    loss.backward()  # 反馈算梯度并更新
    optimizer.step()  # 更新w,b的值

print('w=', model.linear.weight.item())
print('b=', model.linear.bias.item())

x_test = torch.tensor([[4.0]])
y_test = model(x_test)
print('y_pred=', y_test)

plt.plot(epoch_list, loss_list)
plt.show()
相关推荐
BOF_dcb6 小时前
【无标题】
pytorch·深度学习·机器学习
Keep_Trying_Go10 小时前
文生图算法C4Synth: Cross-Caption Cycle-Consistent Text-to-Image Synthesis详解
人工智能·pytorch·深度学习·计算机视觉·文生图
Niuguangshuo11 小时前
# PyTorch 中 `nn.ModuleList` 详解
人工智能·pytorch·python
TonyLee01716 小时前
卷积操作记录(pytorch)
人工智能·pytorch·深度学习
其美杰布-富贵-李17 小时前
PyTorch Lightning 中 TorchMetrics
人工智能·pytorch·python·计算损失
whitelbwwww17 小时前
图像处理--pytorch
图像处理·人工智能·pytorch
kimi-22218 小时前
Transformer 模型中位置编码(Positional Encoding, PE)
pytorch·python·transformer
习习.y18 小时前
基于PyTorch的鲍鱼年龄线性回归
人工智能·pytorch·线性回归
三不原则18 小时前
AI 系统核心组件解析:TensorFlow/PyTorch/ONNX Runtime 怎么用?
人工智能·pytorch·tensorflow
Hello.Reader18 小时前
Flink ML LinearRegression 用 Table API 训练线性回归并输出预测值
大数据·flink·线性回归