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?
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?
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
I've taken @runDOSrun's answer and adjusted it a bit to make it more comprehensive, as it was not working properly in the case where you had, for example, multiple connections.
import pandas as pd
import re
from tensorflow.keras.applications.inception_resnet_v2 import InceptionResNetV2
def clean(x):
return x.replace('[0][0]','').replace('(','').replace(')','').replace('[','').replace(']','')
def magic(x):
tmp = re.split(r'\s{1,}',clean(x))
return tmp
input_shape = (540,960,3)
model = InceptionResNetV2(input_shape)
width = 250
stringlist = []
model.summary(width, print_fn=lambda x: stringlist.append(x))
summ_string = "".join(stringlist)
splitstr1 = f"={{{width}}}"
splitstr2 = f"_{{{width}}}"
tmptable = re.split(splitstr1,summ_string)
header = re.split(splitstr2, tmptable[0])
header = re.split(r'\s{2,}', header[1])[:-1]
table = re.split(splitstr2, tmptable[1])
df = pd.DataFrame(columns=header)
for index,entry in enumerate(table):
entry = re.split(r'\s{2,}', entry)[:-1]
df.loc[index] = {header[0] : entry[0],
header[1] : tuple([int(e) for e in clean(entry[1]).split(', ')[1:]]),
header[2] : int(entry[2]),
header[3] : [clean(e) for e in entry[3:]]}
df['layername'],df['type'] = zip(*df['Layer (type)'].map(magic))
df['kernels'] = [e[-1:][0] for e in df['Output Shape']]
gives the following sample output: