2017-03-13 71 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

好吧..有點奇怪,沒有很好的方法來做到這一點..>< –