【问题标题】:Convolutional Neural Network: can't loop through DirectoryIterator卷积神经网络:无法循环通过 DirectoryIterator
【发布时间】:2018-06-01 14:36:21
【问题描述】:

我正在使用 Keras 实现一个 CNN 图像分类器。我有一个包含训练图像的文件夹和另一个包含验证图像的文件夹,但我没有定义类。

import numpy as np
import os
import matplotlib.pyplot as plt
%matplotlib inline
from __future__ import print_function
import keras
from keras.utils import to_categorical
from keras.preprocessing.image import ImageDataGenerator, array_to_img,img_to_array, load_img
from keras.applications import InceptionV3

conv_base = InceptionV3(weights='imagenet',
                    include_top=False,
                    input_shape=(224, 224, 3))

train_dir = 'MO444_dogs/train/'
validation_dir = 'MO444_dogs/val/'
nTrain = 600
nVal = 150

datagen = ImageDataGenerator(rescale=1./255)
batch_size = 30 
train_features = np.zeros(shape=(nTrain, 7, 7, 512))
train_labels = np.zeros(shape=(nTrain,3)) 
train_generator = datagen.flow_from_directory(
    train_dir,
    target_size=(224, 224),
    batch_size=batch_size,
    class_mode=None,
    shuffle=True)

上面的代码 sn-p 可以正常工作。当我尝试使用 model.predict() 函数通过网络传递图像时,问题就开始了。好吧,更准确地说,它开始于稍早之前,在 for 循环中:

i = 0
for inputs_batch, labels_batch in train_generator:
    features_batch = conv_base.predict(inputs_batch)
    train_features[i * batch_size : (i + 1) * batch_size] = features_batch
    train_labels[i * batch_size : (i + 1) * batch_size] = labels_batch
    i += 1
    if i * batch_size >= nTrain:
        break

最后一个 sn-p 输出这个:

基本上 train_generator 变量是一个 DirectoryIterator 对象,产生 numpy 数组的元组。到目前为止,我认为该错误可能与我没有定义类的事实有关,也许?我认为可能是因为我发现了类似的工作示例,例如 this,但使用文件夹定义的类,就像 Keras 文档解释的那样。

到目前为止,我正在寻找执行此循环的替代方法,但也许我需要完全采用另一种方法。

谢谢或任何指示。

【问题讨论】:

  • 是的,问题是因为它需要文件夹定义的类,但没有它们我不知道如何解决。尝试这样做for x in train_generator: print(x)
  • 另外,您可以在datagen.flow_from_directory() 中使用classes 参数传递您自己的类列表,例如classes=['cat', 'dog']
  • 这是个问题。这些课程基本上是犬种,但它们是未知的……我想我猜不到。我做了你建议的 for 循环,它打印出一个大的 numpy 数组元组,正如预期的那样

标签: python image-processing keras deep-learning convolutional-neural-network


【解决方案1】:

嗯,我重新检查了我的数据,发现其中有一个类模式。所以有课程,我用它解决了问题。

【讨论】:

    猜你喜欢
    • 2017-01-01
    • 1970-01-01
    • 2015-02-27
    • 1970-01-01
    • 1970-01-01
    • 2020-11-01
    • 2020-10-07
    • 2020-10-19
    相关资源
    最近更新 更多