连接或级联多个预训练keras模型

时间:2017-12-05 12:06:26

标签: keras concatenation

我正在尝试构建一个连接或级联(实际上甚至不知道这是否是正确的定义)模型集。 为简单起见,我的基本模型如下所示。

                              ----Input----
                                    |
                                  L1-1
                                    |  
                                  L1-2
                                    |
                                  Dense
                                    |
                                 Softmax

我对这些模型中的7个进行了交叉验证培训,并尝试以级联方式将它们包装起来,例如:

            -----------------------Input---------------------
            |       |       |       |       |       |       |       
          L1-1    L1-2    L1-3    L1-4     L1-5   L1-6    L1-7
            |       |       |       |       |       |       |
          L2-1    L2-2    L2-3    L2-4     L2-5   L2-6    L2-7
            |       |       |       |       |       |       |
            |_______|_______|_______|_______|_______|_______|
            |                  Concatenated                 |
            |___________________Dense Layer_________________|
                                    |
                                 SoftMax

每一个密集层都有512个神经元,所以最终连锁密集层总共会有7*512=3584个神经元。

我所做的是:

  • 训练所有模型并将其保存在名为models[]的列表中。
  • 在所有型号中弹出底部的Softmax图层。

然后我尝试连接它们但得到了错误:

Layer merge was called with an input that isn't a symbolic tensor. 

形成级联后我要做的就是冻结除Concatenated Dense Layer之外的所有中间层并稍微调整一下。但是我在所有细节中都被解释了。

1 个答案:

答案 0 :(得分:4)

您需要使用功能API模型。这种模型适用于张量。

首先定义一个公共输入张量:

inputTensor = Input(inputShape)

然后使用此输入调用每个模型以获得输出张量:

outputTensors = [m(inputTensor) for m in models]

然后将这些张量传递给连接层:

output = Concatenate()(outputTensors) 
output = Dense(...)(output)    
#you might want to use an Average layer instead of these two....

output = Activation('softmax')(output)

最后,您可以定义从开始张量到结束张量的完整模型:

fullModel = Model(inputTensor,output)
相关问题