4
votes

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)
1

1 Answers

11
votes

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')