Nah*_*zas 5 python machine-learning deep-learning pytorch
我在 pytorch 中创建了我的模型并且工作得非常好,但是当我只想测试一个图像时,batch_size=1总是返回第二类(在本例中是一只狗)。
我尝试使用批次 > 1 进行测试,在所有情况下这都有效!
架构:
model = models.densenet121(pretrained=True)
for param in model.parameters():
param.requires_grad = False
from collections import OrderedDict
classifier = nn.Sequential(OrderedDict([
('fc1', nn.Linear(1024, 500)),
('relu', nn.ReLU()),
('fc2', nn.Linear(500, 2)),
('output', nn.LogSoftmax(dim=1))
]))
model.classifier = classifier
Run Code Online (Sandbox Code Playgroud)
所以我的张量是 [batch, 3, 224, 224]
我尝试过:
resize
reshape
unsqueeze(0)
Run Code Online (Sandbox Code Playgroud)
当是一张图像时的响应始终是 [[0.4741, 0.5259]]
我的测试代码
from PIL import *
msize = 256
loader = transforms.Compose([transforms.Scale(imsize), transforms.ToTensor()])
def image_loader(image_name):
"""load image, returns cuda tensor"""
image = Image.open(image_name)
image = loader(image).float()
image = image.unsqueeze(0)
return image.cuda()
image = image_loader('Cat_Dog_data/test/cat/cat.16.jpg')
with torch.no_grad():
logits = model.forward(image)
ps = torch.exp(logits)
_, predTest = torch.max(ps,1)
print(ps) ## same value in all cases
imagen_mostrar = images[ii].to('cpu')
helper.imshow(imagen_mostrar,title=clas_perro_gato(predTest), normalize=True)
Run Code Online (Sandbox Code Playgroud)
第二个测试代码
andrea_data = datasets.ImageFolder(data_dir + '/andrea', transform=test_transforms)
andrealoader = torch.utils.data.DataLoader(andrea_data, batch_size=1, shuffle=True)
dataiter = iter(andrealoader)
images, labels = dataiter.next()
images, labels = images.to(device), labels.to(device)
ps = torch.exp(model.forward(images))
_, predTest = torch.max(ps,1)
print(ps.float())
Run Code Online (Sandbox Code Playgroud)
例如,如果我将batch_size更改为1,总是会返回一个张量,该张量表示这是一只狗[0.43,0.57]。
谢谢!
| 归档时间: |
|
| 查看次数: |
15267 次 |
| 最近记录: |