Search code examples
pythontensorflowkeraskeras-layerkeras-2

How to use Keras layers without making model


I want to use Keras layers pooling layers without making a model. Every time I see example related to Keras,I see them in model form, like as follows:

model = Sequential()
model.add(Conv2D(2, kernel_size=(3, 3),activation='relu',
                 input_shape=input_shape))
model.add(MaxPooling2D(pool_size=(2, 2)))
....

model.compile(loss=keras.losses.binary_crossentropy,
              optimizer=keras.optimizers.Adadelta(),
              metrics=['accuracy'])
model.fit(x_train, y_train,batch_size=batch_size,epochs=epochs,verbose=1,)

This way, first we define input and then model then compile and last fit. but let say I have to perform maxpooling operation and I have only 1 image of size 56*64 with gray scale, i.e input in 4d tensor form (1,56,64,1). Then how can I perform maxpooling operation using Keras MaxPooling2D layer.


Solution

  • You can make a model with only MaxPooling2D and do predict (with no fit):

    model = Sequential()
    model.add(MaxPooling2D(pool_size=(2, 2), input_shape=input_shape))
    model.compile('adadelta')
    
    pooled = model.predict(image)
    

    The compile doesn't affect at all.

    Full code

    Example from @Hitesh comment:

    from keras.models import Sequential
    from keras.layers import MaxPooling2D
    import numpy as np
    
    image=np.random.rand(1, 56, 64, 1)
    input_shape=(56,64,1)
    
    model = Sequential()
    model.add(MaxPooling2D(pool_size=(2, 2), input_shape=input_shape))
    model.compile(loss='categorical_crossentropy', optimizer='rmsprop', metrics=['accuracy'])
    
    pooled = model.predict(image)