Keras model.summary()对象到字符串

2024-05-23 21:52:13 发布

您现在位置:Python中文网/ 问答频道 /正文

我想写一个带有神经网络超参数和模型结构的*.txt文件。是否可以将对象model.summary()写入我的输出文件?

(...)
summary = str(model.summary())
(...)
out = open(filename + 'report.txt','w')
out.write(summary)
out.close

碰巧我得到的是“没有”,你可以看到下面。

Hyperparameters
=========================

learning_rate: 0.01
momentum: 0.8
decay: 0.0
batch size: 128
no. epochs: 3
dropout: 0.5
-------------------------

None
val_acc: 0.232323229313
val_loss: 3.88496732712
train_acc: 0.0965207634216
train_loss: 4.07161939425
train/val loss ratio: 1.04804469418

你知道怎么处理吗?


Tags: 文件对象模型txt参数modeltrain神经网络
3条回答

对我来说,这只是将模型摘要作为一个字符串:

stringlist = []
model.summary(print_fn=lambda x: stringlist.append(x))
short_model_summary = "\n".join(stringlist)
print(short_model_summary)

使用我的Keras(2.0.6)和Python(3.5.0)版本,这对我很有用:

# Create an empty model
from keras.models import Sequential
model = Sequential()

# Open the file
with open(filename + 'report.txt','w') as fh:
    # Pass the file handle in as a lambda function to make it callable
    model.summary(print_fn=lambda x: fh.write(x + '\n'))

这将向文件输出以下行:

_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
Total params: 0
Trainable params: 0
Non-trainable params: 0
_________________________________________________________________

如果要写入日志:

import logging
logger = logging.getLogger(__name__)

model.summary(print_fn=logger.info)

相关问题 更多 >