ValueError: Input 0 of layer "sequential_13" is incompatible with the layer:(cifar-10) with python

Issue

I faced the following problems in conducting Deep Learning practice using Python. How do I solve this problem? I want to recognize Cifar-10 data. However, an error occurs when you write as follows: What should I do to solve this problem? Please help me.

I am using Google Collab(Python 3 backend)

I have also Read this post here but don’t know what that guy is trying to say.

Below is the full version of code and error.

import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import tensorflow as tf
from tensorflow import keras

data = keras.datasets.cifar10
df = data.load_data()
(X_train, y_train),(X_test, y_test) = df
X_train.shape
X_test.shape
X_train[0]
X_train = X_train.astype('float32')         
X_test = X_test.astype('float32')
X_train /= 255.0              
X_test /= 255.0
plt.matshow(X_train[0])
for i in range(10):
  plt.matshow(X_train[i])
y_test.shape
y_test.ndim
X_train_flat[0].ndim

from tensorflow.keras import datasets, layers, models
from tensorflow.keras.layers import Dense, Dropout, Activation, Flatten, Conv2D, MaxPooling2D



"""
I have ask many sources to increase the accuracy rate of this code since the unmodified code was giving
accuracy of only 0.1000 even after icreasing the epochs to 25. Hence, this is the modified version.
"""
model = tf.keras.models.Sequential()

model.add(tf.keras.layers.InputLayer(
                         input_shape=(32,32,3)))

model.add(tf.keras.layers.Conv2D(32, (3, 3), 
                                 padding='same', 
                                 activation='relu'))

model.add(tf.keras.layers.MaxPooling2D(pool_size=(2, 2), 
                                       strides=(2,2)))

model.add(tf.keras.layers.Flatten())

model.add(tf.keras.layers.Dense(10, 
                                activation=tf.nn.softmax))



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

X_train_flat[0].shape

#Train the model
model.summary() 
model.fit(X_train, y_train, batch_size=32, epochs=10)
y_test
y_pred = model.predict(X_test_flat)
y_pred
y_test
model.evaluate(X_test_flat, y_test)

ERROR


---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-88-02bbbb09a8d3> in <module>()
----> 1 y_pred = model.predict(X_test_flat)

1 frames
/usr/local/lib/python3.7/dist-packages/tensorflow/python/framework/func_graph.py in autograph_handler(*args, **kwargs)
   1145           except Exception as e:  # pylint:disable=broad-except
   1146             if hasattr(e, "ag_error_metadata"):
-> 1147               raise e.ag_error_metadata.to_exception(e)
   1148             else:
   1149               raise

ValueError: in user code:

    File "/usr/local/lib/python3.7/dist-packages/keras/engine/training.py", line 1801, in predict_function  *
        return step_function(self, iterator)
    File "/usr/local/lib/python3.7/dist-packages/keras/engine/training.py", line 1790, 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 1783, in run_step  **
        outputs = model.predict_step(data)
    File "/usr/local/lib/python3.7/dist-packages/keras/engine/training.py", line 1751, 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 264, in assert_input_compatibility
        raise ValueError(f'Input {input_index} of layer "{layer_name}" is '

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

Please help me I need to submit this within tomorrow.

Solution

As described in error, the problem is due to incompatible shape of X_test_flat in model.predict(X_test_flat). change your code as below:

y_pred = model.predict(X_test)
y_pred
y_test
model.evaluate(X_test, y_test)

Answered By – Masoud Gheisari

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published