2017-03-13 72 views
1

我试图实现我自己的新损失函数。 当我试图调试它(或在其中打印)时,我注意到它在代码的模型创建部分仅被调用一次。自定义丢失函数的实现

我怎么能知道什么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: 

我怎样才能解决呢?

+1

你可以显示相关故障代码,所以我们有东西去?你现在的问题基本上是问“我_B_不工作时怎么办?而不是“我怎样才能再次工作?” –

回答

2

你必须明白,Theano是一个象征性的语言。例如,当我们定义Keras下列损失函数:

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

Theano只是在计算图形制作一个象征性的规则,当它到达当你与一些迷你训练模型值,即它会被处决批次。

至于如何调试你的模型去你的问题,你可以使用theano.function了点。现在,你想知道你的损失计算是否正确。你做以下。

你可以实现你的损失函数的蟒蛇/ 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是把价值和评估这些象征性的表达方式。我希望这有帮助。

+0

我的问题是当我运行拟合时,损失函数未被调用 - 或者我看不到? –

+0

你看不到它。也许在运行fit函数时有另一种调试方式,但我更喜欢我上述的方式。或者,您可以运行'train_on_batch()'并使用我的方法来调试每个批次。 –

+0

好吧..有点奇怪,没有很好的方法来做到这一点..>< –