12

I am new to tensorflow and to word2vec. I just studied the word2vec_basic.py which trains the model using Skip-Gram algorithm. Now I want to train using CBOW algorithm. Is it true that this can be achieved if I simply reverse the train_inputs and train_labels?

2
  • link FYI, but it's written in Chinese.
    – idailylife
    Oct 10, 2016 at 4:02
  • 1
    @idailylife haha thanks, I am Chinese
    – gladys0313
    Nov 3, 2016 at 9:57

3 Answers 3

14

I think CBOW model can not simply be achieved by flipping the train_inputs and the train_labels in Skip-gram because CBOW model architecture uses the sum of the vectors of surrounding words as one single instance for the classifier to predict. E.g., you should use [the, brown] together to predict quick rather than using the to predict quick.

enter image description here

To implement CBOW, you'll have to write a new generate_batch generator function and sum up the vectors of surrounding words before applying logistic regression. I wrote an example you can refer to: https://github.com/wangz10/tensorflow-playground/blob/master/word2vec.py#L105

2
  • 1
    @Zichen Wang Why would you sum in word2vec._init_graph() (lines 216-217) instead of in generate_batch_cbow() (line 132)? You would be passing a much smaller matrix and you would avoid using a for loop/extra lookups within tf.
    – Rik
    Oct 12, 2016 at 16:32
  • 1
    @Zichen Wang I think it is slightly better to do lookup and sum in generate_batch then pass the sum of embeddings rather than all indices, but I haven't tried it
    – Rik
    Oct 13, 2016 at 18:47
10

For CBOW, You need to change only few parts of the code word2vec_basic.py. Overall the training structure and method are the same.

Which parts should I change in word2vec_basic.py?

1) The way it generates training data pairs. Because in CBOW, you are predicting the center word, not the context words.

The new version for generate_batch will be

def generate_batch(batch_size, bag_window):
  global data_index
  span = 2 * bag_window + 1 # [ bag_window target bag_window ]
  batch = np.ndarray(shape=(batch_size, span - 1), dtype=np.int32)
  labels = np.ndarray(shape=(batch_size, 1), dtype=np.int32)  
  buffer = collections.deque(maxlen=span)
  for _ in range(span):
    buffer.append(data[data_index])
    data_index = (data_index + 1) % len(data)
  for i in range(batch_size):
    # just for testing
    buffer_list = list(buffer)
    labels[i, 0] = buffer_list.pop(bag_window)
    batch[i] = buffer_list
    # iterate to the next buffer
    buffer.append(data[data_index])
    data_index = (data_index + 1) % len(data)
  return batch, labels

Then new training data for CBOW would be

data: ['anarchism', 'originated', 'as', 'a', 'term', 'of', 'abuse', 'first', 'used', 'against', 'early', 'working', 'class', 'radicals', 'including', 'the']

#with bag_window = 1:
    batch: [['anarchism', 'as'], ['originated', 'a'], ['as', 'term'], ['a', 'of']]
    labels: ['originated', 'as', 'a', 'term']

compared to Skip-gram's data

#with num_skips = 2 and skip_window = 1:
    batch: ['originated', 'originated', 'as', 'as', 'a', 'a', 'term', 'term', 'of', 'of', 'abuse', 'abuse', 'first', 'first', 'used', 'used']
    labels: ['as', 'anarchism', 'originated', 'a', 'term', 'as', 'a', 'of', 'term', 'abuse', 'of', 'first', 'used', 'abuse', 'against', 'first']

2) Therefore you also need to change the variable shape

train_dataset = tf.placeholder(tf.int32, shape=[batch_size])

to

train_dataset = tf.placeholder(tf.int32, shape=[batch_size, bag_window * 2])

3) loss function

 loss = tf.reduce_mean(tf.nn.sampled_softmax_loss(
  weights = softmax_weights, biases = softmax_biases, inputs = tf.reduce_sum(embed, 1), labels = train_labels, num_sampled= num_sampled, num_classes= vocabulary_size))

Notice inputs = tf.reduce_sum(embed, 1) as Zichen Wang mentioned it.

This is it!

3
  • "Notice inputs = tf.reduce_sum(embed, 1) as Zichen Wang mentioned it." That would take the average across the whole batch, you need to take the average across the context window. Jun 7, 2018 at 16:54
  • @SantoshGupta7 No. Axis 1 is a window size, not a batch size.
    – aerin
    Dec 16, 2018 at 17:53
  • It's been a while, so I can't comment on this with confidence, but I remember my testing had found that the average was being taken across the batch, so I had to change it. Dec 16, 2018 at 20:56
6

Basically, yes:

for the given text the quick brown fox jumped over the lazy dog:, the CBOW instances for window size 1 would be

([the, brown], quick), ([quick, fox], brown), ([brown, jumped], fox), ...
1
  • 3
    And then the input-output pair should be: (the, quick), (brown, quick), (quick, brown),(fox, brown),..... right?
    – gladys0313
    May 24, 2016 at 6:55

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.