Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Keras MaxPooling2D gives ValueError: Negative dimension size caused by subtracting 2 from 1 for 'MaxPool_x' #3945

Closed
pranay360 opened this issue Oct 3, 2016 · 23 comments

Comments

@pranay360
Copy link

Please look into the following link.
http://stackoverflow.com/questions/39815518/keras-maxpooling2d-layer-gives-valueerror

I have been facing this issue on the following config Ubuntu 16.04, Keras, TensorFlow GPU and Cuda 7.5.
On my windows config with GPU enabled Theano there is no issue in executing the script.

What might be the reason for this?

@cdalbergue
Copy link

cdalbergue commented Oct 3, 2016

Hello, I think taht you need to specify the dimension ordering:

  • Either change image_dim_ordering: 'tf' to image_dim_ordering: 'th' in your ~/.keras/keras.json
  • Specify the dim_ordering in your model like so:
model.add(MaxPooling2D(pool_size=(2, 2), dim_ordering="th"))

hope that helps 👍

@burgalon
Copy link

thanks @cdalbergue That actually resolves the issue however I'm not sure why it's needed as we are using the Tensorflow backend - shouldn't the dim_ordering be 'tf' ?

@cdalbergue
Copy link

cdalbergue commented Nov 24, 2016

@burgalon It depends of the version of tensorflow that you are using. 0.10 would use "tf", 0.11 would use "th"

Edit: or the opposite, can't really remember

@jeffreynghm
Copy link

That's weired. It's th for the latest version of keras... is there any reason? behind it @cdalbergue ?

@PonyboyYbr
Copy link

In fact, this problem results from your initial input.
input_shape=(3,224,224) is for "theano"
and your backend should be "tensorflow", so it should be
input_shape=(224,224,3).

@arashmh
Copy link

arashmh commented Feb 21, 2017

Just add this:

from keras import backend as K
K.set_image_dim_ordering('th')

@sivakumar05
Copy link

Your suggestion really helped me,arashmh!

@OmarMAmin
Copy link

guys how am i supposed to set image dim ordering to theano while my backend is tensorflow?

I made your suggested fix, and it's somehow working

@marektmn
Copy link

marektmn commented May 5, 2018

tensorflow.python.framework.errors_impl.InvalidArgumentError: Negative dimension size caused by subtracting 3 from 1 for 'max_pooling2d_3/MaxPool' (op: 'MaxPool') with input shapes: [?,1,1,256].

guys I'm lost I have tried everything mentioned here and on stackoverflow. My dataset is grayscale 17x17x1, 3 classes, and I'm using Alexnet architecture.

This is output of x_train.shape & y_train.shape :

x_train shape: (18079, 17, 17, 1)
y_train_shape: (18079, 3)

Explicitly I have used :
from keras import backend as K K.set_image_dim_ordering('tf')
and my keras.json :
{ "floatx": "float32", "backend": "tensorflow", "epsilon": 1e-07, "image_data_format": "channels_last" }

@Priyankk18k
Copy link

In fact, this problem results from your initial input.
input_shape=(3,224,224) is for "theano"
and your backend should be "tensorflow", so it should be
input_shape=(224,224,3).

This helped me thanks.

@sammilei
Copy link

sammilei commented Nov 27, 2018

from keras import backend as K
if K.image_data_format() == 'channels_first':
input_shape = (IMG_CHANNELS, IMG_WIDTH, IMG_HEIGHT)
else:
input_shape = (IMG_WIDTH, IMG_HEIGHT, IMG_CHANNELS)

@PallawiSinghal
Copy link

Hi @sammilei how does this help. can u explain!

@wtyn
Copy link

wtyn commented Aug 7, 2019

In fact, this problem results from your initial input.
input_shape=(3,224,224) is for "theano"
and your backend should be "tensorflow", so it should be
input_shape=(224,224,3).

This help me, Thanks very much

@mrgransky
Copy link

in keras 2.2.5, I tried:
model.add(MaxPooling2D(pool_size=(2, 2), strides=(2, 2), data_format='channels_first'))

@knownstranger03
Copy link

Hello, I think taht you need to specify the dimension ordering:

  • Either change image_dim_ordering: 'tf' to image_dim_ordering: 'th' in your ~/.keras/keras.json
  • Specify the dim_ordering in your model like so:
model.add(MaxPooling2D(pool_size=(2, 2), dim_ordering="th"))

hope that helps

there is no dim_ordering parameter when using tensorflow.keras this line will throw another error

@knownstranger03
Copy link

thanks @cdalbergue That actually resolves the issue however I'm not sure why it's needed as we are using the Tensorflow backend - shouldn't the dim_ordering be 'tf' ?

there is no parameter dim_ordering() when you're using functions from tensorflow.keras. The problem here has different reasons in keras and TF.

In keras: change the input shape accoring to the backend framework in use or change the dim_ordering=(tf/th)

