最佳答案
是的,您可以使用 print_fn
参数将输出保存为字符串,然后将其解析为 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())
输出:
Layer (type) Output Shape Param #
0 dense (Dense) (None, 2) 4
1 dense_1 (Dense) (None, 1) 3
关于dataframe - 神经网络摘要到数据框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63843093/