与GlobalAveragePooling2D()不兼容的Dims

时间:2019-05-30 16:42:30

标签: python keras

我正在尝试运行几种不同的模型,直到我添加了GlobalAveragePooling2D(),然后抛出以下错误为止,该模型运行良好:

ValueError: Input 0 is incompatible with layer flatten_105: expected min_ndim=3, found ndim=2

我觉得这与GlobalAveragePooling2D()层与flatten()层不兼容有关,我缺乏理解,但不确定。

我的代码如下。有人能启发我他们的想法吗?在没有GlobalAveragePooling2D层的情况下运行良好。我还是希望尝试一下。

dense_layers = [1,2,3]
layer_sizes = [32, 64, 128]
con_layers = [1,2,3]
con_layer_sizes = [32, 64, 128, 512]

for dense_layer in dense_layers:
    for layer_size in layer_sizes:
        for conv_layer in con_layers:
            for con_layer_size in con_layer_sizes:

                img_size = 125

                batch_size = 16

                K.input_shape = (img_size, img_size)

                NAME = "{}-conv-{}-con_layer_sizes-{}-nodes-{}-dense-{}".format(conv_layer, con_layer_size, layer_size, dense_layer, int(time.time()))
                print(NAME)
                tensorboard = TensorBoard(log_dir= 'logs/{}'.format(NAME))
                mcp = ModelCheckpoint(filepath='C:\\Users\\jordan.howell\\models\\'+NAME+'_model.h5',monitor="val_loss"
                                      , save_best_only=True, save_weights_only=False)
                reduce_learning_rate = ReduceLROnPlateau(monitor='val_loss', factor=0.3,patience=2,cooldown=2
                                                         , min_lr=0.00001, verbose=1)



                #start model build
                model = Sequential()
                model.add(Conv2D(con_layer_size, (3, 3), activation="relu", padding = 'same', input_shape=input_shape))
                model.add(MaxPooling2D(pool_size = (2, 2)))
                model.add(BatchNormalization())
                model.add(Dropout(0.15))

                for l in range(conv_layer-1):
                    #Convolution
                    model.add(Conv2D(con_layer_size, (3, 3), activation="relu", padding = 'same'))
                    model.add(MaxPooling2D(pool_size = (2, 2)))
                    model.add(BatchNormalization())
                    model.add(Dropout(0.15))                


                model.add(GlobalAveragePooling2D())
                # Flatten the layer
                model.add(Flatten())

                for l in range(dense_layer):
                    model.add(Dense(layer_size, activation = 'relu'))

                model.add(Dense(activation = 'sigmoid', units = 1))

                model.compile(loss ='binary_crossentropy', optimizer = 'adam'
                              , metrics=[km.binary_precision(), km.binary_recall()])

                #generators = Generators(TRAIN_DATA_DIR, VALIDATION_DATA_DIR, TEST_DATA_DIR)
                #train_generator = generators.train_generator(150, batch_size=32)
                #validation_generator = generators.validation_generator(150, batch_size=16)

                model.fit_generator(train_generator, steps_per_epoch=5216  // batch_size
                                    ,validation_data=validation_generator, validation_steps=1
                                    , epochs = 50, callbacks = [reduce_learning_rate, tensorboard, mcp])

1 个答案:

答案 0 :(得分:1)

Keras docs中,GlobalAveragePooling2D的输入形状为4D张量,输出形状为2D张量。在这种情况下,Flatten是多余的。