Keras Model Predict Shape Issue

@Deepti_Prasad
Iam using a "efficientnetv2_b0_imagenet pre trained model for Image Classification of Osteoarthritis. The model is Fitted Successfully the below is model summary

But when I run Predict on A Particular Image for this code

import cv2
import numpy as np
from keras.models import load_model



def predict_single_image(image_path):

image = keras.utils.load_img(image_path)
print(image)
image = np.array(image)
print(image.shape)
exp1 = np.expand_dims(image,axis=0)
print(exp1.shape)
predictions = model.predict(exp1)
return predictions

image_path = ‘/kaggle/input/knee-osteoarthritis-dataset-with-severity/train/2/9001695R.png’

predictions = predict_single_image(image_path)

print(“Predictions:”, predictions[0].argmax())

Output:
<PIL.Image.Image image mode=RGB size=224x224 at 0x7B20403151B0>
(224, 224, 3)
(1, 224, 224, 3)

I get this error

Shapes of all inputs must match: values[0].shape = [1,5] != values[1].shape = [0,5]
[[{{node Sum/input}}]] [Op:__inference_one_step_on_data_distributed_488765]

Please Suggest Changes.

textual traceback for reference:

InvalidArgumentError Traceback (most recent call last)
Cell In[60], line 20
16 return predictions
18 image_path = ‘/kaggle/input/knee-osteoarthritis-dataset-with-severity/train/2/9001695R.png’
—> 20 predictions = predict_single_image(image_path)
22 print(“Predictions:”, predictions[0].argmax())

Cell In[60], line 15, in predict_single_image(image_path)
13 exp1 = np.expand_dims(image,axis=0)
14 print(exp1.shape)
—> 15 predictions = model.predict(exp1)
16 return predictions

File /opt/conda/lib/python3.10/site-packages/keras/src/utils/traceback_utils.py:123, in filter_traceback..error_handler(*args, **kwargs)
120 filtered_tb = _process_traceback_frames(e.traceback)
121 # To get the full stack trace, call:
122 # keras.config.disable_traceback_filtering()
→ 123 raise e.with_traceback(filtered_tb) from None
124 finally:
125 del filtered_tb

File /opt/conda/lib/python3.10/site-packages/tensorflow/python/eager/execute.py:53, in quick_execute(op_name, num_outputs, inputs, attrs, ctx, name)
51 try:
52 ctx.ensure_initialized()
—> 53 tensors = pywrap_tfe.TFE_Py_Execute(ctx._handle, device_name, op_name,
54 inputs, attrs, num_outputs)
55 except core._NotOkStatusException as e:
56 if name is not None:

InvalidArgumentError: Graph execution error:

Detected at node Sum/input defined at (most recent call last):
File “/opt/conda/lib/python3.10/runpy.py”, line 196, in _run_module_as_main

File “/opt/conda/lib/python3.10/runpy.py”, line 86, in _run_code

File “/opt/conda/lib/python3.10/site-packages/ipykernel_launcher.py”, line 17, in

File “/opt/conda/lib/python3.10/site-packages/traitlets/config/application.py”, line 1043, in launch_instance

File “/opt/conda/lib/python3.10/site-packages/ipykernel/kernelapp.py”, line 701, in start

File “/opt/conda/lib/python3.10/site-packages/tornado/platform/asyncio.py”, line 195, in start

File “/opt/conda/lib/python3.10/asyncio/base_events.py”, line 603, in run_forever

File “/opt/conda/lib/python3.10/asyncio/base_events.py”, line 1909, in _run_once

File “/opt/conda/lib/python3.10/asyncio/events.py”, line 80, in _run

File “/opt/conda/lib/python3.10/site-packages/ipykernel/kernelbase.py”, line 534, in dispatch_queue

File “/opt/conda/lib/python3.10/site-packages/ipykernel/kernelbase.py”, line 523, in process_one

File “/opt/conda/lib/python3.10/site-packages/ipykernel/kernelbase.py”, line 429, in dispatch_shell

File “/opt/conda/lib/python3.10/site-packages/ipykernel/kernelbase.py”, line 767, in execute_request

File “/opt/conda/lib/python3.10/site-packages/ipykernel/ipkernel.py”, line 429, in do_execute

File “/opt/conda/lib/python3.10/site-packages/ipykernel/zmqshell.py”, line 549, in run_cell

