首页 > 解决方案 > 带有 Theano 后端的 Keras:自定义损失函数

问题描述

我正在尝试在 Keras 中为单层 LSTM 回归问题创建一个自定义损失函数,该问题仅计算标签/真值向量中的非零值与预测向量中的相应值之间的均方误差。我尝试过以下操作

import theano.tensor as T
import keras.backend as K

def custom_loss_func(y_true, y_pred):

    #make the prediction vector zero where the label vector is zero
    y_pred = T.where(T.eq(y_true,0), 0, y_pred) 

    #get nonzero values
    nonzero_vals = T.flatnonzero(y_pred)

    #return mean squared error on only the nonzero values
    return K.sum(K.square(y_pred-y_true)) / K.shape(nonzero_vals)[0]

这会产生错误

“theano.gof.fg.MissingInputError:图表的输入 0(索引从 0 开始),用于计算 Elemwise{neq,no_inplace}(/masking_1_input, InplaceDimShuffle{x,x,x}.0),未提供且未给出值。使用 Theano 标志 exception_verbosity='high',以获取有关此错误的更多信息。”

这似乎不起作用,我认为这是由于非零向量的“形状”因素。我似乎无法从 Theano 文档中收集到如何将形状值拟合到表达式中。任何帮助表示赞赏,谢谢!

标签: pythonmachine-learningkerastheanomathematical-optimization

解决方案


推荐阅读