代码之家  ›  专栏  ›  技术社区  ›  colt.exe

串联或级联多个预训练keras模型

  •  3
  • colt.exe  · 技术社区  · 8 年前

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

                                  ----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 回复  |  直到 8 年前
        1
  •  5
  •   Daniel Möller    8 年前

    为此,您需要使用函数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)