gpt4 book ai didi

deep-learning - 需要在基于 python pytorch 的代码中将 GPU 选项更改为 CPU

转载 作者:行者123 更新时间:2023-12-04 02:52:11 24 4
gpt4 key购买 nike

该代码基本上训练通常的 MNIST 图像数据集,但它在 GPU 上进行训练。我需要更改此选项,以便代码使用我的笔记本电脑训练模型。我需要将第二行的 .cuda() 替换为 CPU 中的等效项。

我知道网上有很多关于如何使用 MNIST 数据库训练神经网络的示例,但这段代码的特别之处在于它使用 PID Controller (工业上常用)进行优化,我需要代码作为一部分我的研究。

net = Net(input_size, hidden_size, num_classes)
net.cuda()
net.train()
#Loss and Optimizer
criterion = nn.CrossEntropyLoss()
optimizer = PIDOptimizer(net.parameters(), lr=learning_rate, weight_decay=0.0001, momentum=0.9, I=I, D=D)
# Train the Model
for epoch in range(num_epochs):
train_loss_log = AverageMeter()
train_acc_log = AverageMeter()
val_loss_log = AverageMeter()
val_acc_log = AverageMeter()
for i, (images, labels) in enumerate(train_loader):
# Convert torch tensor to Variable
images = Variable(images.view(-1, 28*28).cuda())
labels = Variable(labels.cuda())

需要能够在不使用用于使用 GPU 进行训练的 .cuda() 选项的情况下运行代码。需要在我的电脑上运行它。

这里是源代码以备不时之需。

https://github.com/tensorboy/PIDOptimizer

非常感谢,社区!

最佳答案

最好升级到最新的 pytorch (1.0.x)。

使用最新的pytorch,管理“设备”更容易。

下面是一个简单的例子。

device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
#Now send existing model to device.
model_ft = model_ft.to(device)
#Now send input to device and so on.
inputs = inputs.to(device)

使用此构造,您的代码会自动使用适当的设备。

希望对您有所帮助!

关于deep-learning - 需要在基于 python pytorch 的代码中将 GPU 选项更改为 CPU,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54544986/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com