【问题标题】:Fail to write model history to a json file in the end of 2nd epoch of a keras fit_generator training在 keras fit_generator 训练的第二个 epoch 结束时无法将模型历史写入 json 文件
【发布时间】:2019-05-28 10:22:25
【问题描述】:

我正在使用自定义回调将模型历史参数(损失、acc 等)保存到 json 文件 on_epoch_end。我使用 keras fit_generator 来训练数据。在第一个时代结束时,一切正常,我可以得到带参数的 json 文件。但是,在第二个 epoch 之后,我总是遇到一个以“TypeError:'float32' 类型的对象不是 JSON 可序列化的对象”结尾的长错误。我很困惑,因为模型历史是一本字典。

我尝试过: 1) 将 json.dumps 更改为 json.dump。但是在第二个时代结束时同样的错误 2)我已经注​​释掉了json文件部分,并在我的回调类中添加了一个代码“print(self.H)”。有用。在每个 epoch 结束时,都可以打印出模型历史字典,并且我的训练可以无误地完成。 3)我使用 lr 衰减。一个观察结果是模型历史字典中第一个时期没有“lr”参数,并且从第 2 个时期开始,历史字典将添加一个“lr”参数。

class TrainingMonitor(BaseLogger):
    def __init__(self, figPath, jsonPath=None, startAt=0):
        # store the output path for the figure, the path to the JSON
        # serialized file, and the starting epoch
        super(TrainingMonitor, self).__init__()
        self.figPath = figPath
        self.jsonPath = jsonPath
        self.startAt = startAt

    def on_train_begin(self, logs={}):
        # initialize the history dictionary
        self.H = {}

    def on_epoch_end(self, epoch, logs={}):
        # loop over the logs and update the loss, accuracy, etc.
        # for the entire training process
        for (k, v) in logs.items():
            l = self.H.get(k, [])
            l.append(v)
            self.H[k] = l

        # check to see if the training history should be serialized to the file
        if self.jsonPath is not None:
            f = open(self.jsonPath, "w")
            f.write(json.dumps(self.H))
            f.close()

【问题讨论】:

    标签: python python-3.x numpy


    【解决方案1】:

    通过将“l.append(v)”更改为“l.append(float(v))”解决了问题。错误是因为“lr”的数据类型是 numpy.float32 并且 json 的编码器可能无法对其进行编码。下面显示数据类型已更改为原生 Python 浮点类型,然后写入 json 没有问题。

    acc <class 'numpy.float64'>
    
    acc <class 'float'>
    
    lr <class 'numpy.float32'>
    
    lr <class 'float'>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-10-12
      • 1970-01-01
      • 2020-03-20
      • 2019-04-27
      • 1970-01-01
      • 1970-01-01
      • 2020-05-05
      • 2018-12-19
      相关资源
      最近更新 更多