TFF : ValueError: Shapes (None, 1) and (None,) are incompatible

Viewed 135

I use TFF and My dataset has a binary_mode class, this is how I declared my inputs :

genv0 = img_genv.flow_from_directory(pathv0,(224, 224),'rgb', batch_size=2, class_mode='binary')
train_data = tf.data.Dataset.from_generator(genv0, output_types=(tf.float32, tf.float32), output_shapes = ([2,224,224,3],[2,1])

Here is my sample_batch :

images, labels = next(img_gen.flow_from_directory(path0,target_size=(224, 224), batch_size=2, class_mode='binary'))

and I add this layer in my model

model_output = tf.keras.layers.Dense(1, activation="sigmoid")(last_layer)
 model.compile(optimizer=tf.keras.optimizers.SGD(lr=0.001)
             loss=tf.keras.losses.BinaryCrossentropy(),
              metrics=([tf.keras.metrics.BinaryAccuracy()))

When running my code, I find this error :

 ValueError: Shapes (None, 1) and (None,) are incompatible

I think the problem is that sample_batch does not take label with bainary mode. How can I resolve this problem Thanks

1 Answers

From its name, it seems like in binary mode the label may be a scalar 1 or 0 with shape [], rather than a tensor [1] or [0]. Keras generally likes tensors.

Perhaps try a tf.reshape or tf.expand_dims to turn scalars into tensors. If labels is shape [batch_size], we want to turn that into shape [batch_size, 1] with:

labels = tf.reshape(labels, shape=[-1, 1])
Related