tensorflow使用python对pb模型做预估

tensorflow中ckpt模型转成pb模型的代码:参考链接https://blog.youkuaiyun.com/dulingtingzi/article/details/90790282

但是为了使大家更容易明白,因为有些变量需要统一,这里针对下面的使用pb模型进行预估的代码,粘贴一下ckpt转pb模型:

import tensorflow as tf
import os
from tensorflow.contrib.layers import  flatten
from tensorflow.python.framework import graph_util
import tensorflow.contrib.slim as slim
import numpy as np

growth_rate = 6
depth = 50
compression = 0.5
weight_decay = 0.0001
nb_blocks = int((depth - 4) / 6)

def dense_net(img_input, num_classes, nb_blocks, growth_rate, weight_decay, compression, flag):
   ##自定义densenet代码
    return densenet(growth_rate,img_input,num_classes,weight_decay,nb_blocks,compression,flag)

def set_config():#设置GPU使用率# 控制使用率
    os.environ['CUDA_VISIBLE_DEVICES'] = '0'
    # 假如有16GB的显存并使用其中的8GB:
    gpu_options = tf.GPUOptions(per_process_gpu_memory_fraction=0.3)
    config = tf.ConfigProto(gpu_options=gpu_options)
    # session = tf.Session(config=config)
    return config
#下面是你自定义的模型
num_classes=2
#is_training = tf.placeholder(tf.bool, name='placeholder_is_training')
is_training = tf.constant(False, dtype=tf.bool)#下面的名字要和你一开始训练模型的时候是一致的
inputs = tf.placeholder(tf.float32, shape=[None,30, 280, 3], name='placeholder_x')
labels = tf.placeholder(tf.float32, shape=[None,num_classes], name='placeholder_y')
pred=dense_net(inputs, num_classes,nb_blocks, growth_rate,weight_decay,compression,is_training)

model_path="./version1/checkpoint/2_class.ckpt-1"#设置model的路径,因新版tensorflow会生成三个文件,只需写到数字前
cfg=set_config()

from tensorflow.python.saved_model import signature_constants, signature_def_utils, tag_constants, utils
save_path = './version1/model_pb/test'
with tf.Session(config=cfg) as sess:
    saver = tf.train.Saver()
    saver.restore(sess, model_path)
    print('ckpt loaded')
    #注意下面的inputs和outputs的名字要和后面的pb模型做预估保持一致
    model_signature = signature_def_utils.build_signature_def(inputs={"input": utils.build_tensor_info(inputs)},outputs={"pred": utils.build_tensor_info(pred)},method_name=signature_constants.PREDICT_METHOD_NAME)
    builder = tf.saved_model.builder.SavedModelBuilder(save_path)
    legacy_init_op = tf.group(tf.tables_initializer(), name='legacy_init_op')
    builder.add_meta_graph_and_variables(sess, [tag_constants.SERVING],clear_devices=True,signature_def_map={signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY:model_signature},legacy_init_op=legacy_init_op)
    builder.save()
    print('saved_model saved')

 

tensorflow使用pb模型做预估的代码:

import os
import math
import cv2
import numpy as np
import tensorflow as tf
from tensorflow.python.saved_model import signature_constants, signature_def_utils, tag_constants, utils
import matplotlib.pyplot as plt
from time import time

os.environ['CUDA_VISIBLE_DEVICES'] = '0'

def preprocessing_crop_batch(images, height=30, width=280,depth=3):#按照batch去处理图像
    bs = len(images)
    GAUGE = height
    img_canvas = np.zeros([bs, height, width, depth], dtype=np.float32)
    #img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    for i,img in enumerate(images):
       #####预处理代码块
    return img_canvas

sess = tf.Session()
m = tf.saved_model.loader.load(sess, tags=[tag_constants.SERVING], export_dir='./version1/model_pb/test/')
graph = tf.get_default_graph()
signature = m.signature_def
signature_key = tf.saved_model.signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY
input_tensor_name0 = signature[signature_key].inputs['input'].name#与之前转pb的时候的输入输出名字保持一致
output_tensor_name = signature[signature_key].outputs['pred'].name
x0 = tf.get_default_graph().get_tensor_by_name(input_tensor_name0)
y0 = tf.get_default_graph().get_tensor_by_name(output_tensor_name)

img_path = './images'
imgs = os.listdir(img_path)
imgs = list(map(lambda x : os.path.join(img_path, x), imgs))

bs = 8
img_batch = []
for i in range(bs):
    img_batch.append(cv2.imread(imgs[i]))

t0 = time()
img_preprocess= preprocessing_crop_batch(img_batch)
ans = sess.run(y0, {x0 : img_preprocess})
ans = np.argmax(ans, axis=1)
#ans = list(map(lambda x : x.decode(), ans))
t1 = time()

#plt.imshow(img[:,:,::-1])
print(ans)
print('seconds per frame %.2f ms' % ((t1-t0) * 1000 / bs))

 

<think>好的,用户让我介绍一下RKNN模拟器。首先,我需要确定用户对RKNN的了解程度。RKNN是Rockchip NPU的模型格式,用于在他们的芯片上运行神经网络。模拟器可能用于在开发阶段测试模型,而无需实际硬件。 接下来,用户可能是开发者,正在考虑使用Rockchip的NPU进行部署,或者遇到了在PC上测试模型的需求。他们可能想知道模拟器的功能、使用场景、限制以及如何开始使用。 需要覆盖几个关键点:RKNN的定义,模拟器的作用(比如模型转换、仿真运行),支持的功能(性能评估、精度分析),使用步骤,以及注意事项,比如与真实硬件的差异。 还要注意用户可能混淆RKNN工具链和模拟器,需要明确区分。另外,用户可能关心是否需要Rockchip的硬件来使用模拟器,或者是否完全可以在PC上运行。 需要确保结构清晰,分点说明,用例子帮助理解。同时提醒用户模拟器的限制,比如不支持硬件特定优化,性能数据可能不准确。最后,给出官方文档的建议,确保用户有进一步了解的渠道。</think>以下是对RKNN模拟器的分步说明: ### 1. RKNN基础概念 - **定义**:RKNN是Rockchip公司为其NPU(神经网络处理器)设计的专用模型格式,类似TensorFlow的`.pb`或PyTorch的`.pt` - **作用**:可将主流框架(TensorFlow/PyTorch等)训练的模型转换为NPU可执行的格式 - **硬件依赖**:面向Rockchip系列芯片(如RK3588/RK3399Pro) ### 2. RKNN模拟器核心功能 ``` [输入模型] → RKNN-Toolkit → [RKNN格式] → 模拟器运行 ``` - **离线验证**:无需实体设备即可验证模型转换的正确性 - **性能预估**:提供内存占用、理论算力等参考数据(精度约70-80%) - **精度分析**:支持逐层输出对比 - **量化仿真**:模拟8bit/16bit量化效果 ### 3. 典型使用场景 - **开发阶段**:在PC端快速验证模型转换流程 - **算法调优**:对比不同量化策略的影响 - **资源评估**:预测模型在NPU上的内存需求 - **异常排查**:定位模型转换过程中的算子不支持问题 ### 4. 使用流程示例 ```python from rknn.api import RKNN # 初始化模拟环境 rknn = RKNN(verbose=True) # 模型配置 rknn.config(target_platform='rk3588') # 加载原始模型 rknn.load_pytorch(model='resnet18.pth', input_size_list=[[3,224,224]]) # 转换模型 rknn.build(do_quantization=True) # 初始化模拟器 rknn.init_runtime(target='rk3588', device_id='simulator') # 运行推理 outputs = rknn.inference(inputs=[test_image]) ``` ### 5. 重要注意事项 - **功能限制**:不支持硬件级优化特性(如内存复用) - **性能偏差**:实际设备运行速度通常比模拟器快20-30% - **算子兼容**:部分自定义算子可能无法仿真 - **量化差异**:模拟器量化结果与实体芯片可能存在微小误差 建议配合Rockchip官方提供的`RKNN-Toolkit`开发套件使用,最新文档可通过访问Rockchip开发者社区获取。实际部署前仍需在实体设备上进行最终验证。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值