【问题标题】:Create custom loss function in tensorflow with a loop使用循环在 tensorflow 中创建自定义损失函数
【发布时间】:2021-02-08 22:08:05
【问题描述】:

我想使用 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)

【问题讨论】:

    标签: tensorflow model loss-function


    【解决方案1】:

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

    • 1 - 如果sqr_pred_error &lt;= 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)
    

    【讨论】:

    • 当我将它用作指标时它可以工作,但作为损失我有这个消息错误:ValueError:没有为任何变量提供渐变:['dense/kernel:0','dense/bias: 0'、'dense_1/kernel:0'、'dense_1/bias:0'、'dense_2/kernel:0'、'dense_2/bias:0'、'dense_3/kernel:0'、'dense_3/bias:0' ]。有什么想法吗?
    • @JasonGreffier,这是有道理的。因为看看 tf.where 是如何运作的。它收集了一堆与预测本身无关的 1 和 0。所以不会有渐变。我看看能不能挽回损失fn
    • 我尝试的一切都失败了,如果你成功了告诉我
    • @JasonGreffier,是的,还没有机会。今天会尝试看看
    • 我没有看到你的最后评论。如果 sqr_pred_error
    猜你喜欢
    • 2021-02-22
    • 2018-10-28
    • 2017-12-29
    • 2019-10-29
    • 2021-03-11
    • 1970-01-01
    • 2019-12-16
    • 2020-07-29
    • 1970-01-01
    相关资源
    最近更新 更多