【问题标题】:RuntimeError: Expected object of type torch.FloatTensor but found type torch.cuda.DoubleTensor for argument #2 'weight'RuntimeError:预期为 torch.FloatTensor 类型的对象,但为参数 #2 'weight' 找到了类型 torch.cuda.DoubleTensor
【发布时间】:2018-12-07 10:12:08
【问题描述】:

我一直在尝试重新训练模型,但不幸的是,过去 2 天我一直收到同样的错误。

你能帮我解决这个问题吗?

初步工作:

%matplotlib inline
%config InlineBackend.figure_format = 'retina'

import matplotlib.pyplot as plt
import numpy as np
import time

import torch
from torch import nn
from torch import optim
import torch.nn.functional as F
from torch.autograd import Variable
from torchvision import datasets, transforms
import torchvision.models as models
from collections import OrderedDict

数据集:

data_dir = 'flowers'
train_dir = data_dir + '/train'

data_dir = 'flowers'

train_transforms = transforms.Compose([transforms.Resize(224),
                                       transforms.RandomResizedCrop(224),
                                       transforms.RandomRotation(45),
                                       transforms.RandomHorizontalFlip(),
                                       transforms.ToTensor(),
                                       transforms.Normalize([0.485, 0.456, 0.406], 
                                                            [0.229, 0.224, 0.225])])


train_data = datasets.ImageFolder(train_dir, transform=train_transforms)

trainloader = torch.utils.data.DataLoader(train_data, batch_size=32, shuffle=True)

import json

with open('cat_to_name.json', 'r') as f:
    cat_to_name = json.load(f)

尝试使用预训练模型并仅训练分类器:

# Load a pretrained model
model = models.vgg16(pretrained=True)

# Keep the parameters the same
for param in model.parameters():
    param.requires_grad = False


# and final output 102, since tht we have 102 flowers. 
classifier = nn.Sequential(OrderedDict([            
                          ('fc1', nn.Linear(25088, 4096)), 
                          ('relu', nn.ReLU()),
                          ('fc3', nn.Linear(4096, 102)),
                          ('output', nn.LogSoftmax(dim=1))
                          ]))

# Replace model's old classifier with the new classifier
model.classifier = classifier

# Calculate the loss
criterion = nn.NLLLoss()
optimizer = optim.Adam(model.classifier.parameters(), lr=0.001)

model.to('cuda')

epochs = 1
print_every = 40
steps = 0

for e in range(epochs):
    running_loss = 0
    model.train()
   # model = model.double()
    for images, labels in iter(trainloader):
        steps += 1

        images.resize_(32, 3, 224, 224)          

        inputs = Variable(images.to('cuda'))
        targets = Variable(labels.to('cuda'))

        optimizer.zero_grad()

        # Forward and backward passes
        output = model.forward(images)
        loss = criterion(output, labels)
        loss.backward()
        optimizer.step()

        #running_loss += loss.data[0]
        running_loss += loss.item()

        if steps % print_every == 0:
            print("Epoch: {}/{}... ".format(e+1, epochs),
                  "Loss: {:.4f}".format(running_loss/print_every))

错误信息:

RuntimeError: 预期类型为 torch.FloatTensor 的对象,但发现类型为 torch.cuda.DoubleTensor 的参数 #2 weight

【问题讨论】:

  • 你能提供更多关于回溯的信息吗?
  • 我添加了整个代码。这有帮助吗?
  • 不,代码在哪一行中断?
  • 能否具体分配`model = model.to'cuda'`
  • 我现在就试试这个。

标签: neural-network pytorch torch


【解决方案1】:
  1. 如果您想在 pyTorch 中使用 gpu,您必须确保 both 操作流程(这是您的模型)和 数据被传输到 cuda 设备。

  2. 我的意思是(1整个工作流程,包括pre-trained modelcriterionclassifierinputs 都应该分配给 cuda 设备。

  3. 如果 (2) 不能简单地由 model.cuda() 保证,则可能需要手动对所有对象执行此操作,以便 确保内部权重和input-data 是 cuda float 类型的

希望对你有帮助。

【讨论】:

    【解决方案2】:

    您应该已将输入传递给前馈网络,但您已将图像传递给网络


    # Forward and backward passes
    output = model.forward(inputs)
    

    【讨论】:

      猜你喜欢
      • 2018-08-30
      • 1970-01-01
      • 2018-12-29
      • 1970-01-01
      • 2019-01-11
      • 2020-06-15
      • 2019-09-22
      • 2020-12-02
      • 2020-10-21
      相关资源
      最近更新 更多