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

如何在TensorFlow中实现适用于不平衡数据的加权平均绝对误差(MAE)损失函数?

解决TensorFlow中加权MAE损失函数的实现问题

你的思路方向是对的,但问题出在图模式下符号张量无法直接用Python字典取值——训练阶段TensorFlow默认采用图执行模式,y_true是符号张量,而class_weights.get(t, 1.0)是Python层面的即时操作,无法嵌入到计算图中,这才导致了执行失败。下面给你两种可行的解决方案:

方案1:手动实现加权MAE(推荐,更直观)

不用依赖losses.MeanAbsoluteError,直接手动计算加权平均绝对误差,全程用TensorFlow原生的图兼容操作:

import tensorflow as tf
from tensorflow.keras import losses

def weighted_mean_absolute_error(class_weights):
    # 将字典转换为TensorFlow可识别的键值对张量
    class_ids = tf.constant(list(class_weights.keys()), dtype=tf.int32)
    class_weights_tensor = tf.constant(list(class_weights.values()), dtype=tf.float32)
    
    def loss(y_true, y_pred):
        # 确保y_true的类型和class_ids一致
        y_true_int = tf.cast(y_true, tf.int32)
        # 使用TensorFlow的哈希表查找权重,支持符号张量操作
        weight_table = tf.lookup.StaticHashTable(
            tf.lookup.KeyValueTensorInitializer(class_ids, class_weights_tensor),
            default_value=1.0  # 找不到对应类别时用默认权重1.0
        )
        weights = weight_table.lookup(y_true_int)
        
        # 计算每个样本的绝对误差,加权后求平均
        abs_errors = tf.abs(y_true - y_pred)
        weighted_sum = tf.reduce_sum(abs_errors * weights)
        total_weights = tf.reduce_sum(weights)
        # 避免除以0(如果所有权重都是0的极端情况)
        return tf.math.divide_no_nan(weighted_sum, total_weights)
    return loss

方案2:修正原封装逻辑,兼容图模式

如果你还是想基于losses.MeanAbsoluteError来封装,核心是把权重查找改成图兼容的操作,替换掉原来的tf.map_fn + dict.get:

import tensorflow as tf
from tensorflow.keras import losses

def weighted_mean_absolute_error(class_weights):
    class_ids = tf.constant(list(class_weights.keys()), dtype=tf.int32)
    class_weights_tensor = tf.constant(list(class_weights.values()), dtype=tf.float32)
    
    def loss(y_true, y_pred):
        y_true_int = tf.cast(y_true, tf.int32)
        weights = tf.lookup.StaticHashTable(
            tf.lookup.KeyValueTensorInitializer(class_ids, class_weights_tensor),
            default_value=1.0
        ).lookup(y_true_int)
        
        mae = losses.MeanAbsoluteError()
        return mae(y_true, y_pred, sample_weights=weights)
    return loss

关键说明

  • tf.lookup.StaticHashTable是TensorFlow专门为图模式设计的哈希表操作,能处理符号张量的键查找,完美替代Python字典的get方法。
  • 两种方案都需要先把class_weights转换成TensorFlow张量,确保所有操作都在计算图中执行,避免eager模式操作和图模式操作的冲突。

内容的提问来源于stack exchange,提问作者mlinke-ai

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.30 16:02:33