agi*_*ver 3 gpu deep-learning pytorch
代码基本上是训练常用的 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())
Run Code Online (Sandbox Code Playgroud)
需要能够在不使用.cuda()
用于使用 GPU 进行训练的选项的情况下运行代码。需要在我的电脑上运行它。
如果需要,这里是源代码。
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)
Run Code Online (Sandbox Code Playgroud)
使用此构造,您的代码会自动使用适当的设备。
希望这可以帮助!
归档时间: |
|
查看次数: |
3600 次 |
最近记录: |