小土堆Pytorch笔记P32、33

编程基础很弱,需要机器学习,学习记录,按自己理解写的,希望以后能学懂吧,要是有大神看到还请赐教。

完整的模型验证套路

完整的模型验证(测试,demo)套路-利用已经训练好的模型,然后给它提供输入。

import torch
import torchvision.transforms
from PIL import Image
from torch import nn

img_path = "./test/dog.png"
# 读取图片
img = Image.open(img_path)
print(img)
# png图片格式四通道
img = img.convert('RGB')
transform = torchvision.transforms.Compose([
    torchvision.transforms.Resize((32, 32)),
    torchvision.transforms.ToTensor()
])
img = transform(img)
print(img.shape)


# img= img.reshape(())
class Tudui(nn.Module):
    def __init__(self):
        super(Tudui, self).__init__()
        self.model1 = nn.Sequential(
            nn.Conv2d(3, 32, 5, 1, 2),
            nn.MaxPool2d(2),
            nn.Conv2d(32, 32, 5, 1, 2),
            nn.MaxPool2d(2),
            nn.Conv2d(32, 64, 5, 1, 2),
            nn.MaxPool2d(2),
            nn.Flatten(),
            nn.Linear(64 * 4 * 4, 64),
            nn.Linear(64, 10)
        )

    def forward(self, x):
        x = self.model1(x)
        return x


model = torch.load("tudui_50.pth")
print(model)
img = torch.reshape(img, (1, 3, 32, 32))

# 将img输入到模型当中
#良好习惯
model.eval()
with torch.no_grad():
    output = model(img)
print(output)
print(output.argmax(1))

会发现报错,报错内容如下:

RuntimeError: Input type (torch.FloatTensor) and weight type (torch.cuda.FloatTensor) should be the same or input should be a MKLDNN tensor and weight is a dense tensor

原因:

模型是在GPU中训练的,然后这里的代码读取的tensor需要将其放入GPU中进行计算。

解决方法:

将读取的图片放入GPU中,在代码中添加如下:

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

最后一P看不懂我裂开了

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值