'Stuck implementation for CNN

def get_three_classes(x, y):
    indices_0, _ = np.where(y == 0.)
    indices_1, _ = np.where(y == 1.)
    indices_2, _ = np.where(y == 2.)

    indices = np.concatenate([indices_0, indices_1, indices_2], axis=0)
    
    x = x[indices]
    y = y[indices]
    
    count = x.shape[0]
    indices = np.random.choice(range(count), count, replace=False)
    
    x = x[indices]
    y = y[indices]
    
    y = tf.keras.utils.to_categorical(y)
    
    return x, y
(x_train, y_train), (x_test, y_test) = tf.keras.datasets.cifar10.load_data()

x_train, y_train = get_three_classes(x_train, y_train)
x_test, y_test = get_three_classes(x_test, y_test)

print(x_train.shape, y_train.shape)
print(x_test.shape, y_test.shape)

class_names = ['aeroplane', 'car', 'bird']

def show_random_examples (x, y, p):
  indices = np.random.choice(range(x.shape[0]), 10, replace = False)

  x= x [indices]
  y= y [indices]
  p = p[indices]

  plt.figure(figsize = (10,5))

  for i in range(10):
    plt.subplot(2,5, 1+i)
    plt.imshow(x[i])
    plt.xticks([])
    plt.yticks([])

    col = 'green' if np.argmax(y[i]) == np.argmax(p[i]) else 'red'
    plt.xlabel(class_names[np.argmax(p[i])], color = col)
  plt.show()

#Creating model
def create_model():
  def add_conv_block(model, num_filters):
    model.add(Conv2D(num_filters, 3, activation='relu', padding='same'))
    model.add(BatchNormalization())
    model.add(Conv2D(num_filters, 3, activation='relu'))
    model.add(MaxPooling2D(pool_size=2))
    model.add(Dropout(0.5))
    return model
  model = tf.keras.models.Sequential()
  model.add(Input(shape=(32,32,3)))

  model= add_conv_block(model, 32)
  model= add_conv_block(model, 64)
  model= add_conv_block(model, 128)

  model.add(Flatten())
  model.add(Dense(3, activation='softmax'))

  model.compile(
      loss='categorical_crossentropy',
      optimizer = 'adam', metrics = ['accuracy']
  )
  return model
h = model.fit (
    x_train/255., y_train,
    validation_data = (x_test/255., y_test),
    epochs=10, batch_size=128,
    callbacks=[tf.keras.callbacks.EarlyStopping(monitor='val_accuracy', patience=3),
               tf.keras.callbacks.ModelCheckpoint(
                   '/content/drive/MyDrive/models/model_val{val_accuracy:.3f}.h5',
                   save_best_only=True, save_weights_only=False,
                   monitor='val_accuracy') ]
)
model = tf.keras.models.load_model('/content/drive/MyDrive/models/model_val0.896.h5')
preds= model.predict(x_test/255.)

image = np.array(Image.open("/content/drive/MyDrive/thy3.jpg").resize((32, 32)))
print("shape: ", image.shape)
shape: (32, 32)
pr_mask = model.predict(image).round()

ValueError: in user code:

File "/usr/local/lib/python3.7/dist-packages/keras/engine/training.py", line 1621, in predict_function  *
    return step_function(self, iterator)
File "/usr/local/lib/python3.7/dist-packages/keras/engine/training.py", line 1611, in step_function  **
    outputs = model.distribute_strategy.run(run_step, args=(data,))
File "/usr/local/lib/python3.7/dist-packages/keras/engine/training.py", line 1604, in run_step  **
    outputs = model.predict_step(data)
File "/usr/local/lib/python3.7/dist-packages/keras/engine/training.py", line 1572, in predict_step
    return self(x, training=False)
File "/usr/local/lib/python3.7/dist-packages/keras/utils/traceback_utils.py", line 67, in error_handler
    raise e.with_traceback(filtered_tb) from None
File "/usr/local/lib/python3.7/dist-packages/keras/engine/input_spec.py", line 263, in assert_input_compatibility
    raise ValueError(f'Input {input_index} of layer "{layer_name}" is '

ValueError: Input 0 of layer "sequential" is incompatible with the layer: expected shape=(None, 32, 32, 3), found shape=(32, 32, 3)

Hey everyone, this is code im working on it for project but problem is i cannot implement random photos on this model.Getting this error message, I just want to get result for random photos, and model predict it.Its basic tensorflow project only using cifar10 dataset, and only 3 classes outputs. Model predict is it car, airplane or bird thats it. Why i want is lets say i found airjet photo from web and wants this model predict it, is it airplane or bird? prediction could be wrong or accurate i dont care. But problem is i cannot format photos, or maybe you can give me idea how can i deal with that . Thanks for your answers.



Solution 1:[1]

The image used for the predict function is in your code defined as follows:

image = np.array(Image.open("/content/drive/MyDrive/thy3.jpg").resize((32, 32)))

Which corresponds with the following shape according to the error message you posted:

(32, 32, 3)

Error message posted:
ValueError: Input 0 of layer "sequential" is incompatible with the layer: expected shape=(None, 32, 32, 3), found shape=(32, 32, 3)

But the model requires the image to have a batch dimension for the prediciton, like:

(1, 32, 32, 3)

If your image is a 3-channel with width=32 and height=32 use to reshape it:

image = np.array(Image.open("/content/drive/MyDrive/thy3.jpg").reshape((1, 32, 32, 3)))

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1