且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何从Keras.layers实现合并

更新时间:2023-12-02 15:35:22

合并不能与顺序模型一起使用.在顺序模型中,图层只能有一个输入和一个输出. 您必须使用功能性API ,类似这样.我假设您对modela和modelb使用相同的输入层,但是如果不是这种情况,则可以创建另一个Input()并将它们都作为模型的输入.

Merge cannot be used with a sequential model. In a sequential model, layers can only have one input and one output. You have to use the functional API, something like this. I assumed you use the same input layer for modela and modelb, but you could create another Input() if it is not the case and give both of them as input to the model.

def linear_model_combined(optimizer='Adadelta'):    

    # declare input
    inlayer =Input(shape=(100, 34))
    flatten = Flatten()(inlayer)

    modela = Dense(1024)(flatten)
    modela = Activation('relu')(modela)
    modela = Dense(512)(modela)

    modelb = Dense(1024)(flatten)
    modelb = Activation('relu')(modelb)
    modelb = Dense(512)(modelb)

    model_concat = concatenate([modela, modelb])


    model_concat = Activation('relu')(model_concat)
    model_concat = Dense(256)(model_concat)
    model_concat = Activation('relu')(model_concat)

    model_concat = Dense(4)(model_concat)
    model_concat = Activation('softmax')(model_concat)

    model_combined = Model(inputs=inlayer,outputs=model_concat)

    model_combined.compile(loss='categorical_crossentropy', optimizer=optimizer, metrics=['accuracy'])

    return model_combined