2

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.

ebeneditos
  • 2,542
  • 1
  • 15
  • 35
Hitesh
  • 1,285
  • 6
  • 20
  • 36

2 Answers2

3

You can do it using using functional API: just define input, then do something like this:

maxpooled = MaxPooling2D(...)(input)
maxpooled.eval(feed_dict={input: input_image}, session=...)

BTW using Keras for that is kind of an overkill, since it's a toolkit for building models. You can just easily do it without keras using tensorflow or any other deep learning framework.

Jakub Bartczuk
  • 2,317
  • 1
  • 20
  • 27
2

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)
ebeneditos
  • 2,542
  • 1
  • 15
  • 35
  • this works, example code is following: 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) – Hitesh Apr 13 '18 at 10:32
  • can you please look at my question: https://stackoverflow.com/questions/49630178/how-to-know-which-node-is-dropped-after-using-keras-dropout-layer. i am not getting answer – Hitesh Apr 13 '18 at 10:53