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

预测正确!

相关推荐
code2cat7 分钟前
【随笔】Agent Skills如何按需加载:把技能说明放进分层目录
人工智能·ai agent·agent skills
AI 算法大模型备案~当当11 分钟前
各地备案数量怎么看:一份属地公告的认读与台账方法
java·数据库·人工智能
cu14312 分钟前
细谈GM8229的具体功能与其应用
c语言·c++·人工智能·单片机
Alson_Code14 分钟前
从0到1打造个人专属编程智能体
人工智能·langchain·ai编程
AI Data 搭子15 分钟前
阿里云发布 Agentic Storage 全矩阵产品:面向 AI 到 Agent 负载的全栈演进
人工智能·阿里云·云计算
论文复现现场16 分钟前
论文复现看到“RTX 3090 or higher”:显存、CUDA、batch size 与 OOM 怎么判断?
开发语言·pytorch·batch·cuda·rtx3090
2601_9510928317 分钟前
德国海外仓:跨境电商布局欧洲的核心枢纽与合规指南
大数据·人工智能·其他
百数平台29 分钟前
百数 AI 智能体怎么使用?基础操作与常见问题解答
人工智能
xingyuzhisuan31 分钟前
无限画布实操分享:基于 StarVerse-AI 制作连续国风漫剧分镜
人工智能
FII工业富联科技服务35 分钟前
从 AI for AI 到 AI Factory:大模型重构智能制造技术底座的四层逻辑
人工智能