pytorch将数据与模型都放到GPU上训练

默认是CPU,如果想要用GPU需要:

  1. 安装配置cuda,然后更新/下载支持gpu版本的pytorch,可以参考:https://blog.csdn.net/weixin_35757704/article/details/124315569

  2. 设置device:

    py 复制代码
    device = torch.device('cuda' if torch.cuda.is_available else 'cpu')

    然后将数据与模型后面都额外加上.to(device)即可

示例程序

py 复制代码
import torch
import torch.nn as nn


# 一个简单的模型
class LinearRegressionModel(nn.Module):
    def __init__(self, input_shape, output_shape):
        super(LinearRegressionModel, self).__init__()
        self.linear = nn.Linear(input_shape, output_shape)

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


def main():
    x_train = torch.randn(100, 4)  # 生成训练特征
    y_train = torch.randn(100, 1)  # 生成label
    model = LinearRegressionModel(x_train.shape[1], 1)
    optimizer = torch.optim.SGD(model.parameters(), lr=0.01)  # 优化函数
    criterion = nn.MSELoss()  # 损失函数
    for epoch in range(100):
        optimizer.zero_grad()
        outputs = model(x_train)
        loss = criterion(outputs, y_train)
        loss.backward()
        optimizer.step()


if __name__ == '__main__':
    main()

修改为GPU版本:

py 复制代码
import torch
import torch.nn as nn


# 一个简单的模型
class LinearRegressionModel(nn.Module):
    def __init__(self, input_shape, output_shape):
        super(LinearRegressionModel, self).__init__()
        self.linear = nn.Linear(input_shape, output_shape)

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


def main():
    # 1. 设置device
    device = torch.device('cuda' if torch.cuda.is_available else 'cpu')
    # 2. 数据与模型后都加 .to(device) 即可
    x_train = torch.randn(100, 4).to(device)  # 生成训练特征
    y_train = torch.randn(100, 1).to(device)  # 生成label
    model = LinearRegressionModel(x_train.shape[1], 1).to(device)  # next(transformer.parameters()).device

    optimizer = torch.optim.SGD(model.parameters(), lr=0.01)  # 优化函数
    criterion = nn.MSELoss()  # 损失函数
    for epoch in range(100):
        optimizer.zero_grad()
        outputs = model(x_train)
        loss = criterion(outputs, y_train)
        loss.backward()
        optimizer.step()


if __name__ == '__main__':
    main()

修改后:

  1. 查看变量的位置:可以使用x_train.device查看tensor变量的位置
  2. 查看模型的位置:可以使用next(model.parameters()).device查看模型的位置

注意:不在同一个位置上的变量之间无法计算,模型无法使用不在同一个位置的数据

相关推荐
化作星辰2 小时前
深度学习_原理和进阶_PyTorch入门(2)后续语法3
人工智能·pytorch·深度学习
希露菲叶特格雷拉特13 小时前
PyTorch深度学习笔记(二十)(模型验证测试)
人工智能·pytorch·笔记
NewsMash14 小时前
PyTorch之父发离职长文,告别Meta
人工智能·pytorch·python
领航猿1号1 天前
Pytorch 内存布局优化:Contiguous Memory
人工智能·pytorch·深度学习·机器学习
化作星辰1 天前
使用房屋价格预测的场景,展示如何从多个影响因素计算权重和偏置的梯度
pytorch·深度学习
kyle-fang1 天前
pytorch-张量
人工智能·pytorch·python
woshihonghonga1 天前
Dropout提升模型泛化能力【动手学深度学习:PyTorch版 4.6 暂退法】
人工智能·pytorch·python·深度学习·机器学习
Danceful_YJ1 天前
28. 门控循环单元(GRU)的实现
pytorch·python·深度学习
2401_836900331 天前
PyTorch图像分割训练全流程解析
pytorch·模型训练
三排扣1 天前
手搓transformer
pytorch·python·transformer