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

时间:2017-01-15 20:14:32

标签: python deep-learning keras

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

知道怎么处理吗?

9 个答案:

答案 0 :(得分:27)

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

答案 1 :(得分:8)

如果你想写日志:

import logging
logger = logging.getLogger(__name__)

model.summary(print_fn=logger.info)

答案 2 :(得分:7)

这不是最好的方法,但你可以做的一件事是重定向stdout:

orig_stdout = sys.stdout
f = open('out.txt', 'w')
sys.stdout = f
print(model.summary())
sys.stdout = orig_stdout
f.close()

请参阅"How to redirect 'print' output to a file using python?"

答案 3 :(得分:5)

虽然不是model.summary的确切替代品,但是一个选项是使用model.get_config()导出模型的配置。来自the docs

  

model.get_config():返回包含模型配置的字典。该模型可以通过以下命令从其配置中重新实现:

config = model.get_config()
model = Model.from_config(config)
# or, for Sequential:
model = Sequential.from_config(config)

答案 4 :(得分:5)

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

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

答案 5 :(得分:4)

我偶然发现了同样的问题! 有两种可能的解决方法:

使用模型的to_json()方法

summary = str(model.to_json()) 

这是你的情况。

否则使用keras_diagram中的ascii方法

from keras_diagram import ascii
summary = ascii(model)

答案 6 :(得分:1)

我了解OP已接受winni2k的答案,但是由于问题标题实际上意味着将model.summary()的输出保存到 string 而不是文件中,因此以下代码可能会对其他人有所帮助谁来此页面寻找(像我一样)。

以下代码是使用TensorFlow 1.12.0运行的,它与Python 2.1.6-tf上的Keras 3.6.2一起提供。

from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Activation
import io

# Example model
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
_________________________________________________________________

答案 7 :(得分:1)

我有同样的问题。 @Pasa的答案非常有用,但我想我会举一个更简单的例子:这是合理的假设,此时您已经有了Keras模型。

import io

s = io.StringIO()
model.summary(print_fn=lambda x: s.write(x + '\n'))
model_summary = s.getvalue()
s.close()

print("The model summary is:\n\n{}".format(model_summary))

使用此字符串的示例很有用:如果您有 matplotlib 图。然后,您可以使用:

plt.text(0, 0.25, model_summary)

要将模型的摘要写到性能图表中,以供快速参考: enter image description here

答案 8 :(得分:0)

当我来到这里寻找一种记录摘要的方法时,我想与@ajb 的答案分享这个小小的转折,以避免日志文件中每一行的 INFO:使用@FAnders 回答:

def get_model_summary(model: tf.keras.Model) -> str:
    string_list = []
    model.summary(line_length=80, print_fn=lambda x: string_list.append(x))
    return "\n".join(string_list)

# some code
logging.info(get_model_summary(model)

生成的日志文件如下: enter image description here