Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Channels first with Keras?

I'm trying to use my keras model with a keras-to-caffe conversion script; Whenever I try to run the script, it loads my model and then gives me an error that says "only channels-first is supported". I'm feeding my model images with the shape (24,24,3) - but it wants (3,24,24).

Whenever I try to train my model on images of the shape (3,24,24), i get this error (it thinks im feeding it a 3x24 image with 24 channels, i believe);

ValueError: Negative dimension size caused by subtracting 3 from 1 for 'conv2d_2/convolution' (op: 'Conv2D') with input shapes: [?,1,22,32], [3,3,32,64].

How can i feed my keras model channels-first images?

(Model code in case anyone needs it: i'm just doing a simple classification problem)

input_1 = Input(shape=input_shape) # input shape is 24,24,3 - needs to be 3,24,24


conv_1 = Conv2D(32, kernel_size=(3, 3),
             activation='relu',
             input_shape=input_shape)(input_1)

conv_2 = Conv2D(64, (3, 3), activation='relu')(conv_1)

pool_1 = MaxPooling2D(pool_size=(2, 2))(conv_2)

drop_1 = Dropout(0.25)(pool_1)

flatten_1 = Flatten()(drop_1)

dense_1 = Dense(128, activation='relu')(flatten_1)

drop_2 = Dropout(0.5)(dense_1)

dense_2 = Dense(128, activation='relu')(drop_2)

drop_3 = Dropout(0.5)(dense_2)

dense_3 = Dense(num_classes, activation='softmax')(drop_3)

model = Model(inputs=input_1, outputs=dense_3)

model.compile(loss=keras.losses.categorical_crossentropy,
              optimizer=keras.optimizers.Adadelta(),
              metrics=['accuracy'])

model.fit(x_train, y_train,
          batch_size=batch_size,
          epochs=epochs,
          validation_data=(x_test, y_test),
          verbose=1)
like image 944
Robbie Barrat Avatar asked Oct 26 '17 22:10

Robbie Barrat


People also ask

What is Channel first in keras?

The ordering of the dimensions in the inputs. channels_last corresponds to inputs with shape (batch_size, height, width, channels) while channels_first corresponds to inputs with shape (batch_size, channels, height, width) . It defaults to the image_data_format value found in your Keras config file at ~/. keras/keras.

What does channel first mean?

Channels first means that in a specific tensor (consider a photo), you would have (Number_Of_Channels, Height , Width) .

How do you change the image channel in Python?

Try img. transpose(2,0,1) or img. transpose(2,1,0) .


1 Answers

Every convolutional layer accepts the argument data_format='channels_first'.

You can also find your keras.json file (in <yourUserFolder>/.keras) and set this as a default configuration.

Edit: @Gal's comment is a very interesting point. If you're planning on using more than one computer, it might be better to set the config in your code: keras.backend.set_image_data_format('channels_first')

like image 51
Daniel Möller Avatar answered Sep 30 '22 07:09

Daniel Möller