使用循环在tensorflow中创建自定义损失函数



我想使用y_true和y_pred为tensorflow模型创建一个自定义损失函数,但我得到了以下错误:ValueError:无法从形状推断num(无,1(这是我的自定义度量:

def custom_metric(y_true,y_pred):
    y_true = float(y_true)
    y_pred = float(y_pred)
    y_true = tf.unstack(y_true)
    y_pred = tf.unstack(y_pred)
    sqr_pred_error = K.square(y_true - y_pred)
    sqr_y_true = K.square(y_true)
    r = []
    for i in y_true:
        if sqr_pred_error[i] < sqr_y_true[i] or sqr_pred_error[i] == sqr_y_true[i]:
            result = 1
            print("result: 1")
        else:
            result = 0
            print("result: 0")
        r.append(result)
    r = tf.stack(r)
    return  K.sum(r)/K.shape(r)

您可能不需要其中的循环。看起来你只需要一堆0和1。

  • 1-如果sqr_pred_error <= sqr_y_true
  • 0-其他

然后您可以执行以下操作。

def custom_metric(y_true,y_pred):
    y_true = tf.cast(y_true, 'float32')
    y_pred = tf.cast(y_pred, 'float32')
    
    sqr_pred_error = K.square(y_true - y_pred)
    sqr_y_true = K.square(y_true)
    res = tf.where(sqr_pred_error<=sqr_y_true, tf.ones_like(y_true), tf.zeros_like(y_true))
    return  K.mean(res)

最新更新