代码基本上训练通常的MNIST图像数据集,但它在GPU上进行训练。我需要更改此选项,以便代码使用我的笔记本电脑训练模型。我需要将第二行中的.cuda()替换为CPU中的等价物。
我知道网上有很多关于如何使用MNIST数据库训练神经网络的例子,但这段代码的特殊之处在于,它使用PID控制器(工业中常用的)进行优化,我需要这些代码作为我研究的一部分。
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())需要能够在不使用.cuda()选项的情况下运行代码,该选项用于使用图形处理器进行培训。需要在我的电脑上运行它。
这是源代码,以备不时之需。
https://github.com/tensorboy/PIDOptimizer
非常感谢,社区!
发布于 2019-02-06 09:31:51
最好升级到最新的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)有了这个结构,你的代码就会自动使用适当的设备。
希望这能有所帮助!
https://stackoverflow.com/questions/54544986
复制相似问题