2017-06-28 69 views
1

我新的神經網絡和keras時遇到了問題寫這個自定義損失函數:自定義損失函數與TensorFlow後端的圖像

loss function

我使用TensorFlow作爲後端。我看到其他的例子並以這種方式編寫的損失函數:

from keras import backend as K 
def depth_loss_func(pred_depth,actual_depth): 
    n = pred_depth.shape[0] 
    di = K.log(pred_depth)-K.log(actual_depth) 
    di_sq = K.square(di) 
    sum_d = K.sum(di) 
    sum_d_sq = K.sum(di_sq) 
    loss = ((1/n)*sum_d_sq)-((1/(n*n))*sum_d*sum_d) # getting an error in this step 
    return loss 

我得到的錯誤是: TypeError: unsupported operand type(s) for /: 'int' and 'Dimension'

而且我不知道如何把學習率的損失函數。謝謝你的幫助。

+0

不要你混合'pred_depth'和'actual_depth'每其他? – Dmitry

回答

3

而不是使用「N」,這似乎不是在我看來,最優雅的方式,嘗試使用K.mean功能:

di = K.log(pred_depth)-K.log(actual_depth) 

di_mean = K.mean(di) 
sq_mean = K.mean(K.square(di)) 

loss = (sq_mean - (lamb*di_mean*di_mean)) # getting an error in this step 
2

張量的形狀是未知的,直到您在圖形執行期間用輸入提供丟失函數爲止。爲了動態計算執行時的形狀,您可以使用K.shape()

更改爲第一行:

n = K.shape(pred_depth)[0] 

關於學習率,只是把它作爲另一個參數。如果它是動態的,您可以通過model.optimizer.lr.get_value()訪問它。