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

col*_*exe 3 concatenation keras

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

                              ----Input----
                                    |
                                  L1-1
                                    |  
                                  L1-2
                                    |
                                  Dense
                                    |
                                 Softmax
Run Code Online (Sandbox Code Playgroud)

我得到了其中 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
Run Code Online (Sandbox Code Playgroud)

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

我所做的是:

  • 训练所有模型并将它们保存在名为models[].
  • 在所有模型中弹出底部 Softmax 层。

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

Layer merge was called with an input that isn't a symbolic tensor. 
Run Code Online (Sandbox Code Playgroud)

形成级联后我要做的是冻结所有中间层,Concatenated Dense Layer并稍微调整一下。但我坚持在所有细节中解释。

Dan*_*ler 5

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

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

inputTensor = Input(inputShape)
Run Code Online (Sandbox Code Playgroud)

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

outputTensors = [m(inputTensor) for m in models]
Run Code Online (Sandbox Code Playgroud)

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

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

output = Activation('softmax')(output)
Run Code Online (Sandbox Code Playgroud)

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

fullModel = Model(inputTensor,output)
Run Code Online (Sandbox Code Playgroud)