线性回归 Pytorch

笔记来自课程《PyTorch深度学习实践》Lecture5

利用pytorch进行深度学习的基本思路/步骤:

1. 准备数据集

2. 定义模型(使用class,继承自nn.Module)

3. 构建loss和optimizer(使用pytorch API)

4. Training cycle(forward,backward,update)

1. 准备数据集

import torch
x_data = torch.Tensor([[1.0], [2.0], [3.0]])
y_data = torch.Tensor([[2.0], [4.0], [6.0]])

x和y都是3 × 1 的Tensor

梯度下降:

2. 模型设计

class LinearModel(torch.nn.Module): 
    def __init__(self):
        super(LinearModel, self).__init__()
        self.linear = torch.nn.Linear(1, 1)
    def forward(self, x): 
        y_pred = self.linear(x) 
        return y_pred


model = LinearModel()

我们的模型必须继承自nn.Module,nn.Module是所有神经网络的base class。

成员方法__init__()和forword()必须重写。

关于init中的第二行代码,nn.Linear类含有2个成员张量:weight和bias:

关于forward函数中的第一行:Class nn.Linear has implemented the magic method __call__(), which enable the instance of the class can be called just like a function. Normally the forward() will be called.

最后一行,创建了一个LinearModel类的实例。

3. 构建Loss和Optimizer

criterion = torch.nn.MSELoss(size_average=False)
optimizer = torch.optim.SGD(model.parameters(), lr=0.01)

 4. Training Cycle

for epoch in range(100):
    y_pred = model(x_data)        # Forward: Predict
    loss = criterion(y_pred, y_data)         # Forward: Loss
    print(epoch, loss)

    optimizer.zero_grad()         # Notice !!!
    loss.backward()         # Backward: Autograd
    optimizer.step()        # Optimizer.step()

Notice:The grad computed by .backward() will be accumulated. So before backward, remember set the grad to ZERO!!!

5. Test Model

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

# Test Model
x_test = torch.Tensor([[4.0]]) y_test = model(x_test) 
print('y_pred = ', y_test.data)

输出结果为:

代码整体结构 be like:

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
您好!对于使用PyTorch进行线性回归,您可以按照以下步骤进行操作: 1. 导入必要的包和模块: ```python import torch import torch.nn as nn import torch.optim as optim ``` 2. 准备数据: ```python # 假设我们有一些输入特征 x 和对应的目标值 y # 这里使用随机生成的示例数据 x = torch.randn(100, 1) y = 3 * x + 2 + torch.randn(100, 1) * 0.5 ``` 3. 定义模型: ```python class LinearRegression(nn.Module): def __init__(self): super(LinearRegression, self).__init__() self.linear = nn.Linear(1, 1) # 输入维度为1,输出维度为1 def forward(self, x): out = self.linear(x) return out model = LinearRegression() ``` 4. 定义损失函数和优化器: ```python criterion = nn.MSELoss() # 均方误差损失函数 optimizer = optim.SGD(model.parameters(), lr=0.01) # 随机梯度下降优化器,学***率为0.01 ``` 5. 训练模型: ```python num_epochs = 100 # 迭代次数 for epoch in range(num_epochs): inputs = x labels = y # 前向传播 outputs = model(inputs) loss = criterion(outputs, labels) # 反向传播和优化 optimizer.zero_grad() loss.backward() optimizer.step() if (epoch+1) % 10 == 0: print('Epoch [{}/{}], Loss: {:.4f}'.format(epoch+1, num_epochs, loss.item())) ``` 6. 使用模型进行预测: ```python # 假设我们有一些新的输入特征 x_test x_test = torch.Tensor([[1.5], [2.5], [3.5]]) # 预测 with torch.no_grad(): predictions = model(x_test) print(predictions) ``` 这样,您就可以使用PyTorch进行简单的线性回归了。请注意,这只是一个简单的示例,实际应用中可能需要根据具体情况进行相应的修改和调整。希望对您有所帮助!如有任何问题,请随时提问。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值