Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

neural network summary to dataframe

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

like image 751
SeanZhang1997 Avatar asked Apr 30 '26 19:04

SeanZhang1997


1 Answers

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
like image 127
runDOSrun Avatar answered May 04 '26 16:05

runDOSrun



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!