合并多个CNN

时间:2018-10-17 06:20:42

标签: python machine-learning neural-network keras conv-neural-network

我正在尝试对模型中的多个输入执行Conv1D。因此,我有15个大小均为1x1500的输入,每个输入都是一系列图层的输入。因此,我想在完全连接层之前合并15个卷积模型。我已经在函数中定义了卷积模型,但是我不明白如何调用该函数然后将它们合并。

def defineModel(nkernels, nstrides, dropout, input_shape):
    model = Sequential()
    model.add(Conv1D(nkernels, nstrides, activation='relu', input_shape=input_shape))
    model.add(Conv1D(nkernels*2, nstrides, activation='relu'))
    model.add(BatchNormalization())
    model.add(MaxPooling1D(nstrides))
    model.add(Dropout(dropout))
    return model


models = {}
for i in range(15):
    models[i] = defineModel(64,2,0.75,(64,1))

我已经成功地串联了以下四个模型:

merged = Concatenate()([ model1.output, model2.output, model3.output, model4.output])

merged = Dense(512, activation='relu')(merged)
merged = Dropout(0.75)(merged)
merged = Dense(1024, activation='relu')(merged)
merged = Dropout(0.75)(merged)
merged = Dense(40, activation='softmax')(merged)
model = Model(inputs=[model1.input, model2.input, model3.input, model4.input], outputs=merged)

在for循环中如何对15层进行处理,因为分别编写15层效率不高?

2 个答案:

答案 0 :(得分:2)

当然,正如@GabrielM所建议的那样,使用函数式API是执行此操作的最佳方法,但是,如果您不想修改define_model函数,也可以这样做:

models = []
inputs = []
outputs = []
for i in range(15):
    model = defineModel(64,2,0.75,(64,1))
    models.append(model)
    inputs.append(model.input)
    outputs.append(model.output)


merged = Concatenate()(outputs) # this should be output tensors and not models

# the rest is the same ...

model = Model(inputs=inputs, outputs=merged)

答案 1 :(得分:1)

我认为您能做的最好的就是在各处使用功能性API:

def defineModel(nkernels, nstrides, dropout, input_shape):
    l_input = Input( shape=input_shape )
    model = Conv1D(nkernels, nstrides, activation='relu')(l_input)
    model = Conv1D(nkernels*2, nstrides, activation='relu')(model)
    model = BatchNormalization()(model)
    model = MaxPooling1D(nstrides)(model)
    model = Dropout(dropout)(model)
    return model, l_input


models = []
inputs = []
for i in range(15):
    model, input = defineModel(64,2,0.75,(64,1))
    models.append( model )
    inputs.append( input )

然后很容易恢复子模型的输入和输出列表并将它们合并

merged = Concatenate()(models)

merged = Dense(512, activation='relu')(merged)
merged = Dropout(0.75)(merged)
merged = Dense(1024, activation='relu')(merged)
merged = Dropout(0.75)(merged)
merged = Dense(40, activation='softmax')(merged)
model = Model(inputs=inputs, outputs=merged)

通常,这些操作不是瓶颈。在培训或推理过程中,所有这些都不会对

产生重大影响