如何展平嵌套模型? (keras功能API)

时间:2019-02-12 10:46:40

标签: python tensorflow keras

我已经使用keras Model功能API定义了一个简单的模型。它的一层是完全顺序的模型,因此我得到了一个嵌套的层结构(请参见下图)。

如何将嵌套层结构转换为平面层结构? (使用脚本,而不是手动...)


我所拥有的: Nested layer structure

_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
input_1 (InputLayer)         (None, 32, 32, 1)         0         
_________________________________________________________________
sequential_1 (Sequential)    (None, 8, 8, 12)          720       
_________________________________________________________________
flatten_1 (Flatten)          (None, 768)               0         
_________________________________________________________________
dense_1 (Dense)              (None, 1)                 769       
=================================================================

我想将其转换为: Flat layer structure

_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
input_1 (InputLayer)         (None, 32, 32, 1)         0         
_________________________________________________________________
conv2d_1 (Conv2D)            (None, 32, 32, 6)         60        
_________________________________________________________________
max_pooling2d_1 (MaxPooling2 (None, 16, 16, 6)         0         
_________________________________________________________________
conv2d_2 (Conv2D)            (None, 16, 16, 6)         330       
_________________________________________________________________
max_pooling2d_2 (MaxPooling2 (None, 8, 8, 6)           0         
_________________________________________________________________
flatten_1 (Flatten)          (None, 384)               0         
_________________________________________________________________
dense_1 (Dense)              (None, 1)                 385       
=================================================================

生成嵌套层结构的代码:

def create_network_with_one_subnet():
    # define subnetwork
    subnet = keras.models.Sequential()
    subnet.add(keras.layers.Conv2D(6, (3, 3), padding='same'))
    subnet.add(keras.layers.MaxPool2D())
    subnet.add(keras.layers.Conv2D(12, (3, 3), padding='same'))
    subnet.add(keras.layers.MaxPool2D())
    #subnet.summary()


    # define complete network
    input_shape = (32, 32, 1)
    net_in = keras.layers.Input(shape=input_shape)
    net_out = subnet(net_in)
    net_out = keras.layers.Flatten()(net_out)
    net_out = keras.layers.Dense(1)(net_out)
    net_complete = keras.Model(inputs=net_in, outputs=net_out)
    net_complete.compile(loss='binary_crossentropy',
                         optimizer=keras.optimizers.Adam(lr=0.001),
                         metrics=['acc'],
                         )
    net_complete.summary()
    return net_complete

2 个答案:

答案 0 :(得分:2)

啊,这比预期容易得多。在搜索了正确的关键字:https://groups.google.com/forum/#!msg/keras-users/lJcVK25YDuc/atB6TfwqBAAJ

之后,从此处寻求解决方案
def flatten_model(model_nested):
    layers_flat = []
    for layer in model_nested.layers:
        try:
            layers_flat.extend(layer.layers)
        except AttributeError:
            layers_flat.append(layer)
    model_flat = keras.models.Sequential(layers_flat)
    return model_flat

答案 1 :(得分:0)

用于处理具有多个级别的嵌套模型的更好解决方案:

def flatten_model(model_nested):
    def get_layers(layers):
        layers_flat = []
        for layer in layers:
            try:
                layers_flat.extend(get_layers(layer.layers))
            except AttributeError:
                layers_flat.append(layer)
        return layers_flat

    model_flat = tfk.models.Sequential(
        get_layers(model_nested.layers)
    )
    return model_flat