我一直在尝试重新训练模型,但不幸的是,最近两天我一直遇到相同的错误。
您能帮忙一点吗?
初始工作:
%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
的预期对象,但发现参数#2torch.cuda.DoubleTensor
的类型为weight
答案 0 :(得分:0)
如果要在pyTorch中使用gpu,则必须确保两者 操作流程(这是您的模型)和数据已传输到cuda设备。
通过这个( 1 ),我的意思是,整个工作流程包括pre-trained model
, criterion
, classifier
和inputs
应全部分配给cuda设备。
如果model.cuda()
不能仅保证(2),则可能有必要对所有对象进行手动操作,以确保权重和输入数据均为cuda float类型。
希望有帮助。
答案 1 :(得分:0)
您应该已经将输入传递到前馈网络,但是您已经将图像传递到网络
void main() {
DivideBy *d = new DivideBy(2);
Truncate *t = new Truncate();
Compose<DivideBy, Truncate> *c1 = new Compose<DivideBy,Truncate>(d,t);
Compose<Truncate, DivideBy> *c2 = new Compose<Truncate, DivideBy>(t,d);
cout << (*c1)(100.7) << endl; // Prints 50.0
cout << (*c2)(11) << endl; // Prints 5
}