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

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

一、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
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Jeremy-Sky

你的鼓励是我的动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值