TensorFlow自定义加权MSE损失函数报错:形状不可广播问题排查
自定义加权MSE损失函数的形状不兼容问题排查
问题背景
需要实现一个定制化均方误差(MSE)损失函数:
- 标签格式为
(x, y, w),其中w是样本权重 - 模型输出格式为
(x, y) - 需求:用
w加大特定样本的惩罚,同时对垂直方向(y轴)误差额外增加惩罚 - 使用TensorFlow 2.10,训练时触发
required broadcastable shapes错误
原错误代码
def mod_point_loss_weighted(y_true_in, y_pred): import tensorflow as tf # 提取标签中的(x, y)部分 y_true = tf.gather(y_true_in, [0, 1], axis=1) # 提取标签中的权重w部分 y_weight = tf.gather(y_true_in, [2], axis=1) y_true_cast = tf.cast(y_true, tf.float32) diff = y_pred - y_true_cast squared_diff = tf.square(diff) # 对垂直方向误差增加惩罚 weighted_loss = tf.multiply(squared_diff, [0.4, 0.6]) weighted_loss = tf.reduce_sum(weighted_loss, axis=1) # 应用自定义权重 loss = tf.multiply(weighted_loss, y_weight) return loss
错误堆栈
2023-06-23 12:17:42.718546: W tensorflow/core/framework/op_kernel.cc:1768] INVALID_ARGUMENT: required broadcastable shapes 2023-06-23 12:17:42.718583: W tensorflow/core/framework/op_kernel.cc:1768] INVALID_ARGUMENT: required broadcastable shapes Traceback (most recent call last): File "/home/enness/wqla/s3/train_topology.py", line 6, in <module> application.run("train:schema") File "/home/enness/wqla/s3/AuxBase/Application.py", line 103, in run context.execute(stage) File "/home/enness/wqla/s3/AuxBase/ContextImpl.py", line 115, in execute self.__execute_training() File "/home/enness/wqla/s3/AuxBase/ContextImpl.py", line 168, in __execute_training ModelTraining.train(self) File "/home/enness/wqla/s3/AuxBase/ModelTraining.py", line 132, in train history = model.fit( File "/home/enness/wqla/s3/venv/lib/python3.9/site-packages/keras/utils/traceback_utils.py", line 70, in error_handler raise e.with_traceback(filtered_tb) from None File "/home/enness/wqla/s3/venv/lib/python3.9/site-packages/tensorflow/python/eager/execute.py", line 54, in quick_execute tensors = pywrap_tfe.TFE_Py_Execute(ctx._handle, device_name, op_name, tensorflow.python.framework.errors_impl.InvalidArgumentError: Graph execution error: Detected at node 'mod_point_loss_weighted/sub' defined at (most recent call last): File "/home/enness/wqla/s3/train_topology.py", line 6, in <module> application.run("train:schema") File "/home/enness/wqla/s3/AuxBase/Application.py", line 103, in run context.execute(stage) File "/home/enness/wqla/s3/AuxBase/ContextImpl.py", line 115, in execute self.__execute_training() File "/home/enness/wqla/s3/AuxBase/ContextImpl.py", line 168, in __execute_training ModelTraining.train(self) File "/home/enness/wqla/s3/AuxBase/ModelTraining.py", line 132, in train history = model.fit( File "/home/enness/wqla/s3/venv/lib/python3.9/site-packages/keras/utils/traceback_utils.py", line 65, in error_handler return fn(*args, **kwargs) File "/home/enness/wqla/s3/venv/lib/python3.9/site-packages/keras/engine/training.py", line 1564, in fit tmp_logs = self.train_function(iterator) File "/home/enness/wqla/s3/venv/lib/python3.9/site-packages/keras/engine/training.py", line 1160, in train_function return step_function(self, iterator) File "/home/enness/wqla/s3/venv/lib/python3.9/site-packages/keras/engine/training.py", line 1146, in step_function outputs = model.distribute_strategy.run(run_step, args=(data,)) File "/home/enness/wqla/s3/venv/lib/python3.9/site-packages/keras/engine/training.py", line 1135, in run_step outputs = model.train_step(data) File "/home/enness/wqla/s3/venv/lib/python3.9/site-packages/keras/engine/training.py", line 994, in train_step loss = self.compute_loss(x, y, y_pred, sample_weight) File "/home/enness/wqla/s3/venv/lib/python3.9/site-packages/keras/engine/training.py", line 1052, in compute_loss return self.compiled_loss( File "/home/enness/wqla/s3/venv/lib/python3.9/site-packages/keras/engine/compile_utils.py", line 265, in __call__ loss_value = loss_obj(y_t, y_p, sample_weight=sw) File "/home/enness/wqla/s3/venv/lib/python3.9/site-packages/keras/losses.py", line 152, in __call__ losses = call_fn(y_true, y_pred) File "/home/enness/wqla/s3/venv/lib/python3.9/site-packages/keras/losses.py", line 272, in call return ag_fn(y_true, y_pred, **self._fn_kwargs) File "/home/enness/wqla/s3/AuxBase/TrainingUtil.py", line 51, in mod_point_loss_weighted diff = y_pred - y_true_cast Node: 'mod_point_loss_weighted/sub' required broadcastable shapes [[{{node mod_point_loss_weighted/sub}}]] [Op:__inference_train_function_5472] 2023-06-23 12:17:43.033798: W tensorflow/core/kernels/data/generator_dataset_op.cc:108] Error occurred when finalizing GeneratorDataset iterator: FAILED_PRECONDITION: Python interpreter state is not initialized. The process may be terminated. [[{{node PyFunc}}]]
问题根源
错误发生在diff = y_pred - y_true_cast这一步,说明y_pred和y_true_cast的形状不兼容,无法进行广播运算。
核心问题点:
- 维度不匹配:模型输出或标签提取后存在多余维度(比如模型输出是
(batch_size, 1, 2),而y_true_cast是(batch_size, 2)),导致减法运算无法广播。 - 权重张量维度冲突:
tf.reduce_sum(weighted_loss, axis=1)得到(batch_size,)形状的张量,而y_weight是(batch_size, 1)形状,后续相乘也会触发广播问题。
修复方案
修复后的代码
def mod_point_loss_weighted(y_true_in, y_pred): import tensorflow as tf # 提取标签中的(x, y)部分,移除多余维度确保形状为(batch_size, 2) y_true = tf.gather(y_true_in, [0, 1], axis=1) y_true = tf.squeeze(y_true, axis=1) if tf.rank(y_true) == 3 else y_true # 提取权重w并压缩为(batch_size,),和后续损失张量维度对齐 y_weight = tf.gather(y_true_in, 2, axis=1) y_weight = tf.squeeze(y_weight, axis=1) y_true_cast = tf.cast(y_true, tf.float32) # 确保模型输出和标签形状一致 y_pred = tf.squeeze(y_pred, axis=1) if tf.rank(y_pred) == 3 else y_pred diff = y_pred - y_true_cast squared_diff = tf.square(diff) # 对垂直方向(y轴)误差增加惩罚 weighted_loss = tf.multiply(squared_diff, [0.4, 0.6]) weighted_loss = tf.reduce_sum(weighted_loss, axis=1) # 应用自定义权重 loss = tf.multiply(weighted_loss, y_weight) return loss
额外排查建议
- 打印张量形状确认维度:
print("y_true_in shape:", tf.shape(y_true_in)) print("y_pred shape:", tf.shape(y_pred)) - 检查数据加载管道,确保标签被正确加载为
(batch_size, 3)的形状,无多余维度。
内容的提问来源于stack exchange,提问作者EnnessGe
相关产品推荐
相关产品推荐

