pallav rai
pallav rai

Reputation: 21

ValueError:Tensor("inputs:0", shape=(None, 256, 256, 3), dtype=uint8)

I don't know how to solve this error i also tried converting it into float32

import cv2
import tensorflow as tf
import numpy as np

CATEGORIES = ["gas", "break","stop"]

model = tf.keras.models.load_model("trained")


def prepare(filepath):
    IMG_SIZE = 256  # 50 in txt-based
    img_array = cv2.imread(filepath)
    new_array = cv2.resize(img_array, (IMG_SIZE, IMG_SIZE))
    arr=new_array.reshape(-1, IMG_SIZE, IMG_SIZE, 3)
    return arr

x=prepare('img.jpg')
x = tf.keras.utils.normalize(x, axis=1)
x = x.astype('float32') 
print(x.dtype)
prediction = model.predict([x])
print(prediction)  # will be a list in a list.
print(CATEGORIES[np.argmax(prediction[0])])

float32 --------------------------------------------------------------------------- ValueError Traceback (most recent call last) in 11 x = x.astype('float32') 12 print(x.dtype) ---> 13 prediction = model.predict([x]) 14 print(prediction) # will be a list in a list. 15 print(CATEGORIES[np.argmax(prediction[0])])

~\anaconda3\envs\tf\lib\site-packages\tensorflow_core\python\keras\engine\training.py in predict(self, x, batch_size, verbose, steps, callbacks, max_queue_size, workers, use_multiprocessing) 1011
max_queue_size=max_queue_size, 1012 workers=workers, -> 1013 use_multiprocessing=use_multiprocessing) 1014 1015 def reset_metrics(self):

~\anaconda3\envs\tf\lib\site-packages\tensorflow_core\python\keras\engine\training_v2.py in predict(self, model, x, batch_size, verbose, steps, callbacks, max_queue_size, workers, use_multiprocessing, **kwargs) 496 model, ModeKeys.PREDICT, x=x, batch_size=batch_size, verbose=verbose, 497 steps=steps, callbacks=callbacks, max_queue_size=max_queue_size, --> 498 workers=workers, use_multiprocessing=use_multiprocessing, **kwargs) 499 500

~\anaconda3\envs\tf\lib\site-packages\tensorflow_core\python\keras\engine\training_v2.py in _model_iteration(self, model, mode, x, y, batch_size, verbose, sample_weight, steps, callbacks, max_queue_size, workers, use_multiprocessing, **kwargs) 473 mode=mode, 474 training_context=training_context, --> 475 total_epochs=1) 476 cbks.make_logs(model, epoch_logs, result, mode) 477

~\anaconda3\envs\tf\lib\site-packages\tensorflow_core\python\keras\engine\training_v2.py in run_one_epoch(model, iterator, execution_function, dataset_size, batch_size, strategy, steps_per_epoch, num_samples, mode, training_context, total_epochs) 126 step=step, mode=mode, size=current_batch_size) as batch_logs: 127 try: --> 128 batch_outs = execution_function(iterator) 129 except (StopIteration, errors.OutOfRangeError): 130 # TODO(kaftan): File bug about tf function and errors.OutOfRangeError?

~\anaconda3\envs\tf\lib\site-packages\tensorflow_core\python\keras\engine\training_v2_utils.py in execution_function(input_fn) 96 # numpy translates Tensors to values in Eager mode. 97 return nest.map_structure(_non_none_constant_value, ---> 98 distributed_function(input_fn)) 99 100 return execution_function

~\anaconda3\envs\tf\lib\site-packages\tensorflow_core\python\eager\def_function.py in call(self, *args, **kwds) 566 xla_context.Exit() 567 else: --> 568 result = self._call(*args, **kwds) 569 570 if tracing_count == self._get_tracing_count():

