【问题标题】:Keras: What is the output of predict_generator?Keras:predict_generator 的输出是什么?
【发布时间】:2017-09-13 14:35:05
【问题描述】:

Keras 文档说它返回“A Numpy array of predictions”。 在具有 4 个类的 496 个图像示例上使用它,我得到一个 4 维数组 (496、4、4、512)。其他 2 个维度是什么? 最终,我想要一个 X 数组(示例)和一个 Y 数组(标签)。

img_width, img_height = 150, 150
top_model_weights_path = 'bottleneck_fc_model.h5'
train_data_dir = 'data/train'
validation_data_dir = 'data/validation'
nb_train_samples = 496
nb_validation_samples = 213
epochs = 50
batch_size = 16
number_of_classes = 3
datagen = ImageDataGenerator(rescale=1. / 255)

# build the VGG16 network (exclude last layer)
model = applications.VGG16(include_top=False, weights='imagenet')

# generate training data from image files
train_generator = datagen.flow_from_directory(
    train_data_dir,
    target_size=(img_width, img_height),
    batch_size=batch_size,
    class_mode='categorical',
    shuffle=False)

# predict bottleneck features on training data
bottleneck_features_train = model.predict_generator(
    train_generator, nb_train_samples // batch_size)
print(bottleneck_features_train.shape)

train_data = np.load(open('bottleneck_features_train.npy', 'rb'))
print(train_data.shape)

【问题讨论】:

  • 能否请您发布代码的相关部分,尤其是描述您的模型的部分?
  • @Mike - 添加代码

标签: python python-3.x numpy keras


【解决方案1】:

您正在做的是从您提供给模型的图像中提取瓶颈特征。 您获得的形状 (496, 4, 4, 512) 是 (n_samples, feature_height, feature_width, feature:channels) 你通过传递取出模型的密集层

include_top=False

为了解释,你通过这个模型传递了样本

没有最后 4 层。 (你有不同的高度和宽度,因为你的凝视图像是 150x150 而不是标准 VGG16 中的 224x224

你得到的不是类别的预测,而是图像重要特征的合成表示。

要获得您似乎需要的内容,您可以像这样修改代码

model = applications.VGG16(include_top=False, weights='imagenet')
for layer in model.layers:
    layer.trainable = False
model = Dense(512, activation='relu')(model) #512 is a parameter you can tweak, the higher, the more complex the model
model = Dense(number_of_classes, activation='softmax')(model)

现在,您可以在用于训练模型的样本上调用 model.fit(X,Y),将 496 个样本图像作为 X 并将您准备的地面实况标签作为 Y。

训练结束后,您可以使用 model.predict 来预测您需要的类。

【讨论】:

  • 谢谢!但是如何从 train_data 为 model.fit(X,Y) 生成矩阵 X 和 Y?
  • 由于您似乎正在使用生成器,您可以使用 model.fit_generator(train_generator, steps_per_epoch=100, epochs=100)
猜你喜欢
  • 1970-01-01
  • 2021-01-21
  • 2017-11-22
  • 1970-01-01
  • 1970-01-01
  • 2017-02-04
  • 2016-02-11
  • 2020-01-17
  • 2019-11-01
相关资源
最近更新 更多