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

预测正确!

相关推荐
武子康10 小时前
AI-调查研究-74-具身智能 机器人学习新突破:元学习与仿真到现实迁移的挑战与机遇
人工智能·程序人生·ai·职场和发展·系统架构·机器人·具身智能
练习两年半的工程师10 小时前
AWS TechFest 2025: 适合使用 Agentic AI 的场景、代理(Agents)应用的平衡之道、数据战略优先级矩阵、新治理模式
人工智能·云计算·aws
Monkey的自我迭代10 小时前
图像直方图
图像处理·人工智能·计算机视觉
Monkey的自我迭代10 小时前
图像金字塔---图像上采样下采样
人工智能·opencv·计算机视觉
colus_SEU10 小时前
【卷积神经网络详解与实例】4——感受野
人工智能·深度学习·计算机视觉·cnn
掘金一周10 小时前
凌晨零点,一个TODO,差点把我们整个部门抬走 | 掘金一周 9.11
前端·人工智能·后端
Sirius Wu10 小时前
私有化部署Ragflow的预训练模型
人工智能·python·语言模型·火山引擎
Cyan_RA910 小时前
SpringMVC 执行流程分析 详解(图解SpringMVC执行流程)
java·人工智能·后端·spring·mvc·ssm·springmvc
工藤学编程10 小时前
零基础学AI大模型之读懂AI大模型
人工智能
h_k1008611 小时前
如何使用 DeepSeek 帮助自己的工作?的技术文章大纲
人工智能