~\anaconda3\envs\tf\lib\site-packages\tensorflow_core\python\eager\def_function.py in _call(self, *args, **kwds) 613 # This is the first call of call, so we have to initialize. 614 initializers = [] --> 615 self._initialize(args, kwds, add_initializers_to=initializers) 616 finally: 617 # At this point we know that the initialization is complete (or less

~\anaconda3\envs\tf\lib\site-packages\tensorflow_core\python\eager\def_function.py in _initialize(self, args, kwds, add_initializers_to) 495 self._concrete_stateful_fn = ( 496 self._stateful_fn._get_concrete_function_internal_garbage_collected(

pylint: disable=protected-access

--> 497 *args, **kwds)) 498 499 def invalid_creator_scope(*unused_args, **unused_kwds):

~\anaconda3\envs\tf\lib\site-packages\tensorflow_core\python\eager\function.py in _get_concrete_function_internal_garbage_collected(self, *args, **kwargs) 2387 args, kwargs = None, None 2388 with self._lock: -> 2389 graph_function, _, _ = self._maybe_define_function(args, kwargs) 2390 return graph_function 2391

~\anaconda3\envs\tf\lib\site-packages\tensorflow_core\python\eager\function.py in _maybe_define_function(self, args, kwargs) 2701 2702
self._function_cache.missed.add(call_context_key) -> 2703 graph_function = self._create_graph_function(args, kwargs) 2704 self._function_cache.primary[cache_key] = graph_function 2705 return graph_function, args, kwargs

~\anaconda3\envs\tf\lib\site-packages\tensorflow_core\python\eager\function.py in _create_graph_function(self, args, kwargs, override_flat_arg_shapes) 2591 arg_names=arg_names,
2592 override_flat_arg_shapes=override_flat_arg_shapes, -> 2593 capture_by_value=self._capture_by_value), 2594 self._function_attributes, 2595 # Tell the ConcreteFunction to clean up its graph once it goes out of

~\anaconda3\envs\tf\lib\site-packages\tensorflow_core\python\framework\func_graph.py in func_graph_from_py_func(name, python_func, args, kwargs, signature, func_graph, autograph, autograph_options, add_control_dependencies, arg_names, op_return_value, collections, capture_by_value, override_flat_arg_shapes) 976 converted_func) 977 --> 978 func_outputs = python_func(*func_args, **func_kwargs) 979 980 # invariant: func_outputs contains only Tensors, CompositeTensors,

~\anaconda3\envs\tf\lib\site-packages\tensorflow_core\python\eager\def_function.py in wrapped_fn(*args, **kwds) 437 # wrapped allows AutoGraph to swap in a converted function. We give 438 # the function a weak reference to itself to avoid a reference cycle. --> 439 return weak_wrapped_fn().wrapped(*args, **kwds) 440 weak_wrapped_fn = weakref.ref(wrapped_fn) 441

~\anaconda3\envs\tf\lib\site-packages\tensorflow_core\python\keras\engine\training_v2_utils.py in distributed_function(input_iterator) 83 args = _prepare_feed_values(model, input_iterator, mode, strategy) 84 outputs = strategy.experimental_run_v2( ---> 85 per_replica_function, args=args) 86 # Out of PerReplica outputs reduce or pick values to return. 87 all_outputs = dist_utils.unwrap_output_dict(

~\anaconda3\envs\tf\lib\site-packages\tensorflow_core\python\distribute\distribute_lib.py in experimental_run_v2(self, fn, args, kwargs) 761 fn = autograph.tf_convert(fn, ag_ctx.control_status_ctx(), 762 convert_by_default=False) --> 763 return self._extended.call_for_each_replica(fn, args=args, kwargs=kwargs) 764 765 def reduce(self, reduce_op, value, axis):

~\anaconda3\envs\tf\lib\site-packages\tensorflow_core\python\distribute\distribute_lib.py in call_for_each_replica(self, fn, args, kwargs) 1817 kwargs = {} 1818 with self._container_strategy().scope(): -> 1819 return self._call_for_each_replica(fn, args, kwargs) 1820 1821 def _call_for_each_replica(self, fn, args, kwargs):

