Tensorflow 具有keras的损失函数中的批量元素产品
我正试图在keras中编写一个自定义损失函数,其中我需要通过中间层(其形状为(batch_size,1))的输出对y_true和y_pred(形状:(batch_size,64,64))之间的MSE进行加权 我需要的op只是将MSE的每个批次元素加权(乘以)一个因子,即加权张量中对应的批次元素 我尝试了以下方法Tensorflow 具有keras的损失函数中的批量元素产品,tensorflow,keras,backend,loss,eager-execution,Tensorflow,Keras,Backend,Loss,Eager Execution,我正试图在keras中编写一个自定义损失函数,其中我需要通过中间层(其形状为(batch_size,1))的输出对y_true和y_pred(形状:(batch_size,64,64))之间的MSE进行加权 我需要的op只是将MSE的每个批次元素加权(乘以)一个因子,即加权张量中对应的批次元素 我尝试了以下方法 def loss_aux_wrapper(weight_tensor): def loss_aux(y_true, y_pred): K.print_tensor
def loss_aux_wrapper(weight_tensor):
def loss_aux(y_true, y_pred):
K.print_tensor(weight_tensor, message='weight = ')
_shape = K.shape(y_true)
return K.reshape(K.batch_dot(K.batch_flatten(mse(y_true, y_pred)), weight_tensor, axes=[1,1]),_shape)
return loss_aux
但我明白了
tensorflow.python.framework.errors_impl.InvalidArgumentError: In[0] mismatch In[1] shape: 4096 vs. 1: [32,1,4096] [32,1,1] 0 0 [[node loss/aux_motor_output_loss/MatMul (defined at /code/icub_sensory_enhancement/scripts/models.py:327) ]] [Op:__inference_keras_scratch_graph_6548]
我相信K.print_张量不会输出任何东西,因为它是在编译时调用的
非常感谢您的任何建议 为了加权MSE损失函数,您可以在调用
MSE
函数时使用sample\u weight=
参数。根据,
如果
样品重量
是一个大小张量[批次大小]
,然后是总损失
对于批次的每个样品,由相应的元素重新缩放
在样本权重向量中。如果样品重量的形状为
[批量大小,d0,…dN-1]
(或可以广播到此形状),然后
y_pred
的每个损失元素按
样品重量
。(注:N-1:所有损失函数减少1维,
通常轴=-1
)
在您的例子中,重量张量
有一个形状(批量大小,1)
。所以首先我们需要重塑它,比如
reshaped_weight_tensor = K.reshape( weight_tensor , shape=( batch_size ) )
然后,该张量可与MeanSquaredError
一起使用
def loss_aux_wrapper(weight_tensor):
def loss_aux(y_true, y_pred):
reshaped_weight_tensor = K.reshape( weight_tensor , shape=( batch_size ) )
return mse( y_true , y_pred , sample_weight=reshaped_weight_tensor )
return loss_aux