Search code examples
tensorflowkeras-layer

Does Keras convolution option "channels_first" work with Tensorflow?


Keras documentation for a Conv2D layer implies that a value of "channels_first" can be used for the parameter data_format, supporting data that is in "NCHW" format, rather than the default "NHWC" format. But this doesn't seem to work in the code below.

import tensorflow as tf

tf.enable_eager_execution()

#this works:
data = tf.random.uniform((1,5,5,1))
model = tf.keras.Sequential([tf.keras.layers.Conv2D(1,(3,3),data_format="channels_last")])
model(data)       

#this doesn't:
data = tf.random.uniform((1,1,5,5))
model = tf.keras.Sequential([tf.keras.layers.Conv2D(1,(3,3),data_format="channels_first")])
model(data)       

For the "channels_first" case, I get the message:

UnimplementedError: Generic conv implementation only supports NHWC tensor format for now. [Op:Conv2D]

Am I making some silly error here?


Solution

  • Keras is built to work with two backends: Theano and TensorFlow.

    Theano uses the "channels_first" format (NCHW) while TensorFlow uses the "channels_last" format (NHWC). As far as I know the "channels_first" format isn't supported for the TensorFlow backend.