我知道OP已经接受了winni2k的答案,但是由于问题标题实际上暗示着将model.summary()
的输出保存到一个字符串中,而不是文件,所以下面的代码可能会帮助其他人找到这个页面(就像我一样)。
下面的代码是在TensorFlow 1.12.0
上运行的,它自带了Python 3.6.2
上的Keras 2.1.6-tf
。
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Activation
import io
model = Sequential([
Dense(32, input_shape=(784,)),
Activation('relu'),
Dense(10),
Activation('softmax'),
])
def get_model_summary(model):
stream = io.StringIO()
model.summary(print_fn=lambda x: stream.write(x + '\n'))
summary_string = stream.getvalue()
stream.close()
return summary_string
model_summary_string = get_model_summary(model)
print(model_summary_string)
生成的字符串为:
_________________________________________________________________
Layer (type) Output Shape Param #
=================================================================
dense (Dense) (None, 32) 25120
_________________________________________________________________
activation (Activation) (None, 32) 0
_________________________________________________________________
dense_1 (Dense) (None, 10) 330
_________________________________________________________________
activation_1 (Activation) (None, 10) 0
=================================================================
Total params: 25,450
Trainable params: 25,450
Non-trainable params: 0
_________________________________________________________________