繁体   English   中英

自定义损失函数的实现

[英]Custom loss function implementation

我正在尝试实现自己的新损失功能。 当我尝试对其进行调试(或打印)时,我注意到在代码的模型创建部分仅对其调用了一次。

如果在拟合模型时无法将代码运行到该函数中,如何知道y_pred和y_true包含哪些内容(形状,数据等)?

我写了这个损失函数:

def my_loss(y_true, y_pred):
    # run over the sequence, jump by 3
    # calc the label
    # if the label incorrect punish

    y_pred = K.reshape(y_pred, (1, 88, 3))

    y_pred = K.argmax(y_pred, axis=1)

    zero_count = K.sum(K.clip(y_pred, 0, 0))
    one_count = K.sum(K.clip(y_pred, 1, 1))
    two_count = K.sum(K.clip(y_pred, 2, 2))

    zero_punish = 1 - zero_count / K.count_params(y_true)
    one_punish = 1- one_count/ K.count_params(y_true)
    two_punish = 1- two_count/ K.count_params(y_true)

    false_arr = K.not_equal(y_true, y_pred)

    mask0 = K.equal(y_true, K.zeros_like(y_pred))
    mask0_miss = K.dot(false_arr, mask0) * zero_punish

    mask1 = K.equal(y_true, K.ones_like(y_pred))
    mask1_miss = K.dot(false_arr, mask1) * one_punish

    mask2 = K.equal(y_true, K.zeros_like(y_pred)+2)
    mask2_miss = K.dot(false_arr, mask2) * two_punish

    return K.sum(mask0_miss) + K.sum(mask1_miss) + K.sum(mask2_miss)

它在以下方面失败:

theano.gof.fg.MissingInputError: A variable that is an input to the graph was 
neither provided as an input to the function nor given a value. A chain of 
variables leading from this input to an output is [/dense_1_target, Shape.0]. 
This chain may not be unique
Backtrace when the variable is created:

我该如何解决?

您必须了解Theano是一种象征性语言。 例如,当我们在Keras中定义以下损失函数时:

def myLossFn(y_true, y_pred):
    return K.mean(K.abs(y_pred - y_true), axis=-1)

Theano只是在计算图中制定一个符号规则,当它获得值时即在您使用一些小批量训练模型时将执行该规则。

至于关于如何调试模型的问题,可以使用theano.function 现在,您想知道损失计算是否正确。 您执行以下操作。

您可以实现损失函数的python / numpy版本。 将两个随机向量传递给numpy-loss-function并获得一个数字。 要验证theano是否给出几乎相同的结果,请定义以下内容。

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

Y_true = T.frow('Y_true')
Y_pred = T.fcol('Y_pred')
out = K.mean(K.abs(Y_pred - Y_true), axis=-1)

f = theano.function([Y_true, Y_pred], out)

# creating some values
y_true = np.random.random((10,))
y_pred = np.random.random((10,))

numpy_loss_result = np.mean(np.abs(y_true-y_pred))
theano_loss_result = f(y_true, y_pred)

# check if both are close enough
print numpy_loss_result-theano_loss_result # should be less than 1e-5

基本上, theano.function是一种放置值并评估这些符号表达式的方法。 我希望这有帮助。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM