如何在Keras自定义指标函数内部设置断点进行调试
Keras自定义指标函数断点调试解决方案
方法1:使用回调函数实现调试(最稳定)
将指标计算逻辑迁移到Keras回调的批次/轮次钩子中,回调默认以eager模式执行,断点可正常命中:
from tensorflow import keras from sklearn.metrics import f1_score import numpy as np class F1DebugCallback(keras.callbacks.Callback): def on_batch_end(self, batch, logs=None): # 获取当前批次输入、真实标签和预测结果 x, y_true = self.validation_data[0], self.validation_data[1] y_pred = self.model.predict(x, verbose=0) # 以下为原指标计算逻辑,此处设置断点即可正常命中 y_true_array = np.squeeze(np.asarray(y_true)) y_pred_array = np.round(np.squeeze(np.asarray(y_pred))) f1 = f1_score(y_true_array, y_pred_array, "macro") print(f"批次{batch}的F1值:{f1}")
调用时将回调传入model.fit的callbacks参数即可:
model.fit(..., callbacks=[F1DebugCallback()])
方法2:修复run_eagerly执行顺序问题
之前设置run_eagerly未生效大多是执行顺序错误,需在导入TensorFlow后、定义所有模型和指标前就设置全局eager执行:
import tensorflow as tf # 所有代码最开始的位置设置,早于模型、指标定义 tf.config.run_functions_eagerly(True) from sklearn.metrics import f1_score import numpy as np # 原指标函数无需修改,此处设置断点即可命中 def f1_macro(y_true, y_pred): y_true_array = np.squeeze(np.asarray(y_true)) y_pred_array = np.round(np.squeeze(np.asarray(y_pred))) f1 = f1_score(y_true_array, y_pred_array, "macro") return f1 # 编译时保留run_eagerly=True参数 model.compile(optimizer="adam", loss="binary_crossentropy", metrics=[f1_macro], run_eagerly=True)
方法3:使用TensorFlow内置断点操作
如果上述方法都不生效,可以在指标函数内部插入TF专属调试断点,无论是否为eager模式都会触发中断:
def f1_macro(y_true, y_pred): y_true_array = np.squeeze(np.asarray(y_true)) y_pred_array = np.round(np.squeeze(np.asarray(y_pred))) # 插入调试断点,运行到此处会自动进入pdb调试界面 tf.debugging.experimental.enable_dump_debug_info("debug_logs", tensor_debug_mode="FULL_HEALTH", circular_buffer_size=-1) import pdb; pdb.set_trace() f1 = f1_score(y_true_array, y_pred_array, "macro") return f1
内容的提问来源于stack exchange,提问作者Luka
相关产品推荐
相关产品推荐

