python - 在 keras fit_generator 训练的第二个时期结束时无法将模型历史写入 json 文件

标签 python python-3.x numpy

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

我试过了:
1) 将 json.dumps 更改为 json.dump。但是在第二个时代结束时出现了同样的错误
2) 我已经注释掉了 json 文件部分,并在我的回调类中添加了一个代码“print(self.H)”。有用。在每个 epoch 结束时,模型历史字典都可以打印出来,我的训练可以无误地完成。
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()

最佳答案

通过将“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'>

关于python - 在 keras fit_generator 训练的第二个时期结束时无法将模型历史写入 json 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56340068/

相关文章:

python - pandas:为列中的每一行计算 numpy 数组的平均值

python - 无法在新的 docker 容器上安装 psycopg2-binary

python - 使用python在excel中转​​换dicom标签时出错

python - 如何使用环境变量覆盖Python配置

python - 特定列中的简单 Numpy 最小值和最大值

python - 如何(/if)使用 dask 转置分布式 3D numpy 数组?

python - 复制并替换,同时将符号保留在属于搜索词的括号内

python - re.sub 字符串 : (? : . ..) 的一部分

python - 重新启动后Pyserial的串行连接问题

python - 如何为SVC绘制训练数据和训练目标