Why I can't get the internal output of a trained model?

Viewed 55
import tensorflow.keras as keras
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt

if __name__ == '__main__':
    model = keras.models.load_model('model/model_test_0.99408.h5', custom_objects={'leaky_relu': tf.nn.leaky_relu})
    model.summary()
    inputs = keras.layers.Input(shape=(28, 28, 1))
    y = model(inputs)
    feature = model.get_layer('conv2d_4').output
    model = keras.Model(inputs=inputs, outputs=[y, feature])
    model.summary()

why i can't get the output of 'conv2d_4' that is the internal layer of the model? And i get the following error.

Graph disconnected: cannot obtain value for tensor Tensor("input_1:0", shape=(None, 28, 28, 1), dtype=float32) at layer "conv2d". The following previous layers were accessed without issue: []
1 Answers

We can try restacking the model, assigning feature to the required layer,

import tensorflow.keras as keras
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt

if __name__ == '__main__':
    model = keras.models.load_model('model/model_test_0.99408.h5', custom_objects={'leaky_relu': tf.nn.leaky_relu})
    model.summary()
    inputs = keras.layers.Input(shape=(28, 28, 1))
    y = inputs
    for layer in vgg.layers:
        if layer.name == 'conv2d_4':
            feature = y
        y = layer( y )
    model = keras.Model(inputs=inputs, outputs=[y, feature])
    model.summary()
Related