Resnet C ++ 部署 pytorch功能测试(一)

说明

最近在研究分类模型如何部署C++,先拿Resnet50 来练一练手,文章将 分为多篇,这一篇主要验证一下pytorch 模型输出是正确的,为后续tensort RT 模型输出提供验证。

1 官方权重下载

https://download.pytorch.org/models/resnet50-19c8e357.pth

2 测试代码

python 复制代码
import torchvision.models as models
import os
import json
import torch
from PIL import Image
from torchvision import transforms
import matplotlib.pyplot as plt


def main():
    # device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
    device = torch.device("cuda:0")
    # device = torch.device("cpu")
    model = models.resnet50()
    model = model.cuda()
    # num_classes = 10  # 修改为你自己的类别数量
    # model.fc = torch.nn.Linear(model.fc.in_features, num_classes)
    data_transform = transforms.Compose(
        [transforms.Resize(256),
         transforms.CenterCrop(224),
         transforms.ToTensor(),
         transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])])
    # model.load_state_dict(torch.load('params.pth', map_location=device)) #
    model.load_state_dict(torch.load('resnet50-19c8e357.pth'))
    model.eval()
    img_path = 'data/fox.png'
    assert os.path.exists(img_path), "file: '{}' dose not exist.".format(img_path)
    img = Image.open(img_path)
    plt.imshow(img)
    # [N, C, H, W]
    img = data_transform(img)
    # expand batch dimension
    img = torch.unsqueeze(img, dim=0)
    with torch.no_grad():
        # predict class
        output = torch.squeeze(model(img.to(device))).cpu()
        predict = torch.softmax(output, dim=0)
        print(predict.shape)
        print(predict[270:280]) # 打印几个softmax之后的输出
        predict_cla = torch.argmax(predict).numpy() # 找出最大的序号
        print(predict_cla) # 打印出类别


if __name__ == '__main__':
    main()

3 测试图片

这是我找的几张图片


4 测试结果

跑一张狐狸的图片,输出序号277

查看预训练模型对应的类别编号

相关推荐
侃侃_天下1 天前
最终的信号类
开发语言·c++·算法
echoarts1 天前
Rayon Rust中的数据并行库入门教程
开发语言·其他·算法·rust
Aomnitrix1 天前
知识管理新范式——cpolar+Wiki.js打造企业级分布式知识库
开发语言·javascript·分布式
每天回答3个问题1 天前
UE5C++编译遇到MSB3073
开发语言·c++·ue5
伍哥的传说1 天前
Vite Plugin PWA – 零配置构建现代渐进式Web应用
开发语言·前端·javascript·web app·pwa·service worker·workbox
l12345sy1 天前
Day24_【深度学习—广播机制】
人工智能·pytorch·深度学习·广播机制
小莞尔1 天前
【51单片机】【protues仿真】基于51单片机的篮球计时计分器系统
c语言·stm32·单片机·嵌入式硬件·51单片机
小莞尔1 天前
【51单片机】【protues仿真】 基于51单片机八路抢答器系统
c语言·开发语言·单片机·嵌入式硬件·51单片机
liujing102329291 天前
Day03_刷题niuke20250915
c语言
我是菜鸟0713号1 天前
Qt 中 OPC UA 通讯实战
开发语言·qt