Help us understand the problem. What is going on with this article?

PyTorch で GPU を使う

More than 1 year has passed since last update.

説明

基本的に .cuda() を使う。
1. モデル(net)
2. 入力(inputs)
3. 正解データ(labels)
のそれぞれに対して作用させること。

def try_gpu(e):
    if torch.cuda.is_available():
        return e.cuda()
    return e

みたいなメソッドを定義しておいて、

import torch.nn as nn
import torch.nn.functional as F


class Net(nn.Module):
    def __init__(self):
        super().__init__()
        self.fc1 = nn.Linear(28 * 28, 128)
        self.fc2 = nn.Linear(128, 10)

    def forward(self, x):
        x = x.view(-1, 28 * 28)
        x = F.relu(self.fc1(x))
        x = self.fc2(x)
        return x

net = Net()
net = try_gpu(net)

とか

epochs = 100

for epoch in range(epochs):
    running_loss = 0.0
    for i, (inputs, labels) in enumerate(trainloader, 0):
        # zero the parameter gradients
        optimizer.zero_grad()
        inputs = try_gpu(inputs)
        labels = try_gpu(labels)

        # forward + backward + optimize
        outputs = net(inputs)
        loss = criterion(outputs, labels)
        loss.backward()
        optimizer.step()

        # print statistics
        running_loss += loss.item()
        if i % 100 == 99:
            print('[{:d}, {:5d}] loss: {:.3f}'
                    .format(epoch + 1, i + 1, running_loss / 100))
            running_loss = 0.0

print('Finished Training')

とかすると、自動的に CPU と GPU を切り替えられて良いかもしれない。
理想は、.cuda() を明示的にコードの中に入れないことなのだが、もっとよい方法があれば教えてください。

参考

PyTorchでMNIST

elm200
ソフトウェアエンジニア。Python と機械学習。
http://elm200.hatenablog.com/
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした