在Keras中使用Lambda图层后无法保存模型

时间:2020-04-15 17:52:54

标签: python keras

我的Keras版本是2.0.8。我添加了以下代码片段:

        units = 32
        hidden_with_time_axis = Lambda(lambda x: K.expand_dims(x,1))(layer)
        W1 = Dense(units)(kb_embedding)
        W2 = Dense(units)(hidden_with_time_axis)
        out = Add()([W1,W2])
        score = Lambda(lambda x: K.tanh(x))(out)
        out2 = Dense(1)(score)
        attention_weights = Lambda(lambda x: K.softmax(x))(out2)
        context = Lambda(lambda x: x * kb_embedding)(attention_weights)
        context_vector = Lambda(lambda x: K.sum(context,axis=1))(context)

        layer = merge([layer,context_vector], mode='concat')
        # Classification layers
        denseSize = self.getParameter("dense", self.styles, 400, parameters, 1)

        if denseSize > 0:
            layer = Dense(denseSize, activation='relu')(layer) #layer = Dense(800, activation='relu')(layer)
        assert self.cmode in ("binary", "multiclass", "multilabel")
        if self.cmode in ("binary", "multilabel"):
            layer = Dense(dimLabels, activation='sigmoid')(layer)
        else:
            layer = Dense(dimLabels, activation='softmax')(layer)
        if self.tag == 'entity-' or self.tag =='edge-':
            feature_embedding = sum([self.embeddings[x].inputLayers for x in embNames], [])
            feature_embedding.append(kb_embedding)
            kerasModel = Model(feature_embedding,layer)

然后发生错误:

TypeError: can't pickle NotImplementedType objects

显然,这是因为,如果您未正确使用Lambda层,则Keras模型将无法序列化,但是我不知道如何修改代码以使其正常工作。

1 个答案:

答案 0 :(得分:0)

在使用 tensorflow.keras.layers.Lambda 时,最好使用:

  1. 保存权重:model.save_weights()
  2. 加载权重:model.load_weights()