Paddle Inference(模型推理)实例分析

article/2025/8/22 17:13:17

一、Paddle推理生态

在这里插入图片描述


二、API说明

create_predictor 方法

# 根据 Config 构建预测执行器 Predictor
# 参数: config - 用于构建 Predictor 的配置信息
# 返回: Predictor - 预测执行器
paddle.inference.create_predictor(config: Config)

加载预测模型 - 非Combined模型

import paddle.inference as paddle_infer# 创建 config
config = paddle_infer.Config("./mobilenet_v1")# 根据 config 创建 predictor
predictor = paddle_infer.create_predictor(config)

加载预测模型 - Combined模型

# 引用 paddle inference 预测库
import paddle.inference as paddle_infer# 创建 config
config = paddle_infer.Config("./mobilenet_v2/__model__", "./mobilenet_v2/__params__")# 根据 config 创建 predictor
predictor = paddle_infer.create_predictor(config)

Predictor 类

Paddle Inference的预测器,由 create_predictor 根据 Config 进行创建。用户可以根据Predictor提供的接口设置输入数据、执行模型预测、获取输出等。

import numpy# 引用 paddle inference 预测库
import paddle.inference as paddle_infer# 创建 config
config = paddle_infer.Config("./mobilenet_v1")# 根据 config 创建 predictor
predictor = paddle_infer.create_predictor(config)# 获取输入 Tensor
input_names = predictor.get_input_names()
input_tensor = predictor.get_input_handle(input_names[0])# 从 CPU 获取数据,设置到 Tensor 内部
fake_input = numpy.random.randn(1, 3, 224, 224).astype("float32")
input_tensor.copy_from_cpu(fake_input)# 执行预测
predictor.run()# 获取输出 Tensor
output_names = predictor.get_output_names()
output_tensor = predictor.get_output_handle(output_names[0])# 释放中间Tensor
predictor.clear_intermediate_tensor()# 释放内存池中的所有临时 Tensor
predictor.try_shrink_memory()

三、自建线性模型推理

1、保存模型跟参数

'''
1.1.1 动态图存储载入体系
为提升框架使用体验,飞桨框架2.0将主推动态图模式,动态图模式下的存储载入接口包括:paddle.save  #训练调优,只保存参数
paddle.loadpaddle.jit.save  # 训练部署,保存模型与参数
paddle.jit.load
'''import numpy as np
import paddle
import paddle.nn as nn
from paddle.io import Dataset,DataLoader
import paddle.optimizer as optBATCH_SIZE = 4
BATCH_NUM = 4
EPOCH_NUM = 4IMAGE_SIZE = 16
CLASS_NUM = 10# define a random dataset
class RandomDataset(Dataset):def __init__(self,nums):super(RandomDataset,self).__init__()self.num_samples = numsdef __getitem__(self, idx):image = np.random.random([IMAGE_SIZE]).astype('float32')label = np.random.randint(0,CLASS_NUM-1,(1,)).astype('int64')return image,labeldef __len__(self):return self.num_samplesclass LinearNet(nn.Layer):def __init__(self):super(LinearNet,self).__init__()self.linear = paddle.nn.Linear(IMAGE_SIZE,700)self.linear1 = paddle.nn.Linear(700, CLASS_NUM)# @paddle.jit.to_static 保存模型跟参数的时候需要转化def forward(self, x):x = self.linear(x)return self.linear1(x)# create data loader
dataset = RandomDataset(BATCH_NUM*BATCH_SIZE)loader = DataLoader(dataset,batch_size=BATCH_SIZE)def train(layer,loader,loss_fn,opt):for epoch_id in range(EPOCH_NUM):for batch_id,(image,label) in enumerate(loader):print(image.shape)out = layer(image)loss = loss_fn(out,label)loss.backward()opt.step()opt.clear_grad()print("Epoch[{}/{}] batch {}: loss = {}".format(epoch_id,EPOCH_NUM,batch_id,np.mean(loss.numpy())))# create network
layer = LinearNet()
loss_fn = nn.CrossEntropyLoss()
adam = opt.Adam(learning_rate=0.001, parameters=layer.parameters())# train
train(layer, loader, loss_fn, adam)'''
动转静训练 + 模型&参数存储class LinearNet(nn.Layer):def __init__(self):super(LinearNet, self).__init__()self._linear = nn.Linear(IMAGE_SIZE, CLASS_NUM)@paddle.jit.to_staticdef forward(self, x):return self._linear(x)
'''
# from paddle.static import InputSpec
# save
path = "example.model/linear"
paddle.jit.save(layer, path)# save
path = "example.dy_model/linear"
paddle.jit.save(layer=layer,path=path,input_spec=[InputSpec(shape=[None, 784], dtype='float32')])还有一种方法如下:
net = to_static(model, input_spec=[InputSpec(shape=[None, 1, 28, 28], name='x')])
paddle.jit.save(net, 'inference_model/lenet')

