【问题标题】:Is there a way to write up a custom loss function in keras?有没有办法在 keras 中编写自定义损失函数?
【发布时间】:2021-05-07 17:38:58
【问题描述】:

有没有办法在 keras 中编写自定义 MSE 损失函数?

我的训练样本是 k x n 输入的横截面数据,我的输出是时间 t 的 k x 1,但 t 的范围从 t-1 到 t-120(横截面数据的每月时间戳)。

我想编写一个自定义的 MSE 损失函数,它本质上对训练样本 t-120 赋予较低的权重,而对训练样本 t-1 赋予更高的权重。

有没有办法做到这一点?

这是一些在 keras 中编写自定义损失函数的简单代码。

def my_loss_fn(y_true, y_pred):

    squared_difference = tf.square(y_true - y_pred)
    return tf.reduce_mean(squared_difference, axis=-1)  # Note the `axis=-1`

model.compile(optimizer='adam', loss=my_loss_fn)

【问题讨论】:

    标签: python tensorflow keras


    【解决方案1】:

    您可以使用类权重来为每个输出单元指定自定义权重,然后在 model.fit() 1 上指定它

    【讨论】:

    • 感谢这位天使。我查了一下——实际上可以在 model.fit() 中指定样本权重,而不是类权重(它可以解决分类问题),这似乎可以解决问题。谢谢
    • 很高兴为您提供帮助:D
    猜你喜欢
    • 2020-04-09
    • 1970-01-01
    • 2021-09-21
    • 2020-12-19
    • 2017-12-18
    • 2020-03-27
    • 1970-01-01
    • 1970-01-01
    • 2018-12-03
    相关资源
    最近更新 更多