【问题标题】:RuntimeError: Input type (torch.FloatTensor) and weight type (torch.cuda.FloatTensor) should be the same - PyTorchRuntimeError:输入类型(torch.FloatTensor)和权重类型(torch.cuda.FloatTensor)应该相同 - PyTorch
【发布时间】:2021-07-19 07:31:42
【问题描述】:

我正在尝试通过以下方式推动我的模式和数据、图像和标签在 GPU 上运行:

device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")

接着是:

count = 0
loss_list = []
iteration_list = []
accuracy_list = []
epochs = 30

for epoch in range(epochs):
    for i, (images, labels) in enumerate(trainloader):
            net = net.to(device)
            images.to(device)
            labels.to(device)

            optimizer.zero_grad()
            outputs = net(images)
            loss = criterion(outputs, labels)
            loss.backward()
            optimizer.step()

            count += 1

            if count % 50 == 0:
                correct = 0
                total = 0

                for i, (images, labels) in enumerate(testloader):
                    images.to(device)
                    labels.to(device)

                    outputs = net(images)
                    predicted = torch.max(outputs.data, 1)[1]
                    total += len(labels)
                    correct += (predicted == labels).sum()
                accuracy = 100 * correct / float(total)

                loss_list.append(loss.data)
                iteration_list.append(count)
                accuracy_list.append(accuracy)

                if count % 500 == 0:
                    print("Iteration: {} Loss: {} Accuracy: {} %".format(count, loss.data, accuracy))

我明确地将我的模型和数据推送到设备,但是我遇到了错误:

RuntimeError                              Traceback (most recent call last)
<ipython-input-341-361b906da73d> in <module>()
     12 
     13             optimizer.zero_grad()
---> 14             outputs = net(images)
     15             loss = criterion(outputs, labels)
     16             loss.backward()

4 frames
/usr/local/lib/python3.7/dist-packages/torch/nn/modules/conv.py in _conv_forward(self, input, weight, bias)
    394                             _pair(0), self.dilation, self.groups)
    395         return F.conv2d(input, weight, bias, self.stride,
--> 396                         self.padding, self.dilation, self.groups)
    397 
    398     def forward(self, input: Tensor) -> Tensor:

RuntimeError: Input type (torch.FloatTensor) and weight type (torch.cuda.FloatTensor) should be the same

我觉得我通过将模型和数据都推送到 GPU 来做正确的事情,但我不知道为什么它不起作用。有人知道出了什么问题吗?提前谢谢你。

【问题讨论】:

    标签: python pytorch


    【解决方案1】:

    您的权重保存在您的 gpu 上,但您的输入在您的 cpu 上。您可以通过以下方式更改:images.cuda()

    【讨论】:

    • 但是代码第9行中的这些“images.to(device)”已经将图像发送到设备
    • 我也对我的回答感到困惑。我的意思是这没有错,但似乎代码已经是正确的。也许他给了我们另一个版本代码的错误信息
    猜你喜欢
    • 1970-01-01
    • 2023-03-27
    • 2020-09-29
    • 2021-01-03
    • 2022-11-11
    • 2021-12-30
    • 2021-12-06
    • 2021-07-18
    • 2023-04-10
    相关资源
    最近更新 更多