4

我正在使用自定义回调将模型历史参数(损失、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()
4

1 回答 1

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'>
于 2019-05-29T13:21:38.880 回答