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

时间:2020-10-26 16:00:17

标签: tensorflow model loss-function

我想使用y_true和y_pred为张量流模型创建自定义损失函数,但出现以下错误: 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)

1 个答案:

答案 0 :(得分:0)

您可能不需要在其中循环。看起来您只需要一堆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)