How to implement Merge from Keras.layers

前端 未结 3 1478
盖世英雄少女心
盖世英雄少女心 2021-01-18 10:21

I have been trying to merge the following sequential models but haven\'t been able to. Could somebody please point out my mistake, thank you.

The code compiles while

3条回答
  •  鱼传尺愫
    2021-01-18 10:51

    To be honest, I was struggling on this issue for a long time...

    Luckily I found the panacea expected finally. For anyone who would like to make the minimal changes on their original codes with Sequential, here comes the solution:

    def linear_model_combined(optimizer='Adadelta'): 
        from keras.models import Model, Sequential
        from keras.layers.core import Dense, Flatten, Activation, Dropout
        from keras.layers import add
    
        modela = Sequential()
        modela.add(Flatten(input_shape=(100, 34)))
        modela.add(Dense(1024))
        modela.add(Activation('relu'))
        modela.add(Dense(512))
    
        modelb = Sequential()
        modelb.add(Flatten(input_shape=(100, 34)))
        modelb.add(Dense(1024))
        modelb.add(Activation('relu'))
        modelb.add(Dense(512))
    
        merged_output = add([modela.output, modelb.output])   
    
        model_combined = Sequential()
        model_combined.add(Activation('relu'))
        model_combined.add(Dense(256))
        model_combined.add(Activation('relu'))
        model_combined.add(Dense(4))
        model_combined.add(Activation('softmax'))
    
        final_model = Model([modela.input, modelb.input], model_combined(merged_output))
    
        final_model.compile(loss='categorical_crossentropy', optimizer=optimizer, metrics=['accuracy'])
    
        return final_model
    

    For more information, refer to https://github.com/keras-team/keras/issues/3921#issuecomment-335457553 for farizrahman4u's comment. ;)

提交回复
热议问题