當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Python tf.keras.losses.CategoricalHinge用法及代碼示例

計算 y_truey_pred 之間的分類鉸鏈損失。

繼承自:Loss

用法

tf.keras.losses.CategoricalHinge(
    reduction=losses_utils.ReductionV2.AUTO, name='categorical_hinge'
)

參數

  • reduction 類型tf.keras.losses.Reduction適用於損失。默認值為AUTO.AUTO表示縮減選項將由使用上下文確定。對於幾乎所有情況,這默認為SUM_OVER_BATCH_SIZE.當與tf.distribute.Strategy,在內置訓練循環之外,例如tf.keras compilefit, 使用AUTO或者SUM_OVER_BATCH_SIZE將引發錯誤。請參閱此自定義訓練教程更多細節。
  • name 實例的可選名稱。默認為'categorical_hinge'。

loss = maximum(neg - pos + 1, 0) 其中neg=maximum((1-y_true)*y_pred) and pos=sum(y_true*y_pred)

單機使用:

y_true = [[0, 1], [0, 0]]
y_pred = [[0.6, 0.4], [0.4, 0.6]]
# Using 'auto'/'sum_over_batch_size' reduction type.
h = tf.keras.losses.CategoricalHinge()
h(y_true, y_pred).numpy()
1.4
# Calling with 'sample_weight'.
h(y_true, y_pred, sample_weight=[1, 0]).numpy()
0.6
# Using 'sum' reduction type.
h = tf.keras.losses.CategoricalHinge(
    reduction=tf.keras.losses.Reduction.SUM)
h(y_true, y_pred).numpy()
2.8
# Using 'none' reduction type.
h = tf.keras.losses.CategoricalHinge(
    reduction=tf.keras.losses.Reduction.NONE)
h(y_true, y_pred).numpy()
array([1.2, 1.6], dtype=float32)

compile() API 的用法:

model.compile(optimizer='sgd', loss=tf.keras.losses.CategoricalHinge())

相關用法


注:本文由純淨天空篩選整理自tensorflow.org大神的英文原創作品 tf.keras.losses.CategoricalHinge。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。