[Keras] 错误之ValueError: Unknown activation function:******

在使用keras加载模型时,例如load_model, model_from_json等,如果模型存在keras未定义的激活函数、层等会导致未知错误,例如错误可能是:

ValueError: Unknown activation function:swish_activation

ValueError: Unknown layer:FixedDropout

解决思路有两种:

一是使用代码构建模型model = model_build(...),而不是直接加载模型;

二是在加载模型时指定这些结构对象,并提前定义好。但是怎么定义呢?直接去构建模型的代码里找相应的对象即可,或者搜索

1、定义结构对象:


from keras import backend as K
from keras.utils.generic_utils import get_custom_objects  # tensorflow.keras.generic_utils
from keras.layers import Activation

# 函数
def swish_activation(x):
        return (K.sigmoid(x) * x)

# 类
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)

2、加载模型时指定自定义的结构对象:

from keras_bert import get_custom_objects

# load_model
from keras.models import load_model
model = load_model(model_path, custom_objects=get_custom_objects(
    'swish_activation': swish_activation, 'FixedDropout': FixedDropout))

# model_from_json
from keras.models import model_from_json
model = model_from_json(model_string, custom_objects=get_custom_objects(
    'swish_activation': swish_activation, 'FixedDropout': FixedDropout))

参考:

1、Implementing Swish Activation Function in Keras

2、ValueError: Unknown activation function:swish_activation

3、Keras读取保存的模型时, 产生错误[ValueError: Unknown activation function:relu6]

4、Keras load_model raise ValueError: Unknown layer: TokenEmbedding问题

  • 6
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
def create_LSTM_model(): # instantiate the model model = Sequential() model.add(Input(shape=(X_train.shape[1], X_train.shape[2]))) model.add(Reshape((X_train.shape[1], 1, X_train.shape[2], 1))) # cnn1d Layers model.add(ConvLSTM2D(filters=64, kernel_size=(1,3), activation='relu', padding='same', return_sequences=True)) model.add(Flatten()) model.add(Dropout(0.5)) model.add(RepeatVector(1)) # 添加lstm层 model.add(LSTM(64, activation = 'relu', return_sequences=True)) model.add(Dropout(0.5)) #添加注意力层 model.add(LSTM(64, activation = 'relu', return_sequences=False)) # 添加dropout model.add(Dropout(0.5)) model.add(Dense(128)) # 输出层 model.add(Dense(1, name='Output')) # 编译模型 model.compile(optimizer='adam', loss='mse', metrics=['mae']) return model # lstm network model = create_LSTM_model() # summary print(model.summary())修改该代码,解决ValueError: in user code: File "C:\Users\gaozhiyuan\anaconda3\lib\site-packages\keras\engine\training.py", line 1284, in train_function * return step_function(self, iterator) File "C:\Users\gaozhiyuan\anaconda3\lib\site-packages\keras\engine\training.py", line 1268, in step_function ** outputs = model.distribute_strategy.run(run_step, args=(data,)) File "C:\Users\gaozhiyuan\anaconda3\lib\site-packages\keras\engine\training.py", line 1249, in run_step ** outputs = model.train_step(data) File "C:\Users\gaozhiyuan\anaconda3\lib\site-packages\keras\engine\training.py", line 1050, in train_step y_pred = self(x, training=True) File "C:\Users\gaozhiyuan\anaconda3\lib\site-packages\keras\utils\traceback_utils.py", line 70, in error_handler raise e.with_traceback(filtered_tb) from None File "C:\Users\gaozhiyuan\anaconda3\lib\site-packages\keras\layers\reshaping\reshape.py", line 118, in _fix_unknown_dimension raise ValueError(msg) ValueError: Exception encountered when calling layer 'reshape_51' (type Reshape). total size of new array must be unchanged, input_shape = [10, 1, 1, 5], output_shape = [10, 1, 1, 1] Call arguments received by layer 'reshape_51' (type Reshape): • inputs=tf.Tensor(shape=(None, 10, 1, 1, 5), dtype=float32)问题
最新发布
05-26
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值