结果如下:
在这里插入图片描述


2、Paddle Inference

# model_inference.py
import argparse
import numpy as np# 引用 paddle inference 预测库
import paddle.inference as paddle_inferdef main():args = parse_args()# 创建 configconfig = paddle_infer.Config(args.model_file, args.params_file)config.disable_gpu() # 使用cpu预测# 根据 config 创建 predictorpredictor = paddle_infer.create_predictor(config)# 获取输入的名称input_names = predictor.get_input_names()print("input_names:",input_names)input_handle = predictor.get_input_handle(input_names[0])# 设置输入fake_input = np.random.randn(args.batch_size, 16).astype("float32")input_handle.reshape([args.batch_size, 16])input_handle.copy_from_cpu(fake_input)# 运行predictorpredictor.run()# 获取输出output_names = predictor.get_output_names()output_handle = predictor.get_output_handle(output_names[0])output_data = output_handle.copy_to_cpu() # numpy.ndarray类型print("Output data size is {}".format(output_data.size))print("Output data shape is {}".format(output_data.shape))def parse_args():parser = argparse.ArgumentParser()parser.add_argument("--model_file", type=str,default='./example.model/linear.pdmodel', help="model filename")parser.add_argument("--params_file", type=str,default='./example.model/linear.pdiparams', help="parameter filename")parser.add_argument("--batch_size", type=int, default=1, help="batch size")return parser.parse_args()if __name__ == "__main__":main()'''
# 参数输入上面生成的linear模型
python model_inference.py --model_file ./example.model/linear.pdmodel --params_file ./example.model/linear.pdiparams --batch_size 2
'''

结果如下:
在这里插入图片描述


四、检测网络YOLOV3推理

总共需要三个文件:
1、Paddle模型和参数
2、utils.py包括图像的处理
3、infer_yolov3.py实现模型的推理

获取模型

wget https://paddle-inference-dist.bj.bcebos.com/Paddle-Inference-Demo/yolov3_r50vd_dcn_270e_coco.tgz
tar xzf yolov3_r50vd_dcn_270e_coco.tgz

# utils.py
import cv2
import numpy as np
from PIL import Image, ImageDrawdef resize(img, target_size):"""resize to target size"""if not isinstance(img, np.ndarray):raise TypeError('image type is not numpy.')im_shape = img.shapeprint(im_shape)im_size_min = np.min(im_shape[0:2])im_size_max = np.max(im_shape[0:2])im_scale_x = float(target_size) / float(im_shape[1])im_scale_y = float(target_size) / float(im_shape[0])img = cv2.resize(img, None, None, fx=im_scale_x, fy=im_scale_y)return imgdef normalize(img, mean, std):img = img / 255.0mean = np.array(mean)[np.newaxis, np.newaxis, :]std = np.array(std)[np.newaxis, np.newaxis, :]img -= meanimg /= stdreturn imgdef preprocess(img, img_size):mean = [0.485, 0.456, 0.406]std = [0.229, 0.224, 0.225]img = resize(img, img_size)img = img[:, :, ::-1].astype('float32')  # bgr -> rgbimg = normalize(img, mean, std)img = img.transpose((2, 0, 1))  # hwc -> chwimg = img[np.newaxis, :]print(img.shape)return img"""
def draw_bbox(img, result, threshold=0.5, save_name='res.jpg'):"""draw bbox"""draw = ImageDraw.Draw(img)for res in result:cat_id, score, bbox = res[0], res[1], res[2:]if score < threshold:continuexmin, ymin, xmax, ymax = bboxdraw.line([(xmin, ymin), (xmin, ymax), (xmax, ymax), (xmax, ymin),(xmin, ymin)],width=2,fill=(255, 0, 0))print('category id is {}, bbox is {}'.format(cat_id, bbox))img.save(save_name, quality=95)
"""def draw_box(img,result,threshold=0.5):for res in result:cat_id, score, bbox = res[0], res[1], res[2:]if score < threshold:continuexmin, ymin, xmax, ymax = int(bbox[0]),int(bbox[1]),int(bbox[2]),int(bbox[3])print('category id is {}, bbox is {}'.format(cat_id, bbox))cv2.rectangle(img,(xmin,ymax),(xmax,ymin),(255,0,0),2)cv2.namedWindow("detection",cv2.WINDOW_NORMAL)cv2.imshow("detection",img)cv2.waitKey(0)if __name__ == '__main__':img = cv2.imread('kite.jpg')# xmin, ymin, xmax, ymax = [216, 697, 268, 848]# cv2.rectangle(img, (xmin, ymax), (xmax, ymin), (255, 0, 0), 2)cv2.namedWindow("detection1",cv2.WINDOW_GUI_NORMAL)cv2.imshow("detection1",img)cv2.waitKey(0)

# -*- coding: utf-8 -*-
"""
Created on : 2021/6/3 21:10@author: Jeremy
"""import numpy as np
import argparse
import cv2
from PIL import Imagefrom paddle.inference import Config
from paddle.inference import create_predictorfrom PaddlePaddle.utils import preprocess, draw_bbox,draw_boxdef init_predictor(args):if args.model_dir != "":config = Config(args.model_dir)else:config = Config(args.model_file, args.params_file)config.enable_memory_optim()if args.use_gpu:config.enable_use_gpu(1000, 0)else:# If not specific mkldnn, you can set the blas thread.# The thread num should not be greater than the number of cores in the CPU.config.set_cpu_math_library_num_threads(4)config.enable_mkldnn()predictor = create_predictor(config)return predictordef run(predictor, img):# copy img data to input tensorinput_names = predictor.get_input_names()# print("input_names:",input_names)for i, name in enumerate(input_names):input_tensor = predictor.get_input_handle(name)input_tensor.reshape(img[i].shape)# print("input_tensor:",img[i].shape)input_tensor.copy_from_cpu(img[i].copy())# do the inferencepredictor.run()results = []# get out data from output tensoroutput_names = predictor.get_output_names()for i, name in enumerate(output_names):output_tensor = predictor.get_output_handle(name)output_data = output_tensor.copy_to_cpu()results.append(output_data)return resultsdef parse_args():parser = argparse.ArgumentParser()parser.add_argument("--model_file",type=str,default="./yolov3_coco/model.pdmodel",help="Model filename, Specify this when your model is a combined model.")parser.add_argument("--params_file",type=str,default="./yolov3_coco/model.pdiparams",help="Parameter filename, Specify this when your model is a combined model.")parser.add_argument("--model_dir",type=str,default="",help="Model dir, If you load a non-combined model, specify the directory of the model.")parser.add_argument("--use_gpu",type=int,default=0,help="Whether use gpu.")return parser.parse_args()if __name__ == '__main__':args = parse_args()img_name = 'kite.jpg'save_img_name = 'res.jpg'im_size = 608pred = init_predictor(args)img = cv2.imread(img_name)data = preprocess(img, im_size)scale_factor = np.array([im_size * 1. / img.shape[0], im_size * 1. / img.shape[1]]).reshape((1, 2)).astype(np.float32)im_shape = np.array([im_size, im_size]).reshape((1, 2)).astype(np.float32)result = run(pred, [im_shape, data,scale_factor])# img = Image.open(img_name).convert('RGB')# draw_bbox(img, result[0], save_name=save_img_name)draw_box(img,result[0])

http://chatgpt.dhexx.cn/article/SxWE5Lqc.shtml

相关文章

对于jetson nano 的docker部署jetson-inference等模型

对于Nvidia jetson nano来说是一款十分优秀的网络模型部署设备我对于nano来说也是学习了2个星期左右.这也是对我这一阶段做一个复习总结吧! 目录 烧录 下载jetson-inference dock镜像部署操作 跑个例程助助兴 找到函数接口进行调整 我用的是jetson nano a02 版本 是4GB内存…

LLM Inference 串讲

大家好&#xff0c;这里是 NewBeeNLP。 本文主要概述一下当前LLM 是如何生成文本及为什么对应的资源&#xff08;cost/latency)与prompt 和completion 都有关系。更佳阅读体验请点击原博客地址&#xff1a;LLM Inference 串讲(https://xv44586.github.io/2023/03/10/llm-inf/) …

【PaddleInferenceSharp】基于C#和Paddle Inference 部署PaddlePaddle模型

1. 项目介绍 Paddle Inference 是飞桨的原生推理库&#xff0c; 提供服务器端的高性能推理能力&#xff0c;直接基于飞桨的训练算子&#xff0c;因此它支持飞桨训练出的所有模型的推理&#xff1b;Paddle Inference 功能特性丰富&#xff0c;性能优异&#xff0c;针对不同平台不…

Paddle Inference C++ 依赖库安装(Windows)

Paddle Inference C 依赖库安装 1. 环境准备2. 下载安装库3. 设置环境变量4. VS C 项目配置 Paddle Inference 是飞桨的原生推理库&#xff0c; 提供服务器端的高性能推理能力。由于 Paddle Inference 能力直接基于飞桨的训练算子&#xff0c;因此它支持飞桨训练出的所有模型的…

ESIM:Enhanced LSTM for Natural Language Inference

原文链接&#xff1a;https://aclanthology.org/P17-1152.pdf ACL 2017 概述 对于自然语言推理任务&#xff0c;Bowman等人在2015年提出了一个大数据集&#xff0c;大多数工作就开始使用神经网络来对该任务进行训练。但作者认为序列模型的潜力还没有完全被挖掘&#xff0c;因此…

Triton Inference Server教程2

本文介绍如何编写一个config文件&#xff0c;config.pbtxt文件中包含哪些可以配置的参数&#xff0c;这些参数又会对triton server产生什么影响。 必须指定的模型参数 platform/backend&#xff1a;模型要在什么backend上面运行&#xff0c;可以用两种参数指定&#xff0c;一…

变分推断(variational inference)/variational EM

诸神缄默不语-个人CSDN博文目录 由于我真的&#xff0c;啥都不会&#xff0c;所以本文基本上就是&#xff0c;从0开始。 我看不懂的博客就是写得不行的博客。所以我只写我看得懂的部分。 持续更新。 文章目录 1. 琴生不等式2. 香农信息量/自信息I3. 信息熵4. 相对熵/KL散度/信…

Hugging Face - 推理(Inference)解决方案

每天&#xff0c;开发人员和组织都在使用 Hugging Face 平台上托管的模型&#xff0c;将想法变成概念验证&#xff08;proof-of-concept&#xff09;的 demo&#xff0c;再将 demo 变成生产级的应用。 Transformer 模型已成为广泛的机器学习&#xff08;ML&#xff09;应用的流…

变分推断(Variational Inference)解析

一、什么是变分推断 假设在一个贝叶斯模型中&#xff0c; x x x为一组观测变量&#xff0c; z z z为一组隐变量&#xff08;参数也看做随机变量&#xff0c;包含在 z z z中&#xff09;&#xff0c;则推断问题为计算后验概率密度 P ( z ∣ x ) P(z|x) P(z∣x)。根据贝叶斯公式…

深度学习-在线推断(Inference)技术

深度学习一般分为训练和在线推断两个部分&#xff0c;大家平时经常关注的多为训练阶段&#xff0c;也就是搜索和求解模型最优参数的阶段。而当模型参数已经求解出来&#xff0c;如何使用模型&#xff0c;以及在在线环境中部署模型&#xff0c;也是非常重要的。 一般会比较关注其…

推理(Inference)与预测(Prediction)

在机器学习的背景下&#xff0c;很多人似乎混淆了这两个术语。这篇文章将试图澄清我们所说的这两个词是什么意思&#xff0c;每一个词在哪里有用&#xff0c;以及它们是如何应用的。在这里&#xff0c;我将举几个例子来直观地理解两者之间的区别。 推理和预测这两个术语都描述…

嵌入式C语言自我修养:从芯片、编译器到操作系统(附送书籍)

关注星标公众号&#xff0c;不错过精彩内容 来源 | 宅学部落 最近&#xff0c;阅读了王工&#xff08;王利涛&#xff09;赠送的一本由他编著的书籍《嵌入式C语言自我修养》&#xff0c;感觉写的挺不错。今天分享一下这本书籍《嵌入式C语言自我修养》&#xff1a;从芯片、编译器…

进行嵌入式C语言编程调试的通用办法

总结了一下调试我们嵌入式C程序的一些基本的办法和思想&#xff0c;供大家学习参考&#xff1a; 打印日志&#xff1a;在代码中添加打印语句&#xff0c;输出变量值、函数调用等信息&#xff0c;以便在程序运行时观察程序执行情况。 断点调试&#xff1a;在代码中添加断点&…

linux c与c语言的区别吗,嵌入式c语言与c语言的区别

原标题:嵌入式c语言与c语言的区别 最广泛使用的系统编程语言是C语言,它是使用自由格式源代码的简单编程语言;它曾用于以前用汇编语言构建的应用程序中。嵌入式C是C语言的扩展,它在嵌入式系统中应用于编写嵌入式软件,那么二者之间究竟有什么差异呢? 一、启动过程 1. 通用c…

嵌入式C语言——常见面试题

1、描述一下gcc编译过程&#xff1f; gcc编译过程分为4步骤&#xff1a;预处理、编译、汇编、链接。 预处理&#xff1a;头文件包含、宏替换、条件编译、删除注释。编译&#xff1a;主要进行词法、语法、语义分析等等&#xff0c;检查无误后把预处理好的文件编译成汇编文件。…

c语言对嵌入式的作用是什么,关于嵌入式C语言它有些什么意义

描述 首先&#xff0c;在当前产业结构升级的大背景下&#xff0c;机械行业未来的自动化、智能化程度会越来越高&#xff0c;所以机械类相关专业的知识结构必然会不断得到丰富和发展&#xff0c;而学习编程语言对于机械类专业来说具有较为实际的意义&#xff0c;尤其是C语言。 机…

总结嵌入式C语言难点(2部分)

结构类型和对齐 C语言提供自定义数据类型来描述一类具有相同特征点的事务&#xff0c;主要支持的有结构体&#xff0c;枚举和联合体。其中枚举通过别名限制数据的访问&#xff0c;可以让数据更直观&#xff0c;易读&#xff0c;实现如下&#xff1a; 联合体的是能在同一个存储…

嵌入式c语言教程 题库 百度云,嵌入式c语言视频教程尚观主讲视频教程

嵌入式C语言培训-01C语言概述-01C语言概念-发展历史-特点.mp4 嵌入式C语言培训-01C语言概述-02C基本程序结构-第一个helloworld程序-Linux下编辑编译执行.mp4 嵌入式C语言培训-01C语言概述-03C语言第2个程序第3个程序.mp4 嵌入式C语言培训-01C语言概述-04C程序开发过程.mp4 嵌入…

《嵌入式C语言》C语言介绍及环境搭建

--最具价值的嵌入式C语言1 C语言简介 C语言是国际上广泛流行的高级语言&#xff0c;是在B语言的基础上发展起来的&#xff0c; 1970年&#xff0c; 美国贝尔实验室的D.M.Ritchie设计了B 语言, 并用于编写了第一个UNIX操作系统。 1973年&#xff0c; D.M.Ritchie 在B语言的基础…

嵌入式C语言深入篇之 —— 变量

新建一个物联网行业交流学习QQ群&#xff0c;感兴趣可加&#xff1a;928840648 CUT 变量 可执行程序存储区 当一个C/C原码文件被编译链&#xff08;比如gcc/g&#xff09;编译及链接成为可执行程序后&#xff0c;由4个段组成&#xff0c;分别是&#xff1a;代码段&#xff…