~\anaconda3\envs\tf\lib\site-packages\tensorflow_core\python\distribute\distribute_lib.py in _call_for_each_replica(self, fn, args, kwargs) 2162
self._container_strategy(), 2163
replica_id_in_sync_group=constant_op.constant(0, dtypes.int32)): -> 2164 return fn(*args, **kwargs) 2165 2166 def _reduce_to(self, reduce_op, value, destinations):

~\anaconda3\envs\tf\lib\site-packages\tensorflow_core\python\autograph\impl\api.py in wrapper(*args, **kwargs) 290 def wrapper(*args, **kwargs): 291 with ag_ctx.ControlStatusCtx(status=ag_ctx.Status.DISABLED): --> 292 return func(*args, **kwargs) 293 294 if inspect.isfunction(func) or inspect.ismethod(func):

~\anaconda3\envs\tf\lib\site-packages\tensorflow_core\python\keras\engine\training_v2_utils.py in _predict_on_batch(failed resolving arguments) 210 del y, sample_weights 211 # Note that the x and batch_index is already per-replica value. --> 212 result = predict_on_batch(model, x) 213 if batch_index is None: 214 return result

~\anaconda3\envs\tf\lib\site-packages\tensorflow_core\python\keras\engine\training_v2_utils.py in predict_on_batch(model, x, standalone) 554 555 with backend.eager_learning_phase_scope(0): --> 556 return predict_on_batch_fn(inputs) # pylint: disable=not-callable

~\anaconda3\envs\tf\lib\site-packages\tensorflow_core\python\keras\engine\base_layer.py in call(self, inputs, *args, **kwargs) 776 outputs = base_layer_utils.mark_as_return(outputs, acd) 777 else: --> 778 outputs = call_fn(cast_inputs, *args, **kwargs) 779 780 except errors.OperatorNotAllowedInGraphError as e:

~\anaconda3\envs\tf\lib\site-packages\tensorflow_core\python\keras\engine\sequential.py in call(self, inputs, training, mask) 279 kwargs['training'] = training 280 --> 281 outputs = layer(inputs, **kwargs) 282 283 # outputs will be the inputs to the next layer.

~\anaconda3\envs\tf\lib\site-packages\tensorflow_core\python\keras\engine\base_layer.py in call(self, inputs, *args, **kwargs) 776 outputs = base_layer_utils.mark_as_return(outputs, acd) 777 else: --> 778 outputs = call_fn(cast_inputs, *args, **kwargs) 779 780 except errors.OperatorNotAllowedInGraphError as e:

~\anaconda3\envs\tf\lib\site-packages\tensorflow_core\python\keras\saving\saved_model\utils.py in return_outputs_and_add_losses(*args, **kwargs) 57 inputs = args[inputs_arg_index] 58 args = args[inputs_arg_index + 1:] ---> 59 outputs, losses = fn(inputs, *args, **kwargs) 60 layer.add_loss(losses, inputs) 61 return outputs

~\anaconda3\envs\tf\lib\site-packages\tensorflow_core\python\eager\def_function.py in call(self, *args, **kwds) 566 xla_context.Exit() 567 else: --> 568 result = self._call(*args, **kwds) 569 570 if tracing_count == self._get_tracing_count():

~\anaconda3\envs\tf\lib\site-packages\tensorflow_core\python\eager\def_function.py in _call(self, *args, **kwds) 604 # In this case we have not created variables on the first call. So we can 605 # run the first trace but we should fail if variables are created. --> 606 results = self._stateful_fn(*args, **kwds) 607 if self._created_variables: 608 raise ValueError("Creating variables on a non-first call to a function"

