Search code examples
kerasneural-networkruntime-errorconv-neural-network

Why can't I fit the image data into model.predict in my CNN?


I have built and trained my CNN model and I want to test it. I wrote a script that takes in an input image from the directory path specified, I then preprocessed the image and rescaled the pixel values to be between 0 and 1. I have also resized the image into the right dimensions and used the model.predict() to give a prediction. However when I run the code:

from keras.models import Sequential
from keras_preprocessing.image import *
from keras.layers import *
import tensorflow as tf
import numpy as np
from keras.layers.experimental.preprocessing import Rescaling
import os
import cv2
from keras.models import *

img_size = 250

#Load weights into new model
filepath = os.getcwd() + "/trained_model.h5"

model = load_model(filepath)
print("Loaded model from disk")

#Scales the pixel values to between 0 to 1
#datagen = ImageDataGenerator(rescale=1.0/255.0)

#Prepares Testing Data

testing_dataset = cv2.imread(os.getcwd() + "/cats and dogs images/single test sample/505.png")
#img = datagen.flow_from_directory(testing_dataset, target_size=(img_size,img_size))

img = cv2.resize(testing_dataset, (img_size,img_size))
newimg = np.asarray(img)
pixels = newimg.astype('float32')
pixels /= 255.0
print(pixels.shape)


model.predict(x=pixels)

this error pops up:

Loaded model from disk
(250, 250, 3)
Traceback (most recent call last):
  File "C:\Users\Jackson\Documents\Programming\Python Projects\Neural Network That Deteremines Cats and Dogs\Test Trained Model.py", line 34, in <module>
    model.predict(x=pixels)
  File "C:\Users\Jackson\AppData\Local\Programs\Python\Python38\lib\site-packages\tensorflow\python\keras\engine\training.py", line 130, in _method_wrapper
    return method(self, *args, **kwargs)
  File "C:\Users\Jackson\AppData\Local\Programs\Python\Python38\lib\site-packages\tensorflow\python\keras\engine\training.py", line 1599, in predict
    tmp_batch_outputs = predict_function(iterator)
  File "C:\Users\Jackson\AppData\Local\Programs\Python\Python38\lib\site-packages\tensorflow\python\eager\def_function.py", line 780, in __call__
    result = self._call(*args, **kwds)
  File "C:\Users\Jackson\AppData\Local\Programs\Python\Python38\lib\site-packages\tensorflow\python\eager\def_function.py", line 823, in _call
    self._initialize(args, kwds, add_initializers_to=initializers)
  File "C:\Users\Jackson\AppData\Local\Programs\Python\Python38\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
  File "C:\Users\Jackson\AppData\Local\Programs\Python\Python38\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)
  File "C:\Users\Jackson\AppData\Local\Programs\Python\Python38\lib\site-packages\tensorflow\python\eager\function.py", line 3213, in _maybe_define_function
    graph_function = self._create_graph_function(args, kwargs)
  File "C:\Users\Jackson\AppData\Local\Programs\Python\Python38\lib\site-packages\tensorflow\python\eager\function.py", line 3065, in _create_graph_function
    func_graph_module.func_graph_from_py_func(
  File "C:\Users\Jackson\AppData\Local\Programs\Python\Python38\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)
  File "C:\Users\Jackson\AppData\Local\Programs\Python\Python38\lib\site-packages\tensorflow\python\eager\def_function.py", line 600, in wrapped_fn
    return weak_wrapped_fn().__wrapped__(*args, **kwds)
  File "C:\Users\Jackson\AppData\Local\Programs\Python\Python38\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:

    C:\Users\Jackson\AppData\Local\Programs\Python\Python38\lib\site-packages\tensorflow\python\keras\engine\training.py:1462 predict_function  *
        return step_function(self, iterator)
    C:\Users\Jackson\AppData\Local\Programs\Python\Python38\lib\site-packages\tensorflow\python\keras\engine\training.py:1452 step_function  **
        outputs = model.distribute_strategy.run(run_step, args=(data,))
    C:\Users\Jackson\AppData\Local\Programs\Python\Python38\lib\site-packages\tensorflow\python\distribute\distribute_lib.py:1211 run
        return self._extended.call_for_each_replica(fn, args=args, kwargs=kwargs)
    C:\Users\Jackson\AppData\Local\Programs\Python\Python38\lib\site-packages\tensorflow\python\distribute\distribute_lib.py:2585 call_for_each_replica
        return self._call_for_each_replica(fn, args, kwargs)
    C:\Users\Jackson\AppData\Local\Programs\Python\Python38\lib\site-packages\tensorflow\python\distribute\distribute_lib.py:2945 _call_for_each_replica
        return fn(*args, **kwargs)
    C:\Users\Jackson\AppData\Local\Programs\Python\Python38\lib\site-packages\tensorflow\python\keras\engine\training.py:1445 run_step  **
        outputs = model.predict_step(data)
    C:\Users\Jackson\AppData\Local\Programs\Python\Python38\lib\site-packages\tensorflow\python\keras\engine\training.py:1418 predict_step
        return self(x, training=False)
    C:\Users\Jackson\AppData\Local\Programs\Python\Python38\lib\site-packages\tensorflow\python\keras\engine\base_layer.py:975 __call__
        input_spec.assert_input_compatibility(self.input_spec, inputs,
    C:\Users\Jackson\AppData\Local\Programs\Python\Python38\lib\site-packages\tensorflow\python\keras\engine\input_spec.py:191 assert_input_compatibility
        raise ValueError('Input ' + str(input_index) + ' of layer ' +

    ValueError: Input 0 of layer sequential is incompatible with the layer: : expected min_ndim=4, found ndim=3. Full shape received: [None, 250, 3]

What am I doing wrong or am I just missing something? Also, I have tried the same with model.predict_classes() and model.predict_generator() but the same error appears.


Solution

  • If you're doing everything correct regarding the image input shape that it matches the required input shape of the model then it's most likely that the model expects to receive a batch of images of the size (250, 250, 3) so if you have an image that you want to test on the input shape should be of size (1, 250, 250, 3) this means you're passing a batch of size 1 image.

    What your error message means is that the model expects an input shape of 4 dimensions and an input shape of 3 dimensions was passed, you need to include the batch dimension, so i think adding this line after the normalizing of the image should make it work.

    pixels = np.expand_dims(pixels, axis=0)
    

    At printing the shape line the pixels shape should be (1, 250, 250, 3)