首页 > 解决方案 > 如何在 Keras 模型的自定义损失中访问张量的内容

问题描述

我正在使用 Keras 模型构建一个自动编码器。我想以alpha* L2(x, x_pred) + beta * L1(day_x, day_x_pred). L1损失的第二项关于时间的惩罚(day_x是天数)。这一天是我输入数据中的第一个特征。我的输入数据是形式 ['day', 'beta', 'sigma', 'gamma', 'mu']

输入 x 的形状(batch_size,特征数),我有 5 个特征。所以我的问题是如何从x and x_pred计算中提取第一个特征L1(t_x, t_x_pred)。这是我当前的损失函数:

def loss_function(x, x_predicted):
    #with tf.compat.v1.Session() as sess:   print(x.eval())  
    return 0.7 * K.square(x- x_predicted) + 0.3 * K.abs(x[:,1]-x_predicted[:,1])

但这对我不起作用。

标签: pythontensorflowkerasautoencoderloss

解决方案


这是你需要的损失...

你必须计算你的错误的手段

def loss_function(x, x_predicted):

    get_day_true = x[:,0] # get day column
    get_day_pred = x_predicted[:,0] # get day column                           
    day_loss = K.mean(K.abs(get_day_true - get_day_pred))
    all_loss = K.mean(K.square(x - x_predicted))

    return 0.7 * all_loss + 0.3 * day_loss

否则,您必须插入一个维度

def loss_function(x, x_predicted):

    get_day_true = x[:,0] # get day column
    get_day_pred = x_predicted[:,0] # get day column                           
    day_loss = K.abs(get_day_true - get_day_pred)
    all_loss = K.square(x - x_predicted)

    return 0.7 * all_loss + 0.3 * tf.expand_dims(day_loss, axis=-1)

编译模型时使用损失

model.compile('adam', loss=loss_function)

推荐阅读