在PyTorch中使用GPU进行模型训练可以极大地加速训练过程。以下是一些简单的步骤来使用GPU训练模型:
检查是否有可用的GPU设备:import torchif torch.cuda.is_available(): device = torch.device("cuda")else: device = torch.device("cpu")将模型和数据加载到GPU上:model.to(device)data.to(device)在训练循环中,将输入数据也传递到GPU上:for inputs, labels in dataloader: inputs, labels = inputs.to(device), labels.to(device) outputs = model(inputs) loss = criterion(outputs, labels) # 后续的训练步骤在优化器中指定使用GPU:optimizer = torch.optim.SGD(model.parameters(), lr=0.001)通过这些步骤,你就可以在PyTorch中使用GPU来训练模型了。使用GPU训练模型可以显著提高训练速度和效率。