~\anaconda3\envs\tf\lib\site-packages\tensorflow_core\python\eager\function.py in call(self, *args, **kwargs) 2360 """Calls a graph function specialized to the inputs.""" 2361 with self._lock: -> 2362 graph_function, args, kwargs = self._maybe_define_function(args, kwargs) 2363 return graph_function._filtered_call(args, kwargs) # pylint: disable=protected-access 2364

~\anaconda3\envs\tf\lib\site-packages\tensorflow_core\python\eager\function.py in _maybe_define_function(self, args, kwargs) 2701 2702
self._function_cache.missed.add(call_context_key) -> 2703 graph_function = self._create_graph_function(args, kwargs) 2704 self._function_cache.primary[cache_key] = graph_function 2705 return graph_function, args, kwargs

~\anaconda3\envs\tf\lib\site-packages\tensorflow_core\python\eager\function.py in _create_graph_function(self, args, kwargs, override_flat_arg_shapes) 2591 arg_names=arg_names,
2592 override_flat_arg_shapes=override_flat_arg_shapes, -> 2593 capture_by_value=self._capture_by_value), 2594 self._function_attributes, 2595 # Tell the ConcreteFunction to clean up its graph once it goes out of

~\anaconda3\envs\tf\lib\site-packages\tensorflow_core\python\framework\func_graph.py in func_graph_from_py_func(name, python_func, args, kwargs, signature, func_graph, autograph, autograph_options, add_control_dependencies, arg_names, op_return_value, collections, capture_by_value, override_flat_arg_shapes) 976 converted_func) 977 --> 978 func_outputs = python_func(*func_args, **func_kwargs) 979 980 # invariant: func_outputs contains only Tensors, CompositeTensors,

~\anaconda3\envs\tf\lib\site-packages\tensorflow_core\python\eager\def_function.py in wrapped_fn(*args, **kwds) 437 # wrapped allows AutoGraph to swap in a converted function. We give 438 # the function a weak reference to itself to avoid a reference cycle. --> 439 return weak_wrapped_fn().wrapped(*args, **kwds) 440 weak_wrapped_fn = weakref.ref(wrapped_fn) 441

~\anaconda3\envs\tf\lib\site-packages\tensorflow_core\python\saved_model\function_deserialization.py in restored_function_body(*args, **kwargs) 260 .format(_pretty_format_positional(args), kwargs, 261 len(saved_function.concrete_functions), --> 262 "\n\n".join(signature_descriptions))) 263 264 concrete_function_objects = []

ValueError: Could not find matching function to call loaded from the

SavedModel. Got: Positional arguments (1 total): * Tensor("inputs:0", shape=(None, 256, 256, 3), dtype=uint8) Keyword arguments: {}

Expected these arguments to match one of the following 1 option(s):

Option 1: Positional arguments (1 total): * TensorSpec(shape=(None, 256, 256, 3), dtype=tf.float32, name='inputs') Keyword arguments: {}

Upvotes: 1

Views: 12349

Answers (1)

Vishnuvardhan Janapati
Vishnuvardhan Janapati

Reputation: 3278

I think the loaded model expecting a input signature (shape and dtype) different from the provided input signature. Specifically, loaded model is expecting tensorflow dtype (tf.float32) but you provided float32. Can you try to replace

x = x.astype('float32') # dtype of x is numpy float32 which is not what the loaded model expecting here

by

x = tf.cast(x,tf.float32) # this makes x to be of correct signature

Please check below what happened in each line

x=prepare('img.jpg')     # x is numpy array
# whenever you run a tensorflow operation on a numpy array, it becomes a tensor and vice versa
x = tf.keras.utils.normalize(x, axis=1)  # x becomes a tensor
x = x.astype('float32')  # dtype of x changed back to numpy float32
print(x.dtype)           # prints correctly float32 (notice that its not tf.float32)
prediction = model.predict([x]) # this throws an error as the underlying concrete function expects input of tf.float32 signature

I don't see any other issue. I suggest you to read about concrete function and input signature.

Upvotes: 0

Related Questions