如何批量获取中间Keras层的输出? [英] How to get output of intermediate Keras layers in batches?

查看:67
本文介绍了如何批量获取中间Keras层的输出?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am not sure how to get output of an intermediate layer in Keras. I have read the other questions on stackoverflow but they seem to be functions with a single sample as input. I want to get output features(at intermediate layer) in batches as well. Here is my model:

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维)之后获得输出.这是正确的方法吗?

After training the model, in my code I want to get the output after the first dense layer (784 dimensional). Is this the right way to do it?

pred = model.layers [1] .predict_generator(data_generator,步骤= len(data_generator),详细= 1)

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

I am new to Keras so I am a little unsure. Do I need to compile the model again after training?

推荐答案

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

No, you don't need to compile again after training.

基于您的顺序模型.

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 方法,访问这些层可能会有所不同.

Accessing the layers, may differ if used Functional API approach.

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

Using Tensorflow 2.1.0, you could try this approach when you want to access intermediate outputs.

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()所示..

It is highly advisable to use the model.predict() method, rather than model.predict_generator() as it is already deprecated.
You could also use shape() method to check whether the output generated is the same as indicated on the model.summary().

这篇关于如何批量获取中间Keras层的输出?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