在进行迁移学习时,我首先通过 VGG16 网络的底层提供图像。我正在使用生成器函数。
datagen = ImageDataGenerator(1./255)
generator = datagen.flow_from_directory(
train_data_dir,
target_size=(img_width, img_height),
batch_size = 32,
class_mode=None,
shuffle=False
)
model.predict_generator(generator, nb_train_samples)
我将类模式设置为无,因为我只想要数据输出。我正在设置 shuffle = false,因为我想稍后在此处提供预测的特征,并将它们与地面实况类别变量相匹配:
train_data = np.lead(open(file_name, 'rb'))
train_labels = np.array([0] * NUMBER_OF_ITEMS_FOR_ITEM1 +
[1] * NUMBER_OF_ITEMS_FOR_ITEM2 +...
[n-1] * NUMBER_OF_ITEMS_FOR_ITEMN
这里的问题是我不知道文件的读取顺序是什么。我怎样才能找到它?或者更好的是,我怎样才能避免猜测正确的顺序?我问是因为我几乎可以肯定低预测准确度与标签不匹配有关。
最佳答案
我查看了 source code .我应该注意,自从我发布这个问题后,Keras 已更新到 2.0 版。所以答案是基于那个版本。
ImageDataGenerator 继承自DirectoryGenerator。在其中,我找到以下几行:
if not classes:
classes = []
for subdir in sorted(os.listdir(directory)):
if os.path.isdir(os.path.join(directory, subdir)):
classes.append(subdir)
self.num_class = len(classes)
self.class_indices = dict(zip(classes, range(len(classes))))
def _recursive_list(subpath):
return sorted(os.walk(subpath, followlinks=follow_links), key=lambda tpl: tpl[0])
for subdir in classes:
subpath = os.path.join(directory, subdir)
for root, _, files in _recursive_list(subpath):
for fname in files:
is_valid = False
for extension in white_list_formats:
if fname.lower().endswith('.' + extension):
is_valid = True
break
if is_valid:
self.samples += 1
print('Found %d images belonging to %d classes.' % (self.samples, self.num_class))
请注意第 3 行,其中显示“sorted(os.listdir(direcectory, subdir))”。生成器按字母顺序遍历所有文件夹。
稍后在 _recursive_list 的定义中也对子结构使用相同的逻辑。
所以答案是:文件夹按字母顺序处理,这在某种程度上是有道理的。
关于python - 如何检查 Keras 的 flow_from_directory 方法处理文件夹的顺序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42868982/