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

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

相关推荐
小白学大数据5 分钟前
现代Python爬虫开发范式:基于Asyncio的高可用架构实战
开发语言·爬虫·python·架构
渔舟小调15 分钟前
P19 | 前端加密通信层 pikachuNetwork.js 完整实现
开发语言·前端·javascript
不爱吃炸鸡柳17 分钟前
数据结构精讲:树 → 二叉树 → 堆 从入门到实战
开发语言·数据结构
网络安全许木17 分钟前
自学渗透测试第21天(基础命令复盘与DVWA熟悉)
开发语言·网络安全·渗透测试·php
t***54422 分钟前
如何在Dev-C++中使用Clang编译器
开发语言·c++
码界筑梦坊32 分钟前
93-基于Python的中药药材数据可视化分析系统
开发语言·python·信息可视化
Aurorar0rua42 分钟前
CS50 x 2024 Notes C - 05
java·c语言·数据结构
Cosmoshhhyyy1 小时前
《Effective Java》解读第49条:检查参数的有效性
java·开发语言
棋子入局1 小时前
C语言制作消消乐游戏(2)
c语言·开发语言·游戏
布谷歌2 小时前
常见的OOM错误 ( OutOfMemoryError全类型详解)
java·开发语言