2016-06-07 88 views
7

我試圖遵循tensorflow的udacity教程在那裏我碰到下面兩行來到一個字嵌入模型:Tensorflow負採樣

# Look up embeddings for inputs. 
    embed = tf.nn.embedding_lookup(embeddings, train_dataset) 
    # Compute the softmax loss, using a sample of the negative labels each time. 
    loss = tf.reduce_mean(tf.nn.sampled_softmax_loss(softmax_weights, softmax_biases, 
         embed, train_labels, num_sampled, vocabulary_size)) 

現在我明白了第二個說法是,用於採樣負標籤。但問題是它如何知道負面標籤是什麼?我所提供的第二個功能是當前輸入及其相應的標籤以及我希望(負面)取樣的標籤數量。從輸入集本身取樣的風險是否不存在?

這是完整的例子:https://github.com/tensorflow/tensorflow/blob/master/tensorflow/examples/udacity/5_word2vec.ipynb

回答

8

你可以找到tf.nn.sampled_softmax_loss()here的文檔。 對TensorFlow here (pdf)提供的候選採樣甚至有很好的解釋。


它怎麼知道的負面標籤是什麼?

TensorFlow將隨機選擇所有可能的類(爲您,所有可能的單詞)中的負類。

是否存在從輸入集本身取樣的風險?

當您想計算真實標籤的softmax概率時,計算:logits[true_label]/sum(logits[negative_sampled_labels]。由於類的數量巨大(詞彙大小),因此將true_label作爲負標籤採樣的可能性非常小。
無論如何,我認爲TensorFlow在隨機抽樣時完全消除了這種可能性。 (編輯:@Alex證實TensorFlow默認完成了這些)

+5

「我認爲TensorFlow在隨機抽樣時完全消除了這種可能性。」正確!有一個標誌:'remove_accidental_hits':一個布爾。是否刪除樣本類別等於目標類別之一的「意外命中」。默認值爲True.' – Alex

+0

有沒有人知道提供取樣權重的方法? –

1

Candidate sampling解釋採樣損失函數是如何計算的:

  • 計算損失函數的子集中的所有訓練樣本大號Ç,其中C = T×S,T是目標類別中的樣本,並且S是所有類別中隨機選擇的樣本。

您提供的代碼使用tf.nn.embedding_lookup來獲取輸入[batch_size,dim] embed

然後,它使用tf.nn.sampled_softmax_loss獲得所採樣的損失函數:

  • softmax_weights:形狀[num_classes,暗淡]的張量。
  • softmax_biases:形狀的張量[num_classes]。班級偏見。
  • 嵌入:形狀的張量[batch_size,dim]。
  • train_labels:形狀的張量[batch_size,1]。目標分類T
  • num_sampled:一個int。每批隨機抽樣的班級數量。麻木的S
  • vocabulary_size:可能的類的數量。
  • sampled_values:默認log_uniform_candidate_sampler

對於一個批次中,目標樣品只是train_labelsŤ)。它從embed隨機選擇num_sampled樣本(S)爲負樣本。

它將從embed統一採樣softmax_wiehgt和softmax_bias。由於embed是嵌入[train_dataset](形狀[batch_size,embedding_size]),如果嵌入[train_dataset [i]]包含train_labels [i],它可能會被選中,那麼它不是負面標籤。

根據Candidate sampling第2頁,有不同的類型。對於NCE和負抽樣,NEG = S,其可能包含部分T;對於採樣邏輯,採樣softmax,NEG = S-T明確刪除T

的確,它可能是從train_set中抽樣的一個機會。