In tensorflow: goto the the code line where error is raised and change the padding='valid' parameter to padding='same'.If the parameter doesn't exist then add as in the example below.

model.add(MaxPooling2D((2,2), strides=(2,2), padding='same'))

more info on the topic can be found here - https://www.tensorflow.org/api_docs/python/tf/keras/layers/MaxPool2D

@Lotus-Blue
Copy link

In fact, this problem results from your initial input.
input_shape=(3,224,224) is for "theano"
and your backend should be "tensorflow", so it should be
input_shape=(224,224,3).

thank you

@jashshah999
Copy link

ValueError: Negative dimension size caused by subtracting 2 from 1 for '{{node max_pooling2d_2/MaxPool}} = MaxPoolT=DT_FLOAT, data_format="NHWC", ksize=[1, 2, 2, 1], padding="VALID", strides=[1, 2, 2, 1]' with input shapes: [?,1,1,64].

Tried all of the above solutions but nothing has worked. Please help!

CODE is below for reference:

import os
import numpy as np
from keras.models import Sequential
from keras.layers import Activation, Dropout, Flatten, Dense
from keras.preprocessing.image import ImageDataGenerator
from keras.layers import Convolution2D, MaxPooling2D, ZeroPadding2D
from keras import optimizers
import scipy
import keras
import pylab as pl
import matplotlib.cm as cm

img_width, img_height = 150, 150

train_data_dir = '/home/jashshah999/Desktop/data/train/'

datagen = ImageDataGenerator(rescale=1./255)

train_generator = datagen.flow_from_directory(
train_data_dir,
target_size=(img_width, img_height),
batch_size=16,
class_mode='binary')

model = Sequential()
model.add(Convolution2D(32, 3, 3, input_shape=(img_width,img_height,3)))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2),strides=(2,2),data_format="channels_last"))

model.add(Convolution2D(32, 3, 3))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2),strides=(2,2),data_format="channels_last"))

model.add(Convolution2D(64, 3, 3))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2),strides=(2,2),data_format="channels_last"))

model.add(Flatten())
model.add(Dense(64))
model.add(Activation('relu'))
model.add(Dropout(0.5))
model.add(Dense(1))
model.add(Activation('sigmoid'))

model.compile(loss='binary_crossentropy',
optimizer='rmsprop',
metrics=['accuracy'])

nb_epoch = 10
nb_train_samples = 2500

model.fit_generator(
train_generator,
samples_per_epoch=nb_train_samples,
nb_epoch=nb_epoch,
validation_data=validation_generator,
nb_val_samples=nb_validation_samples)

@Light--
Copy link

Light-- commented Aug 21, 2020

@burgalon It depends of the version of tensorflow that you are using. 0.10 would use "tf", 0.11 would use "th"

Edit: or the opposite, can't really remember

what about tf2?
@burgalon

@HiroshanG
Copy link

thanks @cdalbergue That actually resolves the issue however I'm not sure why it's needed as we are using the Tensorflow backend - shouldn't the dim_ordering be 'tf' ?

there is no parameter dim_ordering() when you're using functions from tensorflow.keras. The problem here has different reasons in keras and TF.

In keras: change the input shape accoring to the backend framework in use or change the dim_ordering=(tf/th)

In tensorflow: goto the the code line where error is raised and change the padding='valid' parameter to padding='same'.If the parameter doesn't exist then add as in the example below.

model.add(MaxPooling2D((2,2), strides=(2,2), padding='same'))

more info on the topic can be found here - https://www.tensorflow.org/api_docs/python/tf/keras/layers/MaxPool2D

thanks @cdalbergue That actually resolves the issue however I'm not sure why it's needed as we are using the Tensorflow backend - shouldn't the dim_ordering be 'tf' ?

there is no parameter dim_ordering() when you're using functions from tensorflow.keras. The problem here has different reasons in keras and TF.

In keras: change the input shape accoring to the backend framework in use or change the dim_ordering=(tf/th)

In tensorflow: goto the the code line where error is raised and change the padding='valid' parameter to padding='same'.If the parameter doesn't exist then add as in the example below.

model.add(MaxPooling2D((2,2), strides=(2,2), padding='same'))

more info on the topic can be found here - https://www.tensorflow.org/api_docs/python/tf/keras/layers/MaxPool2D

this worked for me... Thanks

@ronghui19
Copy link

Just add this:

from keras import backend as K
K.set_image_dim_ordering('th')

save my life

@fatemeshahbazi
Copy link

from keras import backend as K
if K.image_data_format() == 'channels_first':
input_shape = (IMG_CHANNELS, IMG_WIDTH, IMG_HEIGHT)
else:
input_shape = (IMG_WIDTH, IMG_HEIGHT, IMG_CHANNELS)

thanks a lot , it helped me:))

@kangzhiq
Copy link

For keras 2.0, it becomes:

import tensorflow.keras.backend as K
# to set the image order
K.set_image_data_format('channels_first')

See the link below:
Keras 2.0 release note

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests