0

I am a novice on the subject and I encounter an error, can anyone help me ?

Trying to recognize shapes with a handmade dataset.

I'm Having trouble solving this error:

ValueError: Input 0 of layer sequential is incompatible with the layer: expected axis -1 of input shape to have value 3 but received input with shape [None, 100, 100, 1]

Here is my code :

from keras.models import Sequential
from keras.layers import Dense, Flatten, Dropout
from keras.layers import Convolution2D, MaxPooling2D
from keras.preprocessing.image import ImageDataGenerator
from keras.preprocessing.image import load_img,img_to_array

model1 = Sequential()
model1.add(Convolution2D(32, (3,3), activation='sigmoid',input_shape=(100,100,3)))
model1.add(MaxPooling2D(pool_size=(2,2)))
model1.add(Convolution2D(32,(3,3),activation='relu'))
model1.add(MaxPooling2D(pool_size=(2,2)))
model1.add(Convolution2D(64,(3,3),activation='relu'))
model1.add(Convolution2D(64,(3,3),activation='relu'))
model1.add(MaxPooling2D(pool_size=(2,2)))

model1.add(Flatten())
model1.add(Dense(64,activation='relu'))
model1.add(Dropout(0.2))
model1.add(Dense(1,activation='sigmoid'))
model1.compile(loss='binary_crossentropy',
              optimizer='adam',
              metrics=['accuracy'])

model1.summary()


train_datagen = ImageDataGenerator(
        width_shift_range=0.2, height_shift_range=0.2,
        rotation_range=40,
        zoom_range=0.2,
        horizontal_flip=True,
        rescale=1/255,
        fill_mode='nearest')


validation_datagen = ImageDataGenerator(
        rescale=0.1,
        fill_mode='nearest')

# trainning
train_generator = train_datagen.flow_from_directory(
        'data/train',
        target_size=(100, 100),
        batch_size=16,
        class_mode='binary')
validation_generator = validation_datagen.flow_from_directory(
        'data/validation',
        target_size=(100, 100),
        batch_size=16,
        class_mode='binary')


h = model1.fit_generator(
        train_generator,
        epochs=10,
        validation_data=validation_generator)




img = load_img('img.jpeg', color_mode="grayscale", target_size=(100, 100))
img = img_to_array(img)
img = img.reshape((1, img.shape[0], img.shape[1], img.shape[2]))

prediction = model1.predict(img)




'The output:'

Traceback (most recent call last):
  /custom_train.py", line 68, in <module>
    prediction = model1.predict(img)
  \lib\site-packages\tensorflow\python\keras\engine\training.py", line 130, in _method_wrapper
    return method(self, *args, **kwargs)
  \lib\site-packages\tensorflow\python\keras\engine\training.py", line 1599, in predict
    tmp_batch_outputs = predict_function(iterator)
  \lib\site-packages\tensorflow\python\eager\def_function.py", line 780, in __call__
    result = self._call(*args, **kwds)
  \lib\site-packages\tensorflow\python\eager\def_function.py", line 823, in _call
    self._initialize(args, kwds, add_initializers_to=initializers)
  \lib\site-packages\tensorflow\python\eager\def_function.py", line 696, in _initialize
    self._stateful_fn._get_concrete_function_internal_garbage_collected(  # pylint: disable=protected-access
  \lib\site-packages\tensorflow\python\eager\function.py", line 2855, in _get_concrete_function_internal_garbage_collected
    graph_function, _, _ = self._maybe_define_function(args, kwargs)
  \lib\site-packages\tensorflow\python\eager\function.py", line 3213, in _maybe_define_function
    graph_function = self._create_graph_function(args, kwargs)
  \lib\site-packages\tensorflow\python\eager\function.py", line 3065, in _create_graph_function
    func_graph_module.func_graph_from_py_func(
  \lib\site-packages\tensorflow\python\framework\func_graph.py", line 986, in func_graph_from_py_func
    func_outputs = python_func(*func_args, **func_kwargs)
  \lib\site-packages\tensorflow\python\eager\def_function.py", line 600, in wrapped_fn
    return weak_wrapped_fn().__wrapped__(*args, **kwds)
  \lib\site-packages\tensorflow\python\framework\func_graph.py", line 973, in wrapper
    raise e.ag_error_metadata.to_exception(e)
ValueError: in user code:

    \lib\site-packages\tensorflow\python\keras\engine\training.py:1462 predict_function  *
        return step_function(self, iterator)
    \lib\site-packages\tensorflow\python\keras\engine\training.py:1452 step_function  **
        outputs = model.distribute_strategy.run(run_step, args=(data,))
    \lib\site-packages\tensorflow\python\distribute\distribute_lib.py:1211 run
        return self._extended.call_for_each_replica(fn, args=args, kwargs=kwargs)
    \lib\site-packages\tensorflow\python\distribute\distribute_lib.py:2585 call_for_each_replica
        return self._call_for_each_replica(fn, args, kwargs)
    \lib\site-packages\tensorflow\python\distribute\distribute_lib.py:2945 _call_for_each_replica
        return fn(*args, **kwargs)
    \lib\site-packages\tensorflow\python\keras\engine\training.py:1445 run_step  **
        outputs = model.predict_step(data)
    \lib\site-packages\tensorflow\python\keras\engine\training.py:1418 predict_step
        return self(x, training=False)
    \lib\site-packages\tensorflow\python\keras\engine\base_layer.py:975 __call__
        input_spec.assert_input_compatibility(self.input_spec, inputs,
    \lib\site-packages\tensorflow\python\keras\engine\input_spec.py:212 assert_input_compatibility
        raise ValueError(

    ValueError: Input 0 of layer sequential is incompatible with the layer: expected axis -1 of input shape to have value 3 but received input with shape [None, 100, 100, 1]

``

1 Answer 1

1

The input shape of the model has an image of 100x100x3. So it means that the image has 3 channels (RGB image).

However, in this line:

img = load_img('img.jpeg', color_mode="grayscale", target_size=(100, 100))

You loaded the img in grayscale format, which mean the image shape willl be (100x100x1) which means only one channel.

Try to change that line to :

img = load_img('img.jpeg', color_mode="rgb", target_size=(100, 100))

Keras documentation indicates that:

color_mode: One of "grayscale", "rgb", "rgba". Default: "rgb". Whether the images will be converted to have 1, 3, or 4 channels.

Sign up to request clarification or add additional context in comments.

1 Comment

Okay, thanks a lot, problem solved!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.