TF2.2:从TensorFlow_Hub加载保存的模型失败,并返回`AttributeError:'_UserObject'对象没有属性'摘要'`

问题描述

系统信息: 巨蟒:3.6.9 TensorFlow:PIP提供的2.2.0 CPU包

问题:

我从tf-Hub获取https://tfhub.dev/google/imagenet/resnet_v2_50/classification/4?tf-hub-format=compressed,然后将其解压缩到新目录中。

wget https://storage.googleapis.com/tfhub-modules/google/imagenet/resnet_v2_50/feature_vector/4.tar.gz
mkdir test_pb
mv 4.tar.gz test_pb
cd test_pb
tar -xvf 4.tar.gz
rm 4.tar.gz
cd ..
./test.py

https://storage.googleapis.com/tfhub-modules/google/imagenet/resnet_v2_50/feature_vector/4.tar.gz是TF-Hub中https://tfhub.dev/google/imagenet/resnet_v2_50/feature_vector/4的特征向量预训练模型。

test.py是Python脚本,以下是独立代码:

#!/usr/bin/env python3
from __future__ import absolute_import, division, print_function, unicode_literals

import os
import tensorflow as tf

print(tf.__version__)

resnet50v2_save_path = os.path.join('.', "./test_pb/")

loaded1 = tf.keras.models.load_model(resnet50v2_save_path)
print("Load done")

print("Signatures: ", loaded1.signatures)

print("Type: ", type(loaded1))

print(loaded1.summary())

输出如下:

2.2.0
2020-06-12 20:29:07.677555: I tensorflow/core/platform/profile_utils/cpu_utils.cc:102] CPU Frequency: 1995455000 Hz
2020-06-12 20:29:07.678219: I tensorflow/compiler/xla/service/service.cc:168] XLA service 0x59eb130 initialized for platform Host (this does not guarantee that XLA will be used). Devices:
2020-06-12 20:29:07.678241: I tensorflow/compiler/xla/service/service.cc:176]   StreamExecutor device (0): Host, Default Version
Load done
Signatures:  _SignatureMap({})
Type:  <class 'tensorflow.python.saved_model.load.Loader._recreate_base_user_object.<locals>._UserObject'>
Traceback (most recent call last):
  File "./test.py", line 18, in <module>
    print(loaded1.summary())
AttributeError: '_UserObject' object has no attribute 'summary'

这就是提到的错误。

为什么?

Thx


解决方案

模型为纯SavedModel,缺少keras_metadata.pb文件,无法直接加载到Keras模型中。您必须像加载普通的SavedModel一样加载它,并将其包装在keras模型中,如下所示:

!wget https://storage.googleapis.com/tfhub-modules/google/imagenet/resnet_v2_50/feature_vector/4.tar.gz
!mkdir saved_model
!tar -xvf 4.tar.gz -C saved_model

import tensorflow as tf
import tensorflow_hub as hub

m = tf.keras.Sequential([hub.KerasLayer("saved_model", trainable=True),
    tf.keras.layers.Dense(10, activation='softmax')
])
m.build([None, 224, 224, 3])
m.summary()

# Model: "sequential"
# _________________________________________________________________
# Layer (type)                 Output Shape              Param #   
# =================================================================
# keras_layer (KerasLayer)     (None, 2048)              23564800  
# _________________________________________________________________
# dense (Dense)                (None, 10)                20490     
# =================================================================
# Total params: 23,585,290
# Trainable params: 23,539,850
# Non-trainable params: 45,440

相关文章