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

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

相关推荐
_Chipen21 分钟前
C++基础问题
开发语言·c++
止观止1 小时前
JavaScript对象创建9大核心技术解析
开发语言·javascript·ecmascript
2401_878624791 小时前
pytorch 自动微分
人工智能·pytorch·python·机器学习
阿捏利2 小时前
C Primer Plus 第6版 编程练习——第7章(上)
c语言·编程题·c primer plus
screenCui2 小时前
macOS运行python程序遇libiomp5.dylib库冲突错误解决方案
开发语言·python·macos
水龙吟啸2 小时前
从零开始搭建深度学习大厦系列-2.卷积神经网络基础(5-9)
人工智能·pytorch·深度学习·cnn·mxnet
linux kernel2 小时前
第七讲:C++中的string类
开发语言·c++
jz_ddk2 小时前
[实战]调频(FM)和调幅(AM)信号生成(完整C语言实现)
c语言·算法·信号处理
玩代码3 小时前
Java线程池原理概述
java·开发语言·线程池
泰勒疯狂展开3 小时前
Java研学-MongoDB(三)
java·开发语言·mongodb