ValueError: Shapes (None, 10) and (None, 32, 32, 10) are incompatible (Keras tuner)

Question:

I have a CNN based on 32 by 32 images defined as follows:

from keras.datasets import cifar10
(x_train, y_train), (x_test, y_test) = cifar10.load_data()

img = plt.imshow(x_train[0])
print('The label is:', y_train[0])
img = plt.imshow(x_train[1])
print('The label is:', y_train[1])

y_train_one_hot = keras.utils.to_categorical(y_train, 10)
y_test_one_hot = keras.utils.to_categorical(y_test, 10)

print('The one hot label is:', y_train_one_hot[1])

x_train = x_train.astype('float32')
x_test = x_test.astype('float32')
x_train = x_train / 255
x_test = x_test / 255

x_train[0]

Model:

from tensorflow import keras
from tensorflow.keras import layers
from kerastuner.tuners import RandomSearch

def build_model(hp):
    model = keras.Sequential()
    model.add(layers.Dense(units=hp.Int('units',
                                        min_value=32,
                                        max_value=512,
                                        step=32),
                           activation='relu'))
    input_shape=(32,32,3)
    model.add(layers.Dense(10, activation='softmax'))
    model.compile(
        optimizer=keras.optimizers.Adam(
            hp.Choice('learning_rate',
                      values=[1e-2, 1e-3, 1e-4])),
        loss='categorical_crossentropy',
        metrics=['accuracy'])
    
    return model

    model.compile(loss='categorical_crossentropy',
              optimizer='adam',
              metrics=['accuracy'])

And I’m trying to use the keras tuner as follows:

tuner = RandomSearch(
build_model,
objective='val_accuracy',
max_trials=5,
executions_per_trial=3,
directory='my_dir',
project_name='helloworld')
tuner.search_space_summary()

from kerastuner import RandomSearch
from kerastuner.engine.hyperparameters import HyperParameters

tuner_search=RandomSearch(build_model,
                          objective='val_accuracy',
                          max_trials=5,directory='output',project_name="stuff2")

tuner_search.search(x_train,y_train_one_hot,epochs=3,validation_split=0.1)

But it returns: ValueError: Shapes (None, 10) and (None, 32, 32, 10) are incompatible

I’ve tried reading up on this and can’t figure out what the problem is since I have defined the model as categorical?

Asked By: Paze

||

Answers:

The problem was rooted in the shape of one of the variables not matching the preferred shape as I was trying to use custom data. I just had to re-define the shapes.

Answered By: Paze

Change

loss='categorical_crossentropy' 

to

loss='sparse_categorical_crossentropy'
Answered By: hackerinheels
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.