Python 在keras fit_生成器培训的第二个历元结束时,未能将模型历史记录写入json文件
我使用自定义回调将模型历史参数(loss、acc等)保存到_epoch_end上的json文件中。我使用keras fit_生成器来训练数据。在第一个纪元结束时,一切正常,我可以得到带有参数的json文件。然而,在第二个纪元之后,我总是遇到一个以“TypeError:类型为'float32'的对象不可JSON序列化”结尾的长错误。我很困惑,因为模型历史是一本字典 我试过: 1) 将json.dump更改为json.dump。但在第二纪元末同样的错误 2) 我已经注释掉了json文件部分,并在回调类中添加了代码“print(self.H)”。它起作用了。在每一个时代结束时,模型历史字典都可以打印出来,我的培训可以毫无差错地完成。 3) 我使用lr衰变。一个观察结果是,第一个历元的模型历史字典中没有“lr”参数,从第二个历元开始,历史字典将添加一个“lr”参数Python 在keras fit_生成器培训的第二个历元结束时,未能将模型历史记录写入json文件,python,python-3.x,numpy,Python,Python 3.x,Numpy,我使用自定义回调将模型历史参数(loss、acc等)保存到_epoch_end上的json文件中。我使用keras fit_生成器来训练数据。在第一个纪元结束时,一切正常,我可以得到带有参数的json文件。然而,在第二个纪元之后,我总是遇到一个以“TypeError:类型为'float32'的对象不可JSON序列化”结尾的长错误。我很困惑,因为模型历史是一本字典 我试过: 1) 将json.dump更改为json.dump。但在第二纪元末同样的错误 2) 我已经注释掉了json文件部分,并在回调
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'>
acc
行政协调会
lr
lr