【问题标题】:Keras model.summary() object to stringKeras model.summary() 对象到字符串
【发布时间】:2017-05-30 15:59:43
【问题描述】:

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

知道如何处理吗?

【问题讨论】:

标签: python tensorflow machine-learning keras deep-learning


【解决方案1】:

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

【讨论】:

  • 2.0.6 版新功能
  • 作为附加注释:您还可以使用line_length 作为额外参数来调整输出行的长度。这很有用,因为有时图层名称太长,因此被剪切:model.summary(line_length=80, print_fn=lambda x: fh.write(x + '\n'))
【解决方案2】:

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

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

【讨论】:

    【解决方案3】:

    如果你想写入日志:

    import logging
    logger = logging.getLogger(__name__)
    
    model.summary(print_fn=logger.info)
    

    【讨论】:

      【解决方案4】:

      我知道 OP 已经接受了 winni2k 的回答,但是由于问题标题实际上暗示将 model.summary() 的输出保存到 字符串,而不是文件,因此以下代码可能会帮助其他人到这个页面寻找那个(就像我做的那样)。

      下面的代码是使用 TensorFlow 1.12.0 运行的,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
      
      # 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
      _________________________________________________________________
      

      【讨论】:

        【解决方案5】:

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

        使用模型的to_json()方法

        summary = str(model.to_json())
        

        这是你上面的情况。

        否则使用 keras_diagram 中的 ascii 方法

        from keras_diagram import ascii
        summary = ascii(model)
        

        【讨论】:

          【解决方案6】:

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

          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?"

          【讨论】:

            【解决方案7】:

            虽然不是 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)
            

            【讨论】:

              【解决方案8】:

              我遇到了同样的问题。 @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)
              

              要将模型摘要写入性能图表,以供快速参考:

              【讨论】:

                【解决方案9】:

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

                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)
                

                生成一个日志文件:

                【讨论】:

                  猜你喜欢
                  • 1970-01-01
                  • 1970-01-01
                  • 1970-01-01
                  • 2012-10-11
                  • 1970-01-01
                  • 1970-01-01
                  • 2021-04-28
                  • 2022-12-02
                  • 2020-06-18
                  相关资源
                  最近更新 更多