gpt4 book ai didi

python - 每个纪元后的自定义回调以记录某些信息

转载 作者:太空宇宙 更新时间:2023-11-04 00:07:23 28 4
gpt4 key购买 nike

我知道如何 save the model after every epoch :

savemodel = ModelCheckpoint(filepath='models/model_{epoch:02d}-{loss:.2f}.h5')
model.fit(X, Y, batch_size=4, epochs=32, verbose=1, callbacks=[savemodel])

如何使用自定义回调函数来记录某些信息:

def write_metrics(): 
with open('log.txt', 'a') as f: # append to the log file
f.write('{epoch:02d}: loss = {loss:.1f}')

model.fit(X, Y, batch_size=4, epochs=32, verbose=1, callbacks=[savemodel, write_metrics])

?

使用此代码将无法工作,因为 {loss}{epoch} 未在 f.write('{epoch:02d} : loss = {loss:.1f}').

最佳答案

这是解决方案,通过子类化 Callback:

from keras.callbacks import Callback

class MyLogger(Callback):
def on_epoch_end(self, epoch, logs=None):
with open('log.txt', 'a+') as f:
f.write('%02d %.3f\n' % (epoch, logs['loss']))

然后

mylogger = MyLogger()
model.fit(X, Y, batch_size=32, epochs=32, verbose=1, callbacks=[mylogger])

甚至

model.fit(X, Y, batch_size=32, epochs=32, verbose=1, callbacks=[MyLogger()])

关于python - 每个纪元后的自定义回调以记录某些信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53640596/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com