Search code examples
tensorflowkerasmax-pooling

MinimumPooling in Keras


I have only found MaxPooling2D and AveragePooling2D in keras with tensorflow backend. Have been looking for MinimumPooling2D. This github link suggests to use something like this for minimum pooling (pool2d(-x))

I get an error while using a negative sign before inputs. The following line I use in keras

MaxPooling2D((3, 3), strides=(2, 2), padding='same')(-inputs)

Solution

  • It is not sufficient to negate the input argument of the MaxPooling2D layer because the pooled values are going to be negative that way.

    I think it's better for you to actually implement a general MinPooling2D class whose pooling function gets the same parameters as Keras MaxPooling2D class and operates analogously. By inheriting from MaxPooling2D, the implementation is very simple:

    from keras import layers
    from keras import backend as K
    
    class MinPooling2D(layers.MaxPooling2D):
    
    
      def __init__(self, pool_size=(2, 2), strides=None, 
                   padding='valid', data_format=None, **kwargs):
        super(MaxPooling2D, self).__init__(pool_size, strides, padding,
                                           data_format, **kwargs)
    
      def pooling_function(inputs, pool_size, strides, padding, data_format):
        return -K.pool2d(-inputs, pool_size, strides, padding, data_format,
                                                             pool_mode='max')
    

    Now you can use this layer just as you would a MaxPooling2D layer. For instance, here's an example of how to use MinPooling2D layer in a simple sequntial convolutional neural network:

    from keras import models
    from keras import layers
    
    model = models.Sequential()
    
    model.add(layers.Conv2D(32, (3, 3), activation='relu', input_shape=(28, 28, 1)))
    model.add(MinPooling2D(pool_size=(2, 2)))
    model.add(layers.Flatten())
    model.add(layers.Dense(10, activation='softmax'))