简体   繁体   English

将图像传递给由 TensorFlow 和 Keras 制成的 CNN model 时出错

[英]Error while passing images to a CNN model made from TensorFlow and Keras

I was making a CNN classifier to identify cat and dog images on my colab notebook, but it is giving me the Graph execution error.我正在制作一个 CNN 分类器来识别我的 colab 笔记本上的猫和狗图像,但它给了我图形执行错误。 Initially, I trained the model with various pictures of them with 500 images each which worked without any problems, but my model was not giving me decent accuracy.最初,我用各种图片训练 model,每张图片有 500 张图片,每张图片都没有任何问题,但我的 model 并没有给我不错的准确性。 So, I increased the pictures to 1500 each which gave me this error.所以,我将图片增加到 1500 张,这给了我这个错误。


Epoch 1/10
---------------------------------------------------------------------------
UnknownError                              Traceback (most recent call last)
<ipython-input-32-086f2dc31200> in <module>
----> 1 model.fit(x = train_batches, validation_data = valid_batches, epochs = 10, verbose = 2)

1 frames
/usr/local/lib/python3.7/dist-packages/tensorflow/python/eager/execute.py in quick_execute(op_name, num_outputs, inputs, attrs, ctx, name)
 53     ctx.ensure_initialized()
 54     tensors = pywrap_tfe.TFE_Py_Execute(ctx._handle, device_name, op_name,
---> 55                                         inputs, attrs, num_outputs)
 56   except core._NotOkStatusException as e:
 57     if name is not None:

UnknownError: Graph execution error:

2 root error(s) found.
  (0) UNKNOWN:  UnidentifiedImageError: cannot identify image file <_io.BytesIO object at 0x7f7814555ef0>
Traceback (most recent call last):

  File "/usr/local/lib/python3.7/dist-packages/tensorflow/python/ops/script_ops.py", line 271, in __call__
ret = func(*args)

  File "/usr/local/lib/python3.7/dist-packages/tensorflow/python/autograph/impl/api.py", line 642, in wrapper
return func(*args, **kwargs)

  File "/usr/local/lib/python3.7/dist-packages/tensorflow/python/data/ops/dataset_ops.py", line 1004, in generator_py_func
values = next(generator_state.get_iterator(iterator_id))

  File "/usr/local/lib/python3.7/dist-packages/keras/engine/data_adapter.py", line 830, in wrapped_generator
    for data in generator_fn():

  File "/usr/local/lib/python3.7/dist-packages/keras/engine/data_adapter.py", line 956, in generator_fn
    yield x[I]

  File "/usr/local/lib/python3.7/dist-packages/keras_preprocessing/image/iterator.py", line 65, in __getitem__
    return self._get_batches_of_transformed_samples(index_array)

  File "/usr/local/lib/python3.7/dist-packages/keras_preprocessing/image/iterator.py", line 230, in _get_batches_of_transformed_samples
interpolation=self.interpolation)

  File "/usr/local/lib/python3.7/dist-packages/keras_preprocessing/image/utils.py", line 114, in load_img
    img = pil_image.open(io.BytesIO(f.read()))

  File "/usr/local/lib/python3.7/dist-packages/PIL/Image.py", line 2896, in open
"cannot identify image file %r" % (filename if filename else fp)

PIL.UnidentifiedImageError: cannot identify image file <_io.BytesIO object at 0x7f7814555ef0>


 [[{{node PyFunc}}]]
 [[IteratorGetNext]]
 [[IteratorGetNext/_2]]
  (1) UNKNOWN:  UnidentifiedImageError: cannot identify image file <_io.BytesIO object at 0x7f7814555ef0>
Traceback (most recent call last):

  File "/usr/local/lib/python3.7/dist-packages/tensorflow/python/ops/script_ops.py", line 271, in __call__
ret = func(*args)

  File "/usr/local/lib/python3.7/dist-packages/tensorflow/python/autograph/impl/api.py", line 642, in wrapper
return func(*args, **kwargs)

  File "/usr/local/lib/python3.7/dist-packages/tensorflow/python/data/ops/dataset_ops.py", line 1004, in generator_py_func
values = next(generator_state.get_iterator(iterator_id))

  File "/usr/local/lib/python3.7/dist-packages/keras/engine/data_adapter.py", line 830, in wrapped_generator
for data in generator_fn():

  File "/usr/local/lib/python3.7/dist-packages/keras/engine/data_adapter.py", line 956, in generator_fn
yield x[I]

  File "/usr/local/lib/python3.7/dist-packages/keras_preprocessing/image/iterator.py", line 65, in __getitem__
return self._get_batches_of_transformed_samples(index_array)

  File "/usr/local/lib/python3.7/dist-packages/keras_preprocessing/image/iterator.py", line 230, in _get_batches_of_transformed_samples
interpolation=self.interpolation)

  File "/usr/local/lib/python3.7/dist-packages/keras_preprocessing/image/utils.py", line 114, in load_img
img = pil_image.open(io.BytesIO(f.read()))

  File "/usr/local/lib/python3.7/dist-packages/PIL/Image.py", line 2896, in open
"cannot identify image file %r" % (filename if filename else fp)

PIL.UnidentifiedImageError: cannot identify image file <_io.BytesIO object at 0x7f7814555ef0>


 [[{{node PyFunc}}]]
 [[IteratorGetNext]]
0 successful operations.
0 derived errors ignored. [Op:__inference_train_function_2503]

This is my model这是我的 model

model = Sequential([
Conv2D(filters = 32, kernel_size = (3, 3), activation = "relu", padding = "same", input_shape = (224, 224, 3)),
MaxPool2D(pool_size = (2, 2), strides = 3),
Conv2D(filters = 64, kernel_size = (3, 3), activation = "relu", padding = "same"),
MaxPool2D(pool_size = (2, 2), strides = 3),
Flatten(),
Dense(units = 2, activation = "softmax")

]) ])

My Model Summary我的 Model 总结

Model: "sequential_1"
_________________________________________________________________
 Layer (type)                Output Shape              Param #   
=================================================================
 conv2d_2 (Conv2D)           (None, 224, 224, 32)      896       
                                                             
 max_pooling2d_2 (MaxPooling 2D)  (None, 75, 75, 32)       0         
                                                          
                                                             
 conv2d_3 (Conv2D)           (None, 75, 75, 64)        18496     
                                                             
 max_pooling2d_3 (MaxPooling 2D)  (None, 25, 25, 64)       0                                                                      
                                                             
 flatten_1 (Flatten)         (None, 40000)             0         
                                                             
 dense_1 (Dense)             (None, 2)                 80002     
                                                             
=================================================================
Total params: 99,394
Trainable params: 99,394
Non-trainable params: 0
_________________________________________________________________

My Compile and Training code我的编译和训练代码

model.compile(optimizer = Adam(learning_rate = 0.0001), loss = 
"categorical_crossentropy", metrics = ["accuracy"])

model.fit(x = train_batches, validation_data = valid_batches, epochs = 10, verbose = 2)

Any solutions?有什么解决办法吗?

You may have a corrupt image in your dataset.您的数据集中可能有损坏的图像。 Try to find out that image and remove it.尝试找出该图像并将其删除。

import PIL
from pathlib import Path
from PIL import UnidentifiedImageError

def aggregate_images(
    dataset_root,
    extensions = ["png", "jpg", "jpeg"],
):
    """
    Globs for images in a given data directory and returns them
    """
    dataset_root = Path(dataset_root)
    image_paths = []

    for extension in extensions:
        image_paths.extend(list(dataset_root.glob("**/*.{}".format(extension))))

    return image_paths

path = aggregate_images(/path/to/your/dataset/root)
for img_p in path:
    try:
        img = PIL.Image.open(img_p)
    except PIL.UnidentifiedImageError:
            print(img_p)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM