Как загрузить новый файл в модель распознавания изображений - PullRequest
0 голосов
/ 08 ноября 2019

Я пытаюсь создать свою первую модель распознавания изображений, следуя инструкциям на сайте: Tutorial Towardsdatascience.com

После создания модели вы сможете загрузить своисобственное изображение и пусть модель сделает прогноз. Но в этот момент я застреваю. Я продолжаю получать ошибки и не могу понять, что я делаю неправильно.

Это код последней части:

def prepare(file):
    IMG_SIZE = 224
    img_array = cv2.imread(file, cv2.IMREAD_GRAYSCALE)
    new_array = cv2.resize(img_array, (IMG_SIZE, IMG_SIZE))
    return new_array.reshape(-1, IMG_SIZE, IMG_SIZE, 1)

image = prepare('users/docs/proj/test/test.jpg')

model = tf.keras.models.load_model("CNN.model")
prediction = model.predict([image])
prediction = list(prediction[0])
print(CATEGORIES[prediction.index(max(prediction))])

Ошибка , которую я получаю:

ValueError: входы Python несовместимы с input_signature: input: (Tensor ("IteratorGetNext: 0", shape = (None, 224,224,3), dtype = uint8)) input_signature: (TensorSpec (shape =)Нет, Нет, Нет, 3), dtype = tf.float32, name = Нет))

Я протестировал его с разными jpg-файлами, но сохранил ту же ошибку.

Full-log:

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-25-ac0118ff787e> in <module>
     12 model = tf.keras.models.load_model('CNN.model')
     13 
---> 14 prediction = model.predict([image])
     15 prediction = list(prediction[0])
     16 print(categories[prediction.index(max(prediction))])

/anaconda3/envs/Tensor_env/lib/python3.7/site-packages/tensorflow_core/python/keras/engine/training.py in predict(self, x, batch_size, verbose, steps, callbacks, max_queue_size, workers, use_multiprocessing)
    907         max_queue_size=max_queue_size,
    908         workers=workers,
--> 909         use_multiprocessing=use_multiprocessing)
    910 
    911   def reset_metrics(self):

/anaconda3/envs/Tensor_env/lib/python3.7/site-packages/tensorflow_core/python/keras/engine/training_v2.py in predict(self, model, x, batch_size, verbose, steps, callbacks, **kwargs)
    460     return self._model_iteration(
    461         model, ModeKeys.PREDICT, x=x, batch_size=batch_size, verbose=verbose,
--> 462         steps=steps, callbacks=callbacks, **kwargs)
    463 
    464 

/anaconda3/envs/Tensor_env/lib/python3.7/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, **kwargs)
    442               mode=mode,
    443               training_context=training_context,
--> 444               total_epochs=1)
    445           cbks.make_logs(model, epoch_logs, result, mode)
    446 

/anaconda3/envs/Tensor_env/lib/python3.7/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)
    121         step=step, mode=mode, size=current_batch_size) as batch_logs:
    122       try:
--> 123         batch_outs = execution_function(iterator)
    124       except (StopIteration, errors.OutOfRangeError):
    125         # TODO(kaftan): File bug about tf function and errors.OutOfRangeError?

/anaconda3/envs/Tensor_env/lib/python3.7/site-packages/tensorflow_core/python/keras/engine/training_v2_utils.py in execution_function(input_fn)
     84     # `numpy` translates Tensors to values in Eager mode.
     85     return nest.map_structure(_non_none_constant_value,
---> 86                               distributed_function(input_fn))
     87 
     88   return execution_function

/anaconda3/envs/Tensor_env/lib/python3.7/site-packages/tensorflow_core/python/eager/def_function.py in __call__(self, *args, **kwds)
    455 
    456     tracing_count = self._get_tracing_count()
--> 457     result = self._call(*args, **kwds)
    458     if tracing_count == self._get_tracing_count():
    459       self._call_counter.called_without_tracing()

/anaconda3/envs/Tensor_env/lib/python3.7/site-packages/tensorflow_core/python/eager/def_function.py in _call(self, *args, **kwds)
    501       # This is the first call of __call__, so we have to initialize.
    502       initializer_map = object_identity.ObjectIdentityDictionary()
--> 503       self._initialize(args, kwds, add_initializers_to=initializer_map)
    504     finally:
    505       # At this point we know that the initialization is complete (or less

/anaconda3/envs/Tensor_env/lib/python3.7/site-packages/tensorflow_core/python/eager/def_function.py in _initialize(self, args, kwds, add_initializers_to)
    406     self._concrete_stateful_fn = (
    407         self._stateful_fn._get_concrete_function_internal_garbage_collected(  # pylint: disable=protected-access
--> 408             *args, **kwds))
    409 
    410     def invalid_creator_scope(*unused_args, **unused_kwds):

/anaconda3/envs/Tensor_env/lib/python3.7/site-packages/tensorflow_core/python/eager/function.py in _get_concrete_function_internal_garbage_collected(self, *args, **kwargs)
   1846     if self.input_signature:
   1847       args, kwargs = None, None
-> 1848     graph_function, _, _ = self._maybe_define_function(args, kwargs)
   1849     return graph_function
   1850 

/anaconda3/envs/Tensor_env/lib/python3.7/site-packages/tensorflow_core/python/eager/function.py in _maybe_define_function(self, args, kwargs)
   2148         graph_function = self._function_cache.primary.get(cache_key, None)
   2149         if graph_function is None:
-> 2150           graph_function = self._create_graph_function(args, kwargs)
   2151           self._function_cache.primary[cache_key] = graph_function
   2152         return graph_function, args, kwargs

/anaconda3/envs/Tensor_env/lib/python3.7/site-packages/tensorflow_core/python/eager/function.py in _create_graph_function(self, args, kwargs, override_flat_arg_shapes)
   2039             arg_names=arg_names,
   2040             override_flat_arg_shapes=override_flat_arg_shapes,
-> 2041             capture_by_value=self._capture_by_value),
   2042         self._function_attributes,
   2043         # Tell the ConcreteFunction to clean up its graph once it goes out of

/anaconda3/envs/Tensor_env/lib/python3.7/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)
    913                                           converted_func)
    914 
--> 915       func_outputs = python_func(*func_args, **func_kwargs)
    916 
    917       # invariant: `func_outputs` contains only Tensors, CompositeTensors,

/anaconda3/envs/Tensor_env/lib/python3.7/site-packages/tensorflow_core/python/eager/def_function.py in wrapped_fn(*args, **kwds)
    356         # __wrapped__ allows AutoGraph to swap in a converted function. We give
    357         # the function a weak reference to itself to avoid a reference cycle.
--> 358         return weak_wrapped_fn().__wrapped__(*args, **kwds)
    359     weak_wrapped_fn = weakref.ref(wrapped_fn)
    360 

/anaconda3/envs/Tensor_env/lib/python3.7/site-packages/tensorflow_core/python/keras/engine/training_v2_utils.py in distributed_function(input_iterator)
     71     strategy = distribution_strategy_context.get_strategy()
     72     outputs = strategy.experimental_run_v2(
---> 73         per_replica_function, args=(model, x, y, sample_weights))
     74     # Out of PerReplica outputs reduce or pick values to return.
     75     all_outputs = dist_utils.unwrap_output_dict(

/anaconda3/envs/Tensor_env/lib/python3.7/site-packages/tensorflow_core/python/distribute/distribute_lib.py in experimental_run_v2(self, fn, args, kwargs)
    758       fn = autograph.tf_convert(fn, ag_ctx.control_status_ctx(),
    759                                 convert_by_default=False)
--> 760       return self._extended.call_for_each_replica(fn, args=args, kwargs=kwargs)
    761 
    762   def reduce(self, reduce_op, value, axis):

/anaconda3/envs/Tensor_env/lib/python3.7/site-packages/tensorflow_core/python/distribute/distribute_lib.py in call_for_each_replica(self, fn, args, kwargs)
   1785       kwargs = {}
   1786     with self._container_strategy().scope():
-> 1787       return self._call_for_each_replica(fn, args, kwargs)
   1788 
   1789   def _call_for_each_replica(self, fn, args, kwargs):

/anaconda3/envs/Tensor_env/lib/python3.7/site-packages/tensorflow_core/python/distribute/distribute_lib.py in _call_for_each_replica(self, fn, args, kwargs)
   2130         self._container_strategy(),
   2131         replica_id_in_sync_group=constant_op.constant(0, dtypes.int32)):
-> 2132       return fn(*args, **kwargs)
   2133 
   2134   def _reduce_to(self, reduce_op, value, destinations):

/anaconda3/envs/Tensor_env/lib/python3.7/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/Tensor_env/lib/python3.7/site-packages/tensorflow_core/python/keras/engine/training_v2_utils.py in _predict_on_batch(***failed resolving arguments***)
    160     def _predict_on_batch(model, x, y=None, sample_weights=None):
    161       del y, sample_weights
--> 162       return predict_on_batch(model, x)
    163 
    164     func = _predict_on_batch

/anaconda3/envs/Tensor_env/lib/python3.7/site-packages/tensorflow_core/python/keras/engine/training_v2_utils.py in predict_on_batch(model, x)
    368 
    369   with backend.eager_learning_phase_scope(0):
--> 370     return model(inputs)  # pylint: disable=not-callable

/anaconda3/envs/Tensor_env/lib/python3.7/site-packages/tensorflow_core/python/keras/engine/base_layer.py in __call__(self, inputs, *args, **kwargs)
    845                     outputs = base_layer_utils.mark_as_return(outputs, acd)
    846                 else:
--> 847                   outputs = call_fn(cast_inputs, *args, **kwargs)
    848 
    849             except errors.OperatorNotAllowedInGraphError as e:

/anaconda3/envs/Tensor_env/lib/python3.7/site-packages/tensorflow_core/python/keras/engine/sequential.py in call(self, inputs, training, mask)
    254       if not self.built:
    255         self._init_graph_network(self.inputs, self.outputs, name=self.name)
--> 256       return super(Sequential, self).call(inputs, training=training, mask=mask)
    257 
    258     outputs = inputs  # handle the corner case where self.layers is empty

/anaconda3/envs/Tensor_env/lib/python3.7/site-packages/tensorflow_core/python/keras/engine/network.py in call(self, inputs, training, mask)
    706     return self._run_internal_graph(
    707         inputs, training=training, mask=mask,
--> 708         convert_kwargs_to_constants=base_layer_utils.call_context().saving)
    709 
    710   def compute_output_shape(self, input_shape):

/anaconda3/envs/Tensor_env/lib/python3.7/site-packages/tensorflow_core/python/keras/engine/network.py in _run_internal_graph(self, inputs, training, mask, convert_kwargs_to_constants)
    858 
    859           # Compute outputs.
--> 860           output_tensors = layer(computed_tensors, **kwargs)
    861 
    862           # Update tensor_dict.

/anaconda3/envs/Tensor_env/lib/python3.7/site-packages/tensorflow_core/python/keras/engine/base_layer.py in __call__(self, inputs, *args, **kwargs)
    845                     outputs = base_layer_utils.mark_as_return(outputs, acd)
    846                 else:
--> 847                   outputs = call_fn(cast_inputs, *args, **kwargs)
    848 
    849             except errors.OperatorNotAllowedInGraphError as e:

/anaconda3/envs/Tensor_env/lib/python3.7/site-packages/tensorflow_core/python/keras/saving/saved_model/utils.py in return_outputs_and_add_losses(*args, **kwargs)
     55     inputs = args[inputs_arg_index]
     56     args = args[inputs_arg_index + 1:]
---> 57     outputs, losses = fn(inputs, *args, **kwargs)
     58     layer.add_loss(losses, inputs)
     59     return outputs

/anaconda3/envs/Tensor_env/lib/python3.7/site-packages/tensorflow_core/python/eager/def_function.py in __call__(self, *args, **kwds)
    455 
    456     tracing_count = self._get_tracing_count()
--> 457     result = self._call(*args, **kwds)
    458     if tracing_count == self._get_tracing_count():
    459       self._call_counter.called_without_tracing()

/anaconda3/envs/Tensor_env/lib/python3.7/site-packages/tensorflow_core/python/eager/def_function.py in _call(self, *args, **kwds)
    492       # In this case we have not created variables on the first call. So we can
    493       # run the first trace but we should fail if variables are created.
--> 494       results = self._stateful_fn(*args, **kwds)
    495       if self._created_variables:
    496         raise ValueError("Creating variables on a non-first call to a function"

/anaconda3/envs/Tensor_env/lib/python3.7/site-packages/tensorflow_core/python/eager/function.py in __call__(self, *args, **kwargs)
   1820   def __call__(self, *args, **kwargs):
   1821     """Calls a graph function specialized to the inputs."""
-> 1822     graph_function, args, kwargs = self._maybe_define_function(args, kwargs)
   1823     return graph_function._filtered_call(args, kwargs)  # pylint: disable=protected-access
   1824 

/anaconda3/envs/Tensor_env/lib/python3.7/site-packages/tensorflow_core/python/eager/function.py in _maybe_define_function(self, args, kwargs)
   2105     if self.input_signature is None or args is not None or kwargs is not None:
   2106       args, kwargs = self._function_spec.canonicalize_function_inputs(
-> 2107           *args, **kwargs)
   2108 
   2109     cache_key = self._cache_key(args, kwargs)

/anaconda3/envs/Tensor_env/lib/python3.7/site-packages/tensorflow_core/python/eager/function.py in canonicalize_function_inputs(self, *args, **kwargs)
   1648           inputs,
   1649           self._input_signature,
-> 1650           self._flat_input_signature)
   1651       return inputs, {}
   1652 

/anaconda3/envs/Tensor_env/lib/python3.7/site-packages/tensorflow_core/python/eager/function.py in _convert_inputs_to_signature(inputs, input_signature, flat_input_signature)
   1714       flatten_inputs)):
   1715     raise ValueError("Python inputs incompatible with input_signature:\n%s" %
-> 1716                      format_error_message(inputs, input_signature))
   1717 
   1718   if need_packing:

ValueError: Python inputs incompatible with input_signature:
  inputs: (
    Tensor("IteratorGetNext:0", shape=(None, 224, 224, 3), dtype=uint8))
  input_signature: (
    TensorSpec(shape=(None, None, None, 3), dtype=tf.float32, name=None))

  [1]: https://towardsdatascience.com/all-the-steps-to-build-your-first-image-classifier-with-code-cf244b015799

1 Ответ

0 голосов
/ 09 ноября 2019

Я нашел проблему. Изображения X были разделены на 255, а изображения не было. После того, как я разделил изображение / 255, проблема была решена.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...