You need to enable JavaScript to run this app. 如何获取TensorFlow及Keras序列模型训练时每轮的耗时数据?
优惠活动
大模型
产品
解决方案
定价
更多

如何获取TensorFlow及Keras序列模型训练时每轮的耗时数据?

解决方案

Keras 原生返回的 History 对象默认不存储每轮训练的耗时数据,你可以通过**自定义回调(Custom Callback)**的方式实现需求,具体步骤如下:

步骤1:自定义耗时记录回调

import time
from tensorflow.keras.callbacks import Callback

class EpochTimeRecorder(Callback):
    def on_train_begin(self, logs=None):
        # 训练开始时初始化存储耗时的列表,单位:毫秒
        self.epoch_times = []

    def on_epoch_begin(self, epoch, logs=None):
        # 每轮开始时记录时间戳
        self.epoch_start_time = time.time()

    def on_epoch_end(self, epoch, logs=None):
        # 每轮结束时计算耗时,转成毫秒后存入列表
        epoch_duration = (time.time() - self.epoch_start_time) * 1000
        self.epoch_times.append(round(epoch_duration))

步骤2:训练时传入回调

修改你原来的model.fit代码,传入刚才定义的回调实例:

# 先实例化回调对象
time_recorder = EpochTimeRecorder()

# 训练时添加到callbacks参数中
history = model.fit(
    X_train, y_train,
    validation_split=0.2,
    epochs=500,
    verbose=1,
    callbacks=[time_recorder]
)

步骤3:获取每轮训练耗时

训练完成后直接访问回调实例的epoch_times属性即可,输出格式和你要求的完全一致:

# 输出示例:[159, 40, 36, 44, 49 ... ]
print(time_recorder.epoch_times)

如果需要保留小数位,修改on_epoch_end方法里的round逻辑即可,也可以根据需求把单位改成秒。

内容的提问来源于stack exchange,提问作者nurasaki

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.20 03:45:03