2021年1月17日星期日

DeepLearning: Got error when try to import one test data into model

I am new on deep learning. To practicing I trained a simple Handwriting model with tensor-flow and mnist. After loading mnist I made model and trained that:

(x_train, y_train), (x_test, y_test) = keras.datasets.mnist.load_data()  x_train = x_train.astype('float32')/255  x_test =  x_test.astype('float32')/255  model = keras.Sequential([      keras.layers.Flatten(input_shape=(28,28)),      keras.layers.Dense(100,activation = 'relu'),      keras.layers.Dense(100,activation = 'sigmoid'),      keras.layers.Dense(10,activation = 'sigmoid'),  ])  

As you can see, I flatted my first layer into 784 px One-dimensional array.

I reshape my test data too:

x_test_flattened = x_test.reshape(len(x_test),28*28)  

Now, In predict I want to import just one data into model to test it:

y_predicted = model.predict(x_test_flattened[0])  

but I got these errors:

WARNING:tensorflow:Model was constructed with shape (None, 28, 28) for input Tensor("flatten_input:0", shape=(None, 28, 28), dtype=float32), but it was called on an input with incompatible shape (None, 1).  ---------------------------------------------------------------------------  ValueError                                Traceback (most recent call last)  <ipython-input-13-1bdc43d66a07> in <module>  ----> 1 y_predicted = model.predict(x_test_flattened[0])        2 # y_predicted[1]    ~/anaconda3/lib/python3.8/site-packages/tensorflow/python/keras/engine/training.py in _method_wrapper(self, *args, **kwargs)       86       raise ValueError('{} is not supported in multi-worker mode.'.format(       87           method.__name__))  ---> 88     return method(self, *args, **kwargs)       89        90   return tf_decorator.make_decorator(    ~/anaconda3/lib/python3.8/site-packages/tensorflow/python/keras/engine/training.py in predict(self, x, batch_size, verbose, steps, callbacks, max_queue_size, workers, use_multiprocessing)     1266           for step in data_handler.steps():     1267             callbacks.on_predict_batch_begin(step)  -> 1268             tmp_batch_outputs = predict_function(iterator)     1269             # Catch OutOfRangeError for Datasets of unknown size.     1270             # This blocks until the batch has finished executing.    ~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/def_function.py in __call__(self, *args, **kwds)      578         xla_context.Exit()      579     else:  --> 580       result = self._call(*args, **kwds)      581       582     if tracing_count == self._get_tracing_count():    ~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/def_function.py in _call(self, *args, **kwds)      625       # This is the first call of __call__, so we have to initialize.      626       initializers = []  --> 627       self._initialize(args, kwds, add_initializers_to=initializers)      628     finally:      629       # At this point we know that the initialization is complete (or less    ~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/def_function.py in _initialize(self, args, kwds, add_initializers_to)      503     self._graph_deleter = FunctionDeleter(self._lifted_initializer_graph)      504     self._concrete_stateful_fn = (  --> 505         self._stateful_fn._get_concrete_function_internal_garbage_collected(  # pylint: disable=protected-access      506             *args, **kwds))      507     ~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/function.py in _get_concrete_function_internal_garbage_collected(self, *args, **kwargs)     2444       args, kwargs = None, None     2445     with self._lock:  -> 2446       graph_function, _, _ = self._maybe_define_function(args, kwargs)     2447     return graph_function     2448     ~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/function.py in _maybe_define_function(self, args, kwargs)     2775      2776       self._function_cache.missed.add(call_context_key)  -> 2777       graph_function = self._create_graph_function(args, kwargs)     2778       self._function_cache.primary[cache_key] = graph_function     2779       return graph_function, args, kwargs    ~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/function.py in _create_graph_function(self, args, kwargs, override_flat_arg_shapes)     2655     arg_names = base_arg_names + missing_arg_names     2656     graph_function = ConcreteFunction(  -> 2657         func_graph_module.func_graph_from_py_func(     2658             self._name,     2659             self._python_function,    ~/anaconda3/lib/python3.8/site-packages/tensorflow/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)      979         _, original_func = tf_decorator.unwrap(python_func)      980   --> 981       func_outputs = python_func(*func_args, **func_kwargs)      982       983       # invariant: `func_outputs` contains only Tensors, CompositeTensors,    ~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/def_function.py in wrapped_fn(*args, **kwds)      439         # __wrapped__ allows AutoGraph to swap in a converted function. We give      440         # the function a weak reference to itself to avoid a reference cycle.  --> 441         return weak_wrapped_fn().__wrapped__(*args, **kwds)      442     weak_wrapped_fn = weakref.ref(wrapped_fn)      443     ~/anaconda3/lib/python3.8/site-packages/tensorflow/python/framework/func_graph.py in wrapper(*args, **kwargs)      966           except Exception as e:  # pylint:disable=broad-except      967             if hasattr(e, "ag_error_metadata"):  --> 968               raise e.ag_error_metadata.to_exception(e)      969             else:      970               raise    ValueError: in user code:        /home/Alt/anaconda3/lib/python3.8/site-packages/tensorflow/python/keras/engine/training.py:1147 predict_function  *          outputs = self.distribute_strategy.run(      /home/Alt/anaconda3/lib/python3.8/site-packages/tensorflow/python/distribute/distribute_lib.py:951 run  **          return self._extended.call_for_each_replica(fn, args=args, kwargs=kwargs)      /home/Alt/anaconda3/lib/python3.8/site-packages/tensorflow/python/distribute/distribute_lib.py:2290 call_for_each_replica          return self._call_for_each_replica(fn, args, kwargs)      /home/Alt/anaconda3/lib/python3.8/site-packages/tensorflow/python/distribute/distribute_lib.py:2649 _call_for_each_replica          return fn(*args, **kwargs)      /home/Alt/anaconda3/lib/python3.8/site-packages/tensorflow/python/keras/engine/training.py:1122 predict_step  **          return self(x, training=False)      /home/Alt/anaconda3/lib/python3.8/site-packages/tensorflow/python/keras/engine/base_layer.py:927 __call__          outputs = call_fn(cast_inputs, *args, **kwargs)      /home/Alt/anaconda3/lib/python3.8/site-packages/tensorflow/python/keras/engine/sequential.py:277 call          return super(Sequential, self).call(inputs, training=training, mask=mask)      /home/Alt/anaconda3/lib/python3.8/site-packages/tensorflow/python/keras/engine/network.py:717 call          return self._run_internal_graph(      /home/Alt/anaconda3/lib/python3.8/site-packages/tensorflow/python/keras/engine/network.py:888 _run_internal_graph          output_tensors = layer(computed_tensors, **kwargs)      /home/Alt/anaconda3/lib/python3.8/site-packages/tensorflow/python/keras/engine/base_layer.py:885 __call__          input_spec.assert_input_compatibility(self.input_spec, inputs,      /home/Alt/anaconda3/lib/python3.8/site-packages/tensorflow/python/keras/engine/input_spec.py:212 assert_input_compatibility          raise ValueError(        ValueError: Input 0 of layer dense is incompatible with the layer: expected axis -1 of input shape to have value 784 but received input with shape [None, 1]  

But when I import all flatted x_test data everything is good

y_predicted = model.predict(x_test_flattened)  y_predicted[1]  array([6.1507606e-08, 1.2000690e-05, 5.1280117e-01, 1.5896080e-06,         2.6905557e-08, 2.2364643e-06, 1.0007229e-06, 6.0152153e-08,         2.0705515e-05, 2.9885057e-09], dtype=float32)  

How Can I test just one data?

https://stackoverflow.com/questions/65768689/deeplearning-got-error-when-try-to-import-one-test-data-into-model January 18, 2021 at 12:05PM

没有评论:

发表评论