我正在尝试使用 pytorch 中预训练的 ResNet 模型计算前向传递。我无法创建小批量的 4-d 张量。有人可以告诉什么是正确的方法吗?
编辑:我更改了代码,现在可以使用。但是,我仍然认为应该有一种更有效的方法来做到这一点。
这是我的代码:
import pickle
import json
import shutil
import Image
import torchvision.models as models
import torchvision.transformers as transformers
from torch.autograd import Variable
from torch import Tensor
import glob
import torch
batch_size = 128
im_size = 299
normalize = transforms.Normalize(
mean=[0.485, 0.456, 0.406],
std=[0.229, 0.224, 0.225]
)
preprocess = transforms.Compose([
transforms.Scale(im_size),
transforms.CenterCrop(im_size),
transforms.ToTensor(),
normalize
])
model = models.resnet50(pretrained=True)
d_batch = make_batch(imgs, batch_size)
dtype = torch.FloatTensor
tmp = Variable(torch.randn(batch_size, 3, im_size, im_size).type(dtype), requires_grad=False)
for batch in tqdm(batches):
try:
data = [Image.open(img) for img in batch]
for idx, item in enumerate(data):
tmp[idx] = preprocess(item)
batch_result = model(tmp)
except Exception,x:
print x