Kelas MSE损失与我自己的损失函数有什么区别?

时间:2019-07-23 16:39:51

标签: tensorflow keras deep-learning loss-function

我对Keras陌生。我试图在Keras中创建自定义损失函数。 但是我的代码出了点问题。 Keras工作了,但是估计结果很奇怪。我应该在哪里更改代码?

我只是尝试将MSE实现为自定义损失函数。

这是损失函数部分。

def loss_function(ytrue, ypred):

    qx_true = ytrue[:, 0]
    qx_pred = ytrue[:, 0]
    qy_true = ytrue[:, 1]
    qy_pred = ytrue[:, 1]
    qz_true = ytrue[:, 2]
    qz_pred = ytrue[:, 2]
    qw_true = ytrue[:, 3]
    qw_pred = ytrue[:, 3]
    tx_true = ytrue[:, 4]
    tx_pred = ypred[:, 4]
    ty_true = ytrue[:, 5]
    ty_pred = ypred[:, 5]
    tz_true = ytrue[:, 6]
    tz_pred = ypred[:, 6]

    loss = ((tx_true - tx_pred) * (tx_true - tx_pred) 
        + (ty_true - ty_pred) * (ty_true - ty_pred) 
        + (tz_true - tz_pred) * (tz_true - tz_pred) 
        + (qx_true - qx_pred) * (qx_true - qx_pred) 
        + (qy_true - qy_pred) * (qy_true - qy_pred) 
        + (qz_true - qz_pred) * (qz_true - qz_pred) 
        + (qw_true - qw_pred) * (qw_true - qw_pred)) / 7

    return loss

这是呼叫损失功能部分

    model.add(Dense(7, name='output'))
    model.compile(loss=loss_function, optimizer=keras.optimizers.Adam())

当我尝试Keras原始损失函数时,它有效

    model.add(Dense(7, name='output'))
    model.compile(loss=keras.losses.MSE, optimizer=keras.optimizers.Adam())

损失函数的输入是平移的三个参数和四元数的四个参数。当我尝试使用keras.losses.MSE时,它起作用了,并且我尝试做相同的事情。

哪里是错误的部分?谢谢

1 个答案:

答案 0 :(得分:3)

我相信

qx_true = ytrue[:, 0]
qx_pred = ytrue[:, 0]
qy_true = ytrue[:, 1]
qy_pred = ytrue[:, 1]
qz_true = ytrue[:, 2]
qz_pred = ytrue[:, 2]
qw_true = ytrue[:, 3]
qw_pred = ytrue[:, 3]

应该是

qx_true = ytrue[:, 0]
qx_pred = ypred[:, 0]
qy_true = ytrue[:, 1]
qy_pred = ypred[:, 1]
qz_true = ytrue[:, 2]
qz_pred = ypred[:, 2]
qw_true = ytrue[:, 3]
qw_pred = ypred[:, 3]