You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Keras后端显示完整张量?用于自定义损失函数调试

在Keras自定义损失函数中查看完整张量的方法
  • 用tf.print替代keras.backend.print_tensor
    如果你用TensorFlow作为Keras后端,直接用tf.print就能输出完整张量,它支持关闭截断功能:

    import tensorflow as tf
    from keras import backend as K
    
    def custom_loss(y_true, y_pred):
        # summarize=-1表示输出全部元素,不截断
        tf.print("完整y_true张量:", y_true, summarize=-1)
        loss = K.mean(K.square(y_true - y_pred))
        return loss
    
  • 把张量内容写入本地文件
    可以在损失函数里用TensorFlow的文件API把张量存成文本或二进制文件,方便后续查看:

    def custom_loss(y_true, y_pred):
        # 将张量转为字符串,保留10位精度
        tensor_str = tf.strings.as_string(y_true, precision=10)
        # 写入文件,避免覆盖可以加上批次标识
        batch_num = tf.Variable(0, dtype=tf.int32)
        batch_num.assign_add(1)
        filename = tf.strings.format("/tmp/y_true_batch_{}.txt", batch_num)
        tf.io.write_file(filename, tensor_str)
        
        loss = K.mean(K.square(y_true - y_pred))
        return loss
    
  • 通过自定义回调提取张量值
    不想在损失函数里硬编码的话,可以自定义回调,在训练批次结束后获取张量的实际数值:
    先调整模型,把需要监控的张量设为额外输出:

    from keras.models import Model
    from keras.layers import Dense, Input
    
    input_layer = Input(shape=(10,))
    output_layer = Dense(1)(input_layer)
    # 把y_true和y_pred作为额外输出,训练时要对应传入输入
    model = Model(inputs=[input_layer, input_layer], outputs=[output_layer, input_layer, output_layer])
    

    然后写回调类:

    class TensorLogger(keras.callbacks.Callback):
        def on_train_batch_end(self, batch, logs=None):
            # 获取当前批次的y_true和y_pred数值
            y_true_val = self.model.inputs[1].numpy()
            y_pred_val = self.model.outputs[0].numpy()
            
            # 直接打印
            print(f"批次{batch}的y_true:\n{y_true_val}")
            # 存成numpy文件,方便后续加载分析
            import numpy as np
            np.save(f"/tmp/y_true_batch_{batch}.npy", y_true_val)
    

    训练时传入回调即可:

    model.compile(optimizer='adam', loss=custom_loss)
    model.fit([X_train, y_train], y_train, callbacks=[TensorLogger()])
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 19:51:02