File “/opt/conda/lib/python3.10/site-packages/IPython/core/interactiveshell.py”, line 3051, in run_cell

File “/opt/conda/lib/python3.10/site-packages/IPython/core/interactiveshell.py”, line 3106, in _run_cell

File “/opt/conda/lib/python3.10/site-packages/IPython/core/async_helpers.py”, line 129, in _pseudo_sync_runner

File “/opt/conda/lib/python3.10/site-packages/IPython/core/interactiveshell.py”, line 3311, in run_cell_async

File “/opt/conda/lib/python3.10/site-packages/IPython/core/interactiveshell.py”, line 3493, in run_ast_nodes

File “/opt/conda/lib/python3.10/site-packages/IPython/core/interactiveshell.py”, line 3553, in run_code

File “/tmp/ipykernel_34/630485134.py”, line 37, in

File “/tmp/ipykernel_34/630485134.py”, line 30, in predict_single_image

File “/opt/conda/lib/python3.10/site-packages/keras/src/utils/traceback_utils.py”, line 118, in error_handler

File “/opt/conda/lib/python3.10/site-packages/keras/src/backend/tensorflow/trainer.py”, line 513, in predict

File “/opt/conda/lib/python3.10/site-packages/keras/src/backend/tensorflow/trainer.py”, line 215, in one_step_on_data_distributed

File “/opt/conda/lib/python3.10/site-packages/keras/src/backend/tensorflow/trainer.py”, line 772, in reduce_per_replica

File “/opt/conda/lib/python3.10/site-packages/keras/src/backend/tensorflow/trainer.py”, line 765, in _reduce

Shapes of all inputs must match: values[0].shape = [1,5] != values[1].shape = [0,5]
[[{{node Sum/input}}]] [Op:__inference_one_step_on_data_distributed_488765]

Hello @omkar17

Can you share codes of your model architecture?

Your error states there is input shape mismatch.

Also I saw you got the data from kaggle, so you do have all the necessary dataset required to do the project? Kindly confirm this

Regards
DP

@Deepti_Prasad

Hello Maam ,

Yeh I have All the Data Set Required for the Project :
This is the Data Set Link:

This is the Kaggle Notebook link

Sample Architecture Code:
image

Regards
Omkar

Like the model.fit and model.evaluate works on the Data Directory but when try to predict for a specific image got the above issue.

Based on this message, states the images in the dataset you are using are not of same shape, so it is throwing you this error, once your defined the image path, convert all the images into a shape 256 or your desired shapes and then use those images for prediction.

You using image path in the predictions rather do the following, convert the images to a same image size or shape using the image_path and then use those image to the prediction.

Regards
DP

also you are using categorical cross entropy, I hope you the different between categorical crossentropy and sparse categorical crossentropy?

Also I notice you are not using one hot label to your dataset, because your number of class is more than 3, and use the true labels and then apply sparse categorical crossentropy.

The usage entirely depends on how you load your dataset. One advantage of using sparse categorical cross entropy is it saves time in memory as well as computation because it simply uses a single integer for a class, rather than a whole vector.

In case you want to label images use one.hot label, something like this

def augmentimages(image, label):

cast the image to float32
image = tf.cast(image, tf.float32)

normalize the pixel values
image = (image/255)

resize to 300 x 300
image = tf.image.resize(image, (300, 300))

label = tf.one_hot(label, 2)

return image, label

regards
DP

@Deepti_Prasad

The Above is the Updated NoteBook with Using Sparse Categorical, but now got issue with the model fit it self. Please Look at the Notebook and Suggest Changes

As we can see in the image above Output Shape and target shape same

did you use one hot label?

things to have a relook, using labels as inferred as well as int seems to be incorrect, you use either of the one.
labels referred as “inferred” (labels are generated from the directory structure ), None (no labels), or a list/tuple of integer labels of the same size as the number of text files found in the directory. Labels should be sorted according to the alphanumeric order of the text file paths.

The Value error tells your input shape is still not matching in dimensionality.

To solve this
define an input layer with your input shape, since your output layer cannot infer the shape of the tensor coming from the normalization layer

or

add an extra dimension to feature(input) tensor

input_tensor = tf.reshape(input_tensor,shape=(1,n))

Regards
DP