簡體   English   中英

如何在 Keras 中調試自定義損失函數?

[英]How to debug custom loss function in Keras?

我用參數創建了自定義損失函數。

def w_categorical_crossentropy(weights):
  def loss(y_true, y_pred):
  print(weights)
  print("----")
  print(weights.shape)
  final_mask = K.zeros_like(y_pred[:, 0])
  y_pred_max = K.max(y_pred, axis=1)
  y_pred_max = K.reshape(y_pred_max, (K.shape(y_pred)[0], 1))
  y_pred_max_mat = K.cast(K.equal(y_pred, y_pred_max), K.floatx())
  return K.categorical_crossentropy(y_pred, y_true)
return loss

現在,我需要控制權重參數值,但打印功能無法正常工作。 有沒有辦法打印權重值?

我有時做的(肯定不是最好的解決方案,也不總是可能的)只是用 np 替換 K 后端並用一些簡單的數據對其進行測試。 這是一個例子

原始 Keras 功能:

def loss(y_true, y_pred):
    means = K.reshape(y_pred[:, 0], (-1, 1))
    stds = K.reshape(y_pred[:, 1], (-1, 1))
    var = K.square(stds)
    denom = K.sqrt(2 * np.pi * var)
    prob_num = - K.square(y_true - means) / (2 * var)
    prob = prob_num - denom
    r = K.exp(prob - old_prediction)
    return -K.mean(K.minimum(r * advantage, K.clip(r, min_value=1 - self.LOSS_CLIPPING, max_value=1 + self.LOSS_CLIPPING) * advantage))

測試功能:

def loss(y_true, y_pred):
    means = np.reshape(y_pred[:, 0], (-1, 1))
    stds = np.reshape(y_pred[:, 1], (-1, 1))
    var = np.square(stds)
    print(var.shape)
    denom = np.sqrt(2 * np.pi * var)
    print(denom.shape)
    prob_num = - np.square(y_true - means) / (2 * var)
    prob = prob_num - denom
    r = np.exp(prob - old_prediction)
    print(r.shape)
    cliped = np.minimum(r * advantage, np.clip(r, a_min=1 - LOSS_CLIPPING, a_max=1 + LOSS_CLIPPING) * advantage)
    print(cliped.shape)
    return -np.mean(cliped)

測試它:

LOSS_CLIPPING = 0.2
y_pred = np.array([[2,1], [1, 1], [5, 1]])
y_true = np.array([[1], [3], [2]])
old_prediction = np.array([[-2], [-5], [-6]])
advantage = np.array([[ 0.51467506],[-0.64960159],[-0.53304715]])
loss(y_true, y_pred)

以上運行后,結果:

(3, 1)
(3, 1)
(3, 1)
(3, 1)
0.43409555193679816

您可以使用tf.print來調試自定義丟失函數。 必須在圖表中包含tf.print才能實際打印某些內容。 根據文檔,您可以使用tf.control_dependencies執行此tf.control_dependencies

def w_categorical_crossentropy(weights):
  def loss(y_true, y_pred):
    print_op = tf.print("weights: ", weights, weights.shape)
    final_mask = K.zeros_like(y_pred[:, 0])
    y_pred_max = K.max(y_pred, axis=1)
    y_pred_max = K.reshape(y_pred_max, (K.shape(y_pred)[0], 1))
    y_pred_max_mat = K.cast(K.equal(y_pred, y_pred_max), K.floatx())
    with tf.control_dependencies([print_op]):
      return K.categorical_crossentropy(y_pred, y_true)
  return loss

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM