繁体   English   中英

如何在 TensorFlow 2.0 中冻结 keras model? (专门将一个保存的model格式冻结为.pb格式)

[英]How to freeze a keras model in TensorFlow 2.0? (specifically freeze a saved model format to .pb format)

谁能解释一下将 keras model(保存的 model 格式)冻结为 Z0734DD6997310708 的.pb 格式的过程? 创建了一个示例 mobilenet keras model 并将其以保存的 model 格式保存到磁盘

import tensorflow as tf
#Tensorflow version: 2.7.0
model = tf.keras.applications.mobilenet.MobileNet(
        include_top=True, 
        weights='imagenet', 
        input_tensor=None, 
        pooling=None,
        classes=1000
)
tf.keras.models.save_model( 
        model, 
        *path*, 
        overwrite=True, 
        include_optimizer=True, 
        save_format='pb', 
        signatures=None 
)

然后在另一个文件中,我需要加载 model 并将其冻结为 a.pb 格式

import tensorflow as tf
#Tensorflow version: 2.7.0
model = tf.keras.models.load_model( *path* )

############################################
# Freeze the model to a .pb format
############################################

With the advancement of tensorflow 2, freeze model has changed to saved model where instead of a single.pb file(graphdef), you now have saved model:

  1. 重量
  2. 图形定义 (.pb)
import tensorflow as tf
pretrained_model = tf.keras.applications.MobileNet()
mobilenet_save_path = 'weights/mobilenet'

# Save to saved model
tf.saved_model.save(pretrained_model, mobilenet_save_path)

注意:保存的 model 格式更快并产生完全相同的结果

如何使用已保存的 model

import tensorflow as tf
model = tf.saved_model.load('weights/mobilenet/')

# Grab this function to run saved model
infer = model.signatures['serving_default'] 

image = 'something.jpg'
img = tf.io.decode_jpeg(tf.io.read_file(image))
img_pre = tf.cast(img, tf.float32) 
img_pre = (img_pre / 127.5) - 1
img_pre = tf.image.resize(img_pre, [224, 224])
img_pre = tf.expand_dims(img_pre, axis=0)
preds = infer(img_pre)['outputs']

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM