我无法加载经过训练和保存的nn模型

时间:2020-08-02 07:01:56

标签: anaconda google-colaboratory tf.keras

我使用转移学习来训练模型。基本模型是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(Activation):

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

2 个答案:

答案 0 :(得分:1)

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

effiecientNet

(请注意,如果您还没有安装 effiecientNet(这不太可能),您可以使用 import efficientnet.keras as efn 命令来安装。)

答案 1 :(得分:0)

我在最近的模型上遇到了同样的问题。研究源代码,您可以找到 FixedDropout 类。我通过导入后端和层将其添加到我的推理代码中。该费率还应与您的 Effectivenet 模型中的费率相匹配,因此对于 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)})