11-pytorch-使用自己的数据集测试

b站小土堆pytorch教程学习笔记

python 复制代码
import torch
import torchvision
from PIL import Image
from torch import nn

img_path= '../imgs/dog.png'
image=Image.open(img_path)
print(image)
# image=image.convert('RGB')

transform=torchvision.transforms.Compose([torchvision.transforms.Resize((32,32)),
                                          torchvision.transforms.ToTensor()])
image=transform(image)
print(image.shape)

#加载模型
class Han(nn.Module):
    def __init__(self):
        super(Han, self).__init__()
        self.model = nn.Sequential(
            nn.Conv2d(3, 32, kernel_size=5, stride=1, padding=2),
            nn.MaxPool2d(2),
            nn.Conv2d(32, 32, kernel_size=5, stride=1, padding=2),
            nn.MaxPool2d(2),
            nn.Conv2d(32, 64, kernel_size=5, stride=1, padding=2),
            nn.MaxPool2d(2),
            nn.Flatten(),
            nn.Linear(64 * 4 * 4, 64),
            nn.Linear(64, 10)
        )

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

model=torch.load('../han_9.pth',map_location=torch.device('cpu'))#将GPU上运行的模型转移到CPU
print(model)

#对图片进行reshap
image=torch.reshape(image,(-1,3,32,32))

#将模型转化为测试类型
model.eval()
with torch.no_grad():#节约内存
    output=model(image)
print(output)


print(output.argmax(1))

<PIL.PngImagePlugin.PngImageFile image mode=RGB size=306x283 at 0x250B0006EE0>
torch.Size(3, 32, 32)
Han(
(model): Sequential(
(0): Conv2d(3, 32, kernel_size=(5, 5), stride=(1, 1), padding=(2, 2))
(1): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)
(2): Conv2d(32, 32, kernel_size=(5, 5), stride=(1, 1), padding=(2, 2))
(3): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)
(4): Conv2d(32, 64, kernel_size=(5, 5), stride=(1, 1), padding=(2, 2))
(5): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)
(6): Flatten(start_dim=1, end_dim=-1)
(7): Linear(in_features=1024, out_features=64, bias=True)
(8): Linear(in_features=64, out_features=10, bias=True)
)
)
tensor(\[-2.0302, -0.6256, 0.7483, 1.5765, 0.2651, 2.2243, -0.7037, -0.5262, -1.4401, -0.6563])
tensor(5)
Process finished with exit code 0

预测正确!

相关推荐
IT_陈寒几秒前
React项目实战经验分享:如何避免useEffect闭包陷阱导致的陈旧状态问题?
前端·人工智能·后端
愤怒火龙果3 分钟前
AIShield 靶场 WP
人工智能·网络安全·1024程序员节
云和数据.ChenGuang5 分钟前
Python 菜鸟入门:字典(dict)类型详解与 CRUD 实战案例
开发语言·人工智能·python
lucas_AI8 分钟前
SFT 之后再涨 54%:OPPO 给文档 OCR 装了个「错题本」,自博弈三轮把 CER 从 2.40 打到 1.11
人工智能
知行产研17 分钟前
湖州样板+团体标准,伯镭科技引领水泥矿山无人化
人工智能·科技·1024程序员节
全栈探索者21 分钟前
模型去哪下、放哪里、怎么选:Mac 玩 ComfyUI 的模型管理全图景(附我的实盘清单)
人工智能·macos·aigc·stablediffusion·comfyui
天远Date Lab24 分钟前
零信任架构实战:基于天远车型识别普通构建自动化二手车认证参数建档网关
人工智能·1024程序员节
天远数科26 分钟前
零信任架构实战:基于天远车型识别普通构建自动化汽车消费信贷车辆精细款型校验网关
人工智能·1024程序员节·工具分享
szxinmai主板定制专家28 分钟前
ARM 还是 x86?CODESYS 数控机床控制器选型、FPGA 取舍与实时性真相
arm开发·人工智能·fpga开发·zynq·1024程序员节·codesys
Godspeed Zhao1 小时前
具身智能系统概论——边缘计算和云端协调
人工智能·边缘计算·1024程序员节