首页 > 解决方案 > tensorflow-gpu ValueError:未知层:功能

问题描述

我正在尝试从 .h5 文件(由 mobilenetv2 训练)加载模型。

from tensorflow.keras import models
class Classifier(object):

    def __init__(self, model_path):
        self.model = models.load_model(model_path)

我的模型代码:

model_pre = keras.applications.MobileNetV2(
    input_shape=(224, 224, 3),
    include_top=False,
)

model_pre.trainable = False

last_output = model_pre.output

x = Flatten()(last_output)
x = Dense(3, activation='softmax')(x) 
model = tf.keras.Model(model_pre.input, x)

model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])

model.summary()

tensorflow-gpu == 2.2(与 2.3 相同的问题)python == 3.8.3

加载后我遇到了这个问题

2020-10-12 21:37:39.500606: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library cudart64_101.dll
Traceback (most recent call last):
  File "C:/Users/manos/projects/gesture_recognition/app.py", line 28, in <module>
    classifier = Classifier(CLASSIFIER_MODEL_PATH)
  File "C:\Users\manos\projects\gesture_recognition\classifier\gesture_classifier.py", line 9, in __init__
    self.model = models.load_model(model_path)
  File "C:\Users\manos\AppData\Roaming\Python\Python38\site-packages\tensorflow\python\keras\saving\save.py", line 184, in load_model
    return hdf5_format.load_model_from_hdf5(filepath, custom_objects, compile)
  File "C:\Users\manos\AppData\Roaming\Python\Python38\site-packages\tensorflow\python\keras\saving\hdf5_format.py", line 177, in load_model_from_hdf5
    model = model_config_lib.model_from_config(model_config,
  File "C:\Users\manos\AppData\Roaming\Python\Python38\site-packages\tensorflow\python\keras\saving\model_config.py", line 55, in model_from_config
    return deserialize(config, custom_objects=custom_objects)
  File "C:\Users\manos\AppData\Roaming\Python\Python38\site-packages\tensorflow\python\keras\layers\serialization.py", line 105, in deserialize
    return deserialize_keras_object(
  File "C:\Users\manos\AppData\Roaming\Python\Python38\site-packages\tensorflow\python\keras\utils\generic_utils.py", line 361, in deserialize_keras_object
    (cls, cls_config) = class_and_config_for_serialized_keras_object(
  File "C:\Users\manos\AppData\Roaming\Python\Python38\site-packages\tensorflow\python\keras\utils\generic_utils.py", line 321, in class_and_config_for_serialized_keras_object
    raise ValueError('Unknown ' + printable_module_name + ': ' + class_name)
ValueError: Unknown layer: Functional

我到处查看他们写的关于升级或降级 tensorflow-gpu 版本的这个问题的解决方案,但没有一个选项对我没有帮助

标签: pythontensorflowtensorflow2.0

解决方案


我在使用 import 保存模型时遇到了这个问题:from tensorflow.keras.callbacks import ModelCheckpoint但仅使用 import 加载保存的模型from keras.models import load_model。一旦我将其更改为from tensorflow.keras.models import load_model它工作正常。


推荐阅读