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

新手上路,请多包涵

我想写一个包含神经网络超参数和模型架构的 *.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

知道如何处理吗?

原文由 lmpeixoto 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 724
2 个回答

使用我的 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
_________________________________________________________________

原文由 winni2k 发布,翻译遵循 CC BY-SA 3.0 许可协议

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

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

原文由 FAnders 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题