如何从 Keras.layers 实现 Merge [英] How to implement Merge from Keras.layers

查看:30
本文介绍了如何从 Keras.layers 实现 Merge的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在尝试合并以下顺序模型,但未能成功.谁能指出我的错误,谢谢.

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.

代码在使用merge"时编译但给出以下错误TypeError: 'module' object is not callable"但是它在使用合并"时甚至不会编译

The code compiles while using"merge" but give the following error "TypeError: 'module' object is not callable" However it doesn't even compile while using "Merge"

我使用的是 keras 2.2.0 版和 python 3.6

I am using keras version 2.2.0 and python 3.6

from keras.layers import merge
def linear_model_combined(optimizer='Adadelta'):    
    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))

    model_combined = Sequential()

    model_combined.add(Merge([modela, modelb], mode='concat'))

    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'))

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

    return model_combined

推荐答案

Merge 不能与顺序模型一起使用.在顺序模型中,层只能有一个输入和一个输出.你必须使用函数式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

这篇关于如何从 Keras.layers 实现 Merge的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