在keras fit_生成器培训的第2个epoch结束时,无法将模型历史写入json文件

2024-10-01 17:41:03 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用一个定制的回调将模型历史参数(loss、acc等)保存到一个json文件中。我用keras fit_发生器训练数据。在第一个epoch的末尾,一切都很好,我可以得到带有参数的json文件。但是,在第二个epoch之后,我总是遇到一个以“TypeError:float32”类型的对象不是JSON序列化的对象”结尾的长错误。我很困惑,因为模范历史是一本字典。在

我试过: 1) 改变json.dumps文件到json.dump文件. 但在第二个纪元的末尾也有同样的错误 2) 我已经注释掉了json文件部分,并在回调类中添加了一个代码“print(self.H)”。它起作用了。每到一个时代末,模型历史词典就可以打印出来,我的训练就可以毫无差错地完成了。 3) 我用lr衰变。一个观察是,第一个纪元的模型历史字典中没有“lr”参数,并且从第二个纪元开始,将为历史字典添加一个“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()

Tags: 文件the模型selfjson参数字典def
1条回答
网友
1楼 · 发布于 2024-10-01 17:41:03

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

acc <class 'numpy.float64'>

acc <class 'float'>

lr <class 'numpy.float32'>

lr <class 'float'>

相关问题 更多 >

    热门问题