【问题标题】:How to freeze a keras model in TensorFlow 2.0? (specifically freeze a saved model format to .pb format)如何在 TensorFlow 2.0 中冻结 keras 模型? (专门将保存的模型格式冻结为 .pb 格式)
【发布时间】:2022-01-19 16:28:57
【问题描述】:

谁能解释在 TensorFlow 2 中将 keras 模型(保存的模型格式)冻结为 .pb 格式的过程? 创建了一个示例 mobilenet keras 模型并以保存的模型格式将其保存到磁盘

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 
)

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

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

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

【问题讨论】:

    标签: python tensorflow keras protocol-buffers tensorflow2.0


    【解决方案1】:

    随着 tensorflow 2 的进步,冻结模型已更改为保存模型,您现在已经保存了模型,而不是单个 .pb 文件(graphdef):

    1. 权重
    2. GraphDef (.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)
    

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

    如何使用保存的模型

    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']
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-01-04
      • 2018-01-08
      • 2020-07-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-27
      • 1970-01-01
      相关资源
      最近更新 更多