【发布时间】: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