Python 为什么可以';我不能在这张图片上运行tensorflow CNN模型吗?
我从头创建了一个TensorFlow CNN来识别某些类型的动物。我相信该模型是有效的,因为我正在获取有关培训数据的数据,并且在运行代码时在我的目录中看到一个新文件夹。当我试图运行代码来预测一个新的单一图像时,我得到了这个错误。我是TensorFlow的新手,所以我不确定自己做错了什么。该映像位于主目录中,是一个.jpg映像。如果你需要更多信息,请告诉我。谢谢Python 为什么可以';我不能在这张图片上运行tensorflow CNN模型吗?,python,html,tensorflow,keras,Python,Html,Tensorflow,Keras,我从头创建了一个TensorFlow CNN来识别某些类型的动物。我相信该模型是有效的,因为我正在获取有关培训数据的数据,并且在运行代码时在我的目录中看到一个新文件夹。当我试图运行代码来预测一个新的单一图像时,我得到了这个错误。我是TensorFlow的新手,所以我不确定自己做错了什么。该映像位于主目录中,是一个.jpg映像。如果你需要更多信息,请告诉我。谢谢 CATEGORIES = ["cane", "cavallo", "elefante&
CATEGORIES = ["cane", "cavallo", "elefante", "farfalla", "gallina",
"gatto", "mucca", "pecora", "ragno", "scoiattolo"]
def prepare(file):
IMG_SIZE = 50
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)
model = tf.keras.models.load_model("CNN.model")
from PIL import Image
import numpy as np
from skimage import transform
image = load('test.jpg')
model.predict(image)
prediction = model.predict([image])
prediction = list(prediction[0])
print(CATEGORIES[prediction.index(max(prediction))])
这就是错误所在
ValueError Traceback (most recent call
last)
<ipython-input-4-5c3fc0a5d50b> in <module>
14 from skimage import transform
15 image = load('test.jpg')
---> 16 model.predict(image)
17 prediction = model.predict([image])
18 prediction = list(prediction[0])
~/opt/anaconda3/lib/python3.7/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(
~/opt/anaconda3/lib/python3.7/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.
~/opt/anaconda3/lib/python3.7/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():
~/opt/anaconda3/lib/python3.7/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
~/opt/anaconda3/lib/python3.7/site-packages/tensorflow/python/eager/def_function.py in _initialize(self, args, kwds, add_initializers_to)
504 self._concrete_stateful_fn = (
505 self._stateful_fn._get_concrete_function_internal_garbage_collected( # pylint: disable=protected-access
--> 506 *args, **kwds))
507
508 def invalid_creator_scope(*unused_args, **unused_kwds):
~/opt/anaconda3/lib/python3.7/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
~/opt/anaconda3/lib/python3.7/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
~/opt/anaconda3/lib/python3.7/site-packages/tensorflow/python/eager/function.py in _create_graph_function(self, args, kwargs, override_flat_arg_shapes)
2665 arg_names=arg_names,
2666 override_flat_arg_shapes=override_flat_arg_shapes,
-> 2667 capture_by_value=self._capture_by_value),
2668 self._function_attributes,
2669 # Tell the ConcreteFunction to clean up its graph once it goes out of
~/opt/anaconda3/lib/python3.7/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,
~/opt/anaconda3/lib/python3.7/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
~/opt/anaconda3/lib/python3.7/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:
/Users/rin/opt/anaconda3/lib/python3.7/site-packages/tensorflow/python/keras/engine/training.py:1147 predict_function *
outputs = self.distribute_strategy.run(
/Users/ron/opt/anaconda3/lib/python3.7/site-packages/tensorflow/python/distribute/distribute_lib.py:951 run **
return self._extended.call_for_each_replica(fn, args=args, kwargs=kwargs)
/Users/rn/opt/anaconda3/lib/python3.7/site-packages/tensorflow/python/distribute/distribute_lib.py:2290 call_for_each_replica
return self._call_for_each_replica(fn, args, kwargs)
/Users/romin/opt/anaconda3/lib/python3.7/site-packages/tensorflow/python/distribute/distribute_lib.py:2649 _call_for_each_replica
return fn(*args, **kwargs)
/Users/rin/opt/anaconda3/lib/python3.7/site-packages/tensorflow/python/keras/engine/training.py:1122 predict_step **
return self(x, training=False)
/Users/rn/opt/anaconda3/lib/python3.7/site-packages/tensorflow/python/keras/engine/base_layer.py:886 __call__
self.name)
/Users/rkin/opt/anaconda3/lib/python3.7/site-packages/tensorflow/python/keras/engine/input_spec.py:216 assert_input_compatibility
' but received input with shape ' + str(shape))
ValueError: Input 0 of layer sequential_10 is incompatible with the layer: expected axis -1 of input shape to have value 1 but received input with shape [None, 256, 256, 3]
因此,错误很明显
expected axis -1 of input shape to have value 1 but received input with shape [None, 256, 256, 3]
错误表明,由于RGB图像的原因,提供给模型的输入通道为3
,但您的模型需要通道为1
的图像
这意味着您的模型需要一个灰度
图像,并且您在预测时提供了一个RGB
图像
您应该提供一个具有[None,256,256,1]
的图像,其中None
表示batch\u size
您能通过添加型号代码来确认这一点吗
更新:
你刚刚更新了你的问题,所以在这里我可以看到你正在用灰度图像训练你的模型
X = np.array(X).reshape(-1, IMG_SIZE, IMG_SIZE, 1)
但是我想,当
预测时
您正在使用RGB图像呼叫。我想您只是忘记应用def prepare(文件)
你能试试吗
model.predict(prepare(image))
这就是为什么RGB和扩展灰度不匹配的原因。因为加载它的方式是RGB,因为没有应用prepare函数。申请后,它应该是灰度图像,应该可以工作。请提供完整的代码,然后我想错误消息“ValueError:in user code:”在您的帖子中被截断了,在“:”之后出现了一些内容?抱歉,它被切断了。我刚刚更新了它。我想,与模型的设置相比,在加载图像时,您的图像预处理中缺少了一些东西。为了追踪它,最好有完整的代码。好的,我会添加它。给我两个minutes@StatTistician它是更新的否,这是不正确的,因为这是在def prepare(文件)中完成的。谢谢,我现在明白了。这是实际的问题,您对函数调用是正确的,但这并不意味着我的答案是错误的。好吧,但这是误导/不是问题。无意冒犯,很高兴你在这里!结果如何?
model.predict(prepare(image))