python - 从 Keras 中的生成器获取 x_test、y_test?

标签 python numpy keras marshalling keras-2

对于某些问题,验证数据不能是生成器,例如:TensorBoard histograms :

If printing histograms, validation_data must be provided, and cannot be a generator.

我当前的代码如下:

image_data_generator = ImageDataGenerator()

training_seq   = image_data_generator.flow_from_directory(training_dir)
validation_seq = image_data_generator.flow_from_directory(validation_dir)
testing_seq    = image_data_generator.flow_from_directory(testing_dir)

model = Sequential(..)
# ..
model.compile(..)
model.fit_generator(training_seq, validation_data=validation_seq, ..)

如何将其提供为 validation_data=(x_test, y_test)

最佳答案

Python 2.7 和 Python 3.* 解决方案:

from platform import python_version_tuple

if python_version_tuple()[0] == '3':
    xrange = range
    izip = zip
    imap = map
else:
    from itertools import izip, imap

import numpy as np

# ..
# other code as in question
# ..

x, y = izip(*(validation_seq[i] for i in xrange(len(validation_seq))))
x_val, y_val = np.vstack(x), np.vstack(y)

或者支持class_mode='binary',则:

from keras.utils import to_categorical

x_val = np.vstack(x)
y_val = np.vstack(imap(to_categorical, y))[:,0] if class_mode == 'binary' else y

完整的可运行代码:https://gist.github.com/AlecTaylor/7f6cc03ed6c3dd84548a039e2e0fd006

关于python - 从 Keras 中的生成器获取 x_test、y_test?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50928329/

相关文章:

python - python 中变量定义的意外行为

machine-learning - 使用 Keras 查看层激活

python - Keras:模型和图层有什么区别?

python - Keras 中的 Rank 是多少?

python - 什么时候重构?

python - 更改似乎不会在 Postgres DB 中生效

python - 将 DataFrame 过滤为具有 2 个以上 True 元素的行

python - 在 C 扩展中使用 Python 列表

python - 为什么这个神经网络会给出运行时警告?

python - 有效地删除 numpy 图像数组的行/列