【问题标题】:I can't load my nn model that I've trained and saved我无法加载我训练并保存的 nn 模型
【发布时间】:2020-11-22 13:35:41
【问题描述】:

我使用迁移学习来训练模型。基本模型是efficientNet。 你可以阅读更多关于它here

from tensorflow import keras
from keras.models import Sequential,Model
from keras.layers import Dense,Dropout,Conv2D,MaxPooling2D, 
Flatten,BatchNormalization, Activation
from keras.optimizers import RMSprop , Adam ,SGD
from keras.backend import sigmoid

激活函数

类 SwishActivation(激活):

def __init__(self, activation, **kwargs):
    super(SwishActivation, self).__init__(activation, **kwargs)
    self.__name__ = 'swish_act'

def swish_act(x, beta = 1):
    return (x * sigmoid(beta * x))

from keras.utils.generic_utils import get_custom_objects
from keras.layers import Activation
get_custom_objects().update({'swish_act': SwishActivation(swish_act)})

模型定义

model = enet.EfficientNetB0(include_top=False, input_shape=(150,50,3), pooling='avg', weights='imagenet')

向 B0 添加 2 个全连接层。

x = model.output

x = BatchNormalization()(x)
x = Dropout(0.7)(x)

x = Dense(512)(x)
x = BatchNormalization()(x)
x = Activation(swish_act)(x)
x = Dropout(0.5)(x)

x = Dense(128)(x)
x = BatchNormalization()(x)
x = Activation(swish_act)(x)

x = Dense(64)(x)

x = Dense(32)(x)

x = Dense(16)(x)

# Output layer
predictions = Dense(1, activation="sigmoid")(x)

model_final = Model(inputs = model.input, outputs = predictions)

model_final.summary()

我使用以下方法保存了它:

    model.save('model.h5')

我在尝试加载它时收到以下错误:

    model=tf.keras.models.load_model('model.h5')
    
    ---------------------------------------------------------------------------
    ValueError                                Traceback (most recent call last)
    <ipython-input-12-e3bef1680e4f> in <module>()
          1 # Recreate the exact same model, including its weights and the optimizer
    ----> 2 model = tf.keras.models.load_model('PhoneDetection-CNN_29_July.h5')
          3 
          4 # Show the model architecture
          5 model.summary()
    
    10 frames
    /usr/local/lib/python3.6/dist-packages/tensorflow/python/keras/utils/generic_utils.py in class_and_config_for_serialized_keras_object(config, module_objects, custom_objects, printable_module_name)
        319   cls = get_registered_object(class_name, custom_objects, module_objects)
        320   if cls is None:
    --> 321     raise ValueError('Unknown ' + printable_module_name + ': ' + class_name)
        322 
        323   cls_config = config['config']
    
    ValueError: Unknown layer: FixedDropout
```python

【问题讨论】:

  • 您需要通过custom_objects 参数告诉load_model 在哪里可以找到FixedDropout。
  • 我在训练后使用了model.get_config,它给了我一个很长的模型配置字典,然后我将配置保存在一个pickle文件中。之后,我将它用于 custom_object 但它给出了同样的错误。
  • 你能分享创建模型的代码吗?那里应该有对FixedDropout 的引用。你需要传入custom_objects={"FixedDropout": FixedDropout}
  • 我提供了创建模型和定制激活fcn的代码。正如你提议的@jakub,我使用了custom_objects={"FixedDropout": FixedDropout},但它给出了:NameError: name 'FixedDropout' is not defined。如果您查看我最初在帖子中提到的链接,您会注意到 FixedDropout 在模型结构中使用了 9 次。
  • @AliBesharati 你有没有找到解决方案?我也有同样的问题!

标签: anaconda google-colaboratory tf.keras


【解决方案1】:

我在尝试通过加载我保存的模型进行推理时遇到了同样的错误。 然后我在推理笔记本中也导入了effiecientNet 库,错误就消失了。 我的导入命令看起来像:

import efficientnet.keras as efn

(请注意,如果您还没有安装 effiecientNet(这不太可能),您可以使用!pip install efficientnet 命令来安装。)

【讨论】:

    【解决方案2】:

    我最近的型号也有同样的问题。研究源代码,您可以找到FixedDropout 类。我通过导入后端和层将其添加到我的推理代码中。该速率还应与您的效率网络模型中的速率相匹配,因此对于 EfficientNetB0,速率为 0.2(其他情况不同)。

    from tensorflow.keras import backend, layers
    class FixedDropout(layers.Dropout):
            def _get_noise_shape(self, inputs):
                if self.noise_shape is None:
                    return self.noise_shape
    
                symbolic_shape = backend.shape(inputs)
                noise_shape = [symbolic_shape[axis] if shape is None else shape
                               for axis, shape in enumerate(self.noise_shape)]
                return tuple(noise_shape)
    model = keras.models.load_model('model.h5', custom_objects={'FixedDropout':FixedDropout(rate=0.2)})
    

    【讨论】:

      【解决方案3】:

      我遇到了同样的错误。然后我导入下面的代码。然后它就可以正常工作了

      import cv2
      import matplotlib.pyplot as plt
      import tensorflow as tf
      from sklearn.metrics import confusion_matrix
      import itertools
      import os, glob
      from tqdm import tqdm
      from efficientnet.tfkeras import EfficientNetB4
      

      如果您不必安装它。 !pip install efficientnet。如果你有任何问题,请在这里提出。

      【讨论】:

        猜你喜欢
        • 2021-03-30
        • 1970-01-01
        • 1970-01-01
        • 2015-11-21
        • 1970-01-01
        • 2015-12-24
        • 1970-01-01
        • 2020-08-06
        • 1970-01-01
        相关资源
        最近更新 更多