如何批量获取中间Keras层的输出?

时间:2020-03-31 12:00:26

标签: python tensorflow keras deep-learning feature-extraction

我不确定如何在Keras中获得中间层的输出。我已经阅读了关于stackoverflow的其他问题,但它们似乎是将单个样本作为输入的函数。我也想分批获取输出要素(在中间层)。这是我的模型:

model = Sequential()
model.add(ResNet50(include_top = False, pooling = RESNET50_POOLING_AVERAGE, weights = resnet_weights_path)) #None
model.add(Dense(784, activation = 'relu'))
model.add(Dense(NUM_CLASSES, activation = DENSE_LAYER_ACTIVATION))
model.layers[0].trainable = True

训练模型后,在我的代码中,我想在第一个密集层(784维)之后获得输出。这是正确的方法吗?

pred = model.layers[1].predict_generator(data_generator, steps = len(data_generator), verbose = 1)

我是Keras的新手,所以我不确定。训练后是否需要再次编译模型?

1 个答案:

答案 0 :(得分:1)

,您不需要在训练后再次编译。

基于您的顺序模型。

Layer 0 :: model.add(ResNet50(include_top = False, pooling = RESNET50_POOLING_AVERAGE, weights = resnet_weights_path)) #None
Layer 1 :: model.add(Dense(784, activation = 'relu'))
Layer 2 :: model.add(Dense(NUM_CLASSES, activation = DENSE_LAYER_ACTIVATION))

如果使用 Functional API 方法,访问层可能有所不同。

使用 Tensorflow 2.1.0 ,当您要访问中间输出时可以尝试这种方法。

model_dense_784 = Model(inputs=model.input, outputs = model.layers[1].output)

pred_dense_784 = model_dense_784.predict(train_data_gen, steps = 1) # predict_generator is deprecated

print(pred_dense_784.shape) # Use this to check Output Shape

强烈建议使用model.predict()方法,而不要使用model.predict_generator(),因为它已经已弃用
您还可以使用shape()方法检查所生成的输出是否与model.summary()所示的相同

相关问题