'How to print summary of only last n layers of a model in keras

model.summary() prints details of the entire model. Is there a way to just print the last n layer(s) summary only?

If not, can I create a new model from the last n layers of an existing pre-trained model and print its summary instead.

I tried the following but it gives an error probably because of shared inputs:

temp_model = Model(inputs=base_model.layers[-4].input, outputs = base_model.layers[-1].output)
print(temp_model.summary())

Any help will be appreciated.



Solution 1:[1]

The last layers from summary are seen as something like this:

enter image description here

You can collect this information piece by piece and then put them together as below:

from collections import defaultdict
import pandas as pd  
from tabulate import tabulate

# Number of the last layers
last_layers_len = 5

# Create empty dictionary list
layers_summary = defaultdict(list)

# Iterate over the selected layers
for layer in model.layers[-last_layers_len:]:
    
    layers_summary['Layer'].append(layer.name) # layer name
    layers_summary['Output Shape'].append(layer.output_shape) # layer output shape
    layers_summary['Param #'].append(layer.count_params()) # layer parameter size

# Convert to pandas dataframe
layers_df = pd.DataFrame.from_dict(layers_summary) 

# Tabulate df
print(tabulate(layers_df, headers = 'keys', tablefmt = 'github'))

Output:

enter image description here

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 AEM