neural network summary to dataframe

Issue

We can access the summary of a neural network by

model.summary()

But is there any way we can convert this result into a dataframe, so we can compare the features of different models?

enter image description here

Solution

Yes, you can do it by saving the output to a string using the print_fn parameter and then parsing it into a DataFrame:

from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense
import re
import pandas as pd

model = Sequential()
model.add(Dense(2, input_dim=1, activation='relu'))
model.add(Dense(1, activation='sigmoid'))

stringlist = []
model.summary(print_fn=lambda x: stringlist.append(x))
summ_string = "\n".join(stringlist)
print(summ_string) # entire summary in a variable

table = stringlist[1:-4][1::2] # take every other element and remove appendix

new_table = []
for entry in table:
    entry = re.split(r'\s{2,}', entry)[:-1] # remove whitespace
    new_table.append(entry)

df = pd.DataFrame(new_table[1:], columns=new_table[0])
print(df.head())

Output:

      Layer (type) Output Shape Param #
0    dense (Dense)    (None, 2)       4
1  dense_1 (Dense)    (None, 1)       3

Answered By – runDOSrun

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published