首页 > 解决方案 > 自定义损失函数 keras TypeError

问题描述

我想在 keras 中编写一个自定义损失函数:

def cus_loss_fn(y_true, y_pred):
    a = tf.convert_to_tensor(1, dtype=tf.float32)
    lSRCC = tf.math.subtract(
        a, tf.py_function(
            spearmanr, 
            [tf.cast(y_pred, tf.float32), tf.cast(y_true, tf.float32)], 
            Tout=tf.float32))
    lPLCC = tf.math.subtract( 
         a, tf.py_function(
             pearsonr, 
             [tf.cast(y_pred, tf.float32), tf.cast(y_true, tf.float32)], 
             Tout=tf.float32))
    alpha = tf.convert_to_tensor(0.5, dtype=tf.float32)
    res = tf.math.add(lPLCC , tf.math.multiply(alpha,lSRCC ))
    
    return (tf.convert_to_tensor(res,dtype=tf.float32))

但是当我尝试将数据拟合到我的模型中时出现以下错误。

TypeError: No loop matching the specified signature and casting was found for ufunc add


     [[node cus_loss_fn/EagerPyFunc_1 (defined at <ipython-input-16-f7ce00c481ca>:6) ]] [Op:__inference_train_function_4985]

Errors may have originated from an input operation.
Input Source operations connected to node cus_loss_fn/EagerPyFunc_1:
 sequential/dense_1/Softmax (defined at <ipython-input-17-a300d9883dd2>:4)  
 cus_loss_fn/EagerPyFunc (defined at <ipython-input-16-f7ce00c481ca>:4)

Function call stack:
train_function

我应该如何在 keras 中做到这一点?

标签: pythonkerasloss-function

解决方案


推荐阅读