一、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.load
paddle.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 opt
BATCH_SIZE = 4
BATCH_NUM = 4
EPOCH_NUM = 4
IMAGE_SIZE = 16
CLASS_NUM = 10
# define a random dataset
class RandomDataset(Dataset):
def __init__(self,nums):
super(RandomDataset,self).__init__()
self.num_samples = nums
def __getitem__(self, idx):
image = np.random.random([IMAGE_SIZE]).astype('float32')
label = np.random.randint(0,CLASS_NUM-1,(1,)).astype('int64')
return image,label
def __len__(self):
return self.num_samples
class LinearNet(nn.Layer):
def __init__(self):
super(LinearNet,self).__init__()
self.linear = paddle.nn.Linear(IMAGE_SIZE,700)
self.linear1 = paddle.nn.Linear(700

本文围绕Paddle模型推理与部署展开。介绍了Paddle推理生态和相关API,如create_predictor方法、Predictor类。还阐述了自建线性模型推理的步骤,包括保存模型和参数,以及使用Paddle Inference。最后讲解了检测网络YOLOV3推理所需的文件和获取模型的方法。
最低0.47元/天 解锁文章
3595

被折叠的 条评论
为什么被折叠?



