我不确定如何在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的新手,所以我不确定。训练后是否需要再次编译模型?
否,您不需要在训练后再次编译。
基于您的Sequential模型。
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))
访问层,如果使用功能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()
方法来检查output output是否为[[same,如model.summary()
所示。