我是Keras的新手。我正在尝试合并Keras中三个预训练模型的输出层。每个模型都有两个独立的输入,但具有不同的尺寸,以及Dense图层输出。
model1 = MyModel1() #returns keras.engine.training.Model
model2 = MyModel2() #returns keras.engine.training.Model
model3 = MyModel3() #returns keras.engine.training.Model
x = merge([model1(model1.input),
model2(model2.input),
model3(model3.input)],
mode='concat', concat_axis=1)
# add some trainable layers here...
# and a final softmax layer
x = Dense(2, activation='softmax')(x)
return Model(input=[model1.input,
model2.input,
model3.input],
output=x)
由于model?.input返回一个Tensors列表,这不起作用。我尝试了不同的东西,似乎什么都没有用。这个问题有一个简单的解决方案吗?
修改 来自indraforyou的改进工作解决方案,用于每个模型中的多个输入。
from keras.models import Model
from keras.layers import Input, Dense, merge
def MyModel1():
inp1 = Input(batch_shape=(None,32,))
inp2 = Input(batch_shape=(None,32))
x = Dense(8)(inp1)
y = Dense(8)(inp2)
merged = merge([x, y], mode='concat', concat_axis=-1)
out = Dense(8)(merged)
return Model(input=[inp1,inp2], output=out)
def MyModel2():
inp1 = Input(batch_shape=(None,10,))
inp2 = Input(batch_shape=(None,10,))
x = Dense(4)(inp1)
y = Dense(4)(inp2)
merged = merge([x, y], mode='concat', concat_axis=-1)
out = Dense(4)(merged)
return Model(input=[inp1,inp2], output=out)
def MyModel3():
inp1 = Input(batch_shape=(None,12,))
inp2 = Input(batch_shape=(None,12,))
x = Dense(6)(inp1)
y = Dense(6)(inp1)
merged = merge([x, y], mode='concat', concat_axis=-1)
out = Dense(6)(merged)
return Model(input=[inp1,inp2], output=out)
model1 = MyModel1()
model2 = MyModel2()
model3 = MyModel3()
x = merge([model1.output,
model2.output,
model3.output],
mode='concat', concat_axis=-1)
x = Dense(2, activation='softmax')(x)
merged = Model(input=[model1.input[0], model1.input[1],
model2.input[0], model2.input[1],
model3.input[0], model3.input[1]],
output=x)
merged.summary()
答案 0 :(得分:4)
models对象不是可调用函数。这应解决问题:
x = merge([model1.output,
model2.output,
model3.output],
mode='concat', concat_axis=1)
更新工作代码
from keras.models import Model
from keras.layers import Input, Dense, merge
def MyModel1():
inp = Input(batch_shape=(None,32,))
out = Dense(8)(inp)
return Model(input=inp, output=out)
def MyModel2():
inp = Input(batch_shape=(None,10,))
out = Dense(4)(inp)
return Model(input=inp, output=out)
def MyModel3():
inp = Input(batch_shape=(None,12,))
out = Dense(6)(inp)
return Model(input=inp, output=out)
model1 = MyModel1()
model2 = MyModel2()
model3 = MyModel3()
x = merge([model1.output,
model2.output,
model3.output],
mode='concat', concat_axis=1)
x = Dense(2, activation='softmax')(x)
merged = Model(input=[model1.input,
model2.input,
model3.input],
output=x)
merged.summary()