gpt4 book ai didi

machine-learning - 合并具有不同输入形状的不同模型的输出

转载 作者:行者123 更新时间:2023-11-30 08:39:55 25 4
gpt4 key购买 nike

我是 Keras 新手。我正在尝试合并 Keras 中三个预训练模型的输出层。每个模型都有两个独立的输入,但尺寸不同,以及一个密集层输出。

    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 返回张量列表,因此这不起作用。我尝试了不同的方法,但似乎没有任何效果。有没有简单的方法可以解决这个问题?

编辑:针对每个模型中的多个输入,调整了 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()

最佳答案

模型对象不是可调用函数。这应该可以解决问题:

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

关于machine-learning - 合并具有不同输入形状的不同模型的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42445275/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com