簡體   English   中英

如何在 Tensorflow Keras 中使用 tf.nn.sampled_softmax_loss?

[英]How to use tf.nn.sampled_softmax_loss with Tensorflow Keras?

我一直在尋找一種對我的一個模型使用采樣 softmax tf.nn.sampled_softmax_loss()的方法。 我找不到任何可以幫助我了解如何實施它的帖子。

如果有人用 Keras 架構實現了它,請告訴我如何在 keras 中使用它?

現在對於我可以使用的其他損失,

model.compile(loss=tf.keras.losses.CategoricalCrossentropy())

但我不能以這種方式使用 tf.nn.sampled_softmax_loss model.compile(loss=tf.nn.sampled_softmax_loss())

我試過使用model.compile(loss=tf.nn.sampled_softmax_loss())但它返回錯誤,我認為這是正確的,因為它從最后一層獲取權重和偏差來計算我不知道如何實現的損失在凱拉斯。

sampled_softmax_loss() 計算並返回采樣的 softmax 訓練損失。

這是在大量類別上訓練 softmax 分類器的更快方法。

此操作僅用於培訓。 它通常低估了完整的 softmax 損失。

一個常見的用例是使用這種方法進行訓練,並計算完整的 softmax 損失以進行評估或推理。 在這種情況下,您必須設置partition_strategy="div"以使兩個損失保持一致,如下例所示:

if mode == "train":
  loss = tf.nn.sampled_softmax_loss(
      weights=weights,
      biases=biases,
      labels=labels,
      inputs=inputs,
      ...,
      partition_strategy="div")
elif mode == "eval":
  logits = tf.matmul(inputs, tf.transpose(weights))
  logits = tf.nn.bias_add(logits, biases)
  labels_one_hot = tf.one_hot(labels, n_classes)
  loss = tf.nn.softmax_cross_entropy_with_logits(
      labels=labels_one_hot,
      logits=logits)  

像 CategoricalCrossentropy() 這樣的常規損失函數使用它的默認值,即使您不傳遞任何參數,它也會根據其默認值計算損失。

sampled_softmax_loss 的關鍵是傳遞正確的weightbiasinputlabel形狀。
傳遞給sampled_softmax的權重形狀和一般情況不太一樣。
例如, logits = xw + b ,像這樣調用 sampled_softmax :

sampled_softmax(weight=tf.transpose(w), bias=b, inputs=x)
NOT sampled_softmax(weight=w, bias=b, inputs=logits) !!

此外,標簽不是單熱表示。 如果您的標簽是單熱表示,請傳遞labels=tf.reshape(tf.argmax(labels_one_hot, 1), [-1,1])

暫無
暫無

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

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