word2vec.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535
  1. # Copyright 2015 The TensorFlow Authors. All Rights Reserved.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. # ==============================================================================
  15. """Multi-threaded word2vec mini-batched skip-gram model.
  16. Trains the model described in:
  17. (Mikolov, et. al.) Efficient Estimation of Word Representations in Vector Space
  18. ICLR 2013.
  19. http://arxiv.org/abs/1301.3781
  20. This model does traditional minibatching.
  21. The key ops used are:
  22. * placeholder for feeding in tensors for each example.
  23. * embedding_lookup for fetching rows from the embedding matrix.
  24. * sigmoid_cross_entropy_with_logits to calculate the loss.
  25. * GradientDescentOptimizer for optimizing the loss.
  26. * skipgram custom op that does input processing.
  27. """
  28. from __future__ import absolute_import
  29. from __future__ import division
  30. from __future__ import print_function
  31. import os
  32. import sys
  33. import threading
  34. import time
  35. from six.moves import xrange # pylint: disable=redefined-builtin
  36. import numpy as np
  37. import tensorflow as tf
  38. word2vec = tf.load_op_library(os.path.join(os.path.dirname(os.path.realpath(__file__)), 'word2vec_ops.so'))
  39. flags = tf.app.flags
  40. flags.DEFINE_string("save_path", None, "Directory to write the model and "
  41. "training summaries.")
  42. flags.DEFINE_string("train_data", None, "Training text file. "
  43. "E.g., unzipped file http://mattmahoney.net/dc/text8.zip.")
  44. flags.DEFINE_string(
  45. "eval_data", None, "File consisting of analogies of four tokens."
  46. "embedding 2 - embedding 1 + embedding 3 should be close "
  47. "to embedding 4."
  48. "See README.md for how to get 'questions-words.txt'.")
  49. flags.DEFINE_integer("embedding_size", 200, "The embedding dimension size.")
  50. flags.DEFINE_integer(
  51. "epochs_to_train", 15,
  52. "Number of epochs to train. Each epoch processes the training data once "
  53. "completely.")
  54. flags.DEFINE_float("learning_rate", 0.2, "Initial learning rate.")
  55. flags.DEFINE_integer("num_neg_samples", 100,
  56. "Negative samples per training example.")
  57. flags.DEFINE_integer("batch_size", 16,
  58. "Number of training examples processed per step "
  59. "(size of a minibatch).")
  60. flags.DEFINE_integer("concurrent_steps", 12,
  61. "The number of concurrent training steps.")
  62. flags.DEFINE_integer("window_size", 5,
  63. "The number of words to predict to the left and right "
  64. "of the target word.")
  65. flags.DEFINE_integer("min_count", 5,
  66. "The minimum number of word occurrences for it to be "
  67. "included in the vocabulary.")
  68. flags.DEFINE_float("subsample", 1e-3,
  69. "Subsample threshold for word occurrence. Words that appear "
  70. "with higher frequency will be randomly down-sampled. Set "
  71. "to 0 to disable.")
  72. flags.DEFINE_boolean(
  73. "interactive", False,
  74. "If true, enters an IPython interactive session to play with the trained "
  75. "model. E.g., try model.analogy(b'france', b'paris', b'russia') and "
  76. "model.nearby([b'proton', b'elephant', b'maxwell'])")
  77. flags.DEFINE_integer("statistics_interval", 5,
  78. "Print statistics every n seconds.")
  79. flags.DEFINE_integer("summary_interval", 5,
  80. "Save training summary to file every n seconds (rounded "
  81. "up to statistics interval).")
  82. flags.DEFINE_integer("checkpoint_interval", 600,
  83. "Checkpoint the model (i.e. save the parameters) every n "
  84. "seconds (rounded up to statistics interval).")
  85. FLAGS = flags.FLAGS
  86. class Options(object):
  87. """Options used by our word2vec model."""
  88. def __init__(self):
  89. # Model options.
  90. # Embedding dimension.
  91. self.emb_dim = FLAGS.embedding_size
  92. # Training options.
  93. # The training text file.
  94. self.train_data = FLAGS.train_data
  95. # Number of negative samples per example.
  96. self.num_samples = FLAGS.num_neg_samples
  97. # The initial learning rate.
  98. self.learning_rate = FLAGS.learning_rate
  99. # Number of epochs to train. After these many epochs, the learning
  100. # rate decays linearly to zero and the training stops.
  101. self.epochs_to_train = FLAGS.epochs_to_train
  102. # Concurrent training steps.
  103. self.concurrent_steps = FLAGS.concurrent_steps
  104. # Number of examples for one training step.
  105. self.batch_size = FLAGS.batch_size
  106. # The number of words to predict to the left and right of the target word.
  107. self.window_size = FLAGS.window_size
  108. # The minimum number of word occurrences for it to be included in the
  109. # vocabulary.
  110. self.min_count = FLAGS.min_count
  111. # Subsampling threshold for word occurrence.
  112. self.subsample = FLAGS.subsample
  113. # How often to print statistics.
  114. self.statistics_interval = FLAGS.statistics_interval
  115. # How often to write to the summary file (rounds up to the nearest
  116. # statistics_interval).
  117. self.summary_interval = FLAGS.summary_interval
  118. # How often to write checkpoints (rounds up to the nearest statistics
  119. # interval).
  120. self.checkpoint_interval = FLAGS.checkpoint_interval
  121. # Where to write out summaries.
  122. self.save_path = FLAGS.save_path
  123. if not os.path.exists(self.save_path):
  124. os.makedirs(self.save_path)
  125. # Eval options.
  126. # The text file for eval.
  127. self.eval_data = FLAGS.eval_data
  128. class Word2Vec(object):
  129. """Word2Vec model (Skipgram)."""
  130. def __init__(self, options, session):
  131. self._options = options
  132. self._session = session
  133. self._word2id = {}
  134. self._id2word = []
  135. self.build_graph()
  136. self.build_eval_graph()
  137. self.save_vocab()
  138. def read_analogies(self):
  139. """Reads through the analogy question file.
  140. Returns:
  141. questions: a [n, 4] numpy array containing the analogy question's
  142. word ids.
  143. questions_skipped: questions skipped due to unknown words.
  144. """
  145. questions = []
  146. questions_skipped = 0
  147. with open(self._options.eval_data, "rb") as analogy_f:
  148. for line in analogy_f:
  149. if line.startswith(b":"): # Skip comments.
  150. continue
  151. words = line.strip().lower().split(b" ")
  152. ids = [self._word2id.get(w.strip()) for w in words]
  153. if None in ids or len(ids) != 4:
  154. questions_skipped += 1
  155. else:
  156. questions.append(np.array(ids))
  157. print("Eval analogy file: ", self._options.eval_data)
  158. print("Questions: ", len(questions))
  159. print("Skipped: ", questions_skipped)
  160. self._analogy_questions = np.array(questions, dtype=np.int32)
  161. def forward(self, examples, labels):
  162. """Build the graph for the forward pass."""
  163. opts = self._options
  164. # Declare all variables we need.
  165. # Embedding: [vocab_size, emb_dim]
  166. init_width = 0.5 / opts.emb_dim
  167. emb = tf.Variable(
  168. tf.random_uniform(
  169. [opts.vocab_size, opts.emb_dim], -init_width, init_width),
  170. name="emb")
  171. self._emb = emb
  172. # Softmax weight: [vocab_size, emb_dim]. Transposed.
  173. sm_w_t = tf.Variable(
  174. tf.zeros([opts.vocab_size, opts.emb_dim]),
  175. name="sm_w_t")
  176. # Softmax bias: [vocab_size].
  177. sm_b = tf.Variable(tf.zeros([opts.vocab_size]), name="sm_b")
  178. # Global step: scalar, i.e., shape [].
  179. self.global_step = tf.Variable(0, name="global_step")
  180. # Nodes to compute the nce loss w/ candidate sampling.
  181. labels_matrix = tf.reshape(
  182. tf.cast(labels,
  183. dtype=tf.int64),
  184. [opts.batch_size, 1])
  185. # Negative sampling.
  186. sampled_ids, _, _ = (tf.nn.fixed_unigram_candidate_sampler(
  187. true_classes=labels_matrix,
  188. num_true=1,
  189. num_sampled=opts.num_samples,
  190. unique=True,
  191. range_max=opts.vocab_size,
  192. distortion=0.75,
  193. unigrams=opts.vocab_counts.tolist()))
  194. # Embeddings for examples: [batch_size, emb_dim]
  195. example_emb = tf.nn.embedding_lookup(emb, examples)
  196. # Weights for labels: [batch_size, emb_dim]
  197. true_w = tf.nn.embedding_lookup(sm_w_t, labels)
  198. # Biases for labels: [batch_size, 1]
  199. true_b = tf.nn.embedding_lookup(sm_b, labels)
  200. # Weights for sampled ids: [num_sampled, emb_dim]
  201. sampled_w = tf.nn.embedding_lookup(sm_w_t, sampled_ids)
  202. # Biases for sampled ids: [num_sampled, 1]
  203. sampled_b = tf.nn.embedding_lookup(sm_b, sampled_ids)
  204. # True logits: [batch_size, 1]
  205. true_logits = tf.reduce_sum(tf.multiply(example_emb, true_w), 1) + true_b
  206. # Sampled logits: [batch_size, num_sampled]
  207. # We replicate sampled noise labels for all examples in the batch
  208. # using the matmul.
  209. sampled_b_vec = tf.reshape(sampled_b, [opts.num_samples])
  210. sampled_logits = tf.matmul(example_emb,
  211. sampled_w,
  212. transpose_b=True) + sampled_b_vec
  213. return true_logits, sampled_logits
  214. def nce_loss(self, true_logits, sampled_logits):
  215. """Build the graph for the NCE loss."""
  216. # cross-entropy(logits, labels)
  217. opts = self._options
  218. true_xent = tf.nn.sigmoid_cross_entropy_with_logits(
  219. labels=tf.ones_like(true_logits), logits=true_logits)
  220. sampled_xent = tf.nn.sigmoid_cross_entropy_with_logits(
  221. labels=tf.zeros_like(sampled_logits), logits=sampled_logits)
  222. # NCE-loss is the sum of the true and noise (sampled words)
  223. # contributions, averaged over the batch.
  224. nce_loss_tensor = (tf.reduce_sum(true_xent) +
  225. tf.reduce_sum(sampled_xent)) / opts.batch_size
  226. return nce_loss_tensor
  227. def optimize(self, loss):
  228. """Build the graph to optimize the loss function."""
  229. # Optimizer nodes.
  230. # Linear learning rate decay.
  231. opts = self._options
  232. words_to_train = float(opts.words_per_epoch * opts.epochs_to_train)
  233. lr = opts.learning_rate * tf.maximum(
  234. 0.0001, 1.0 - tf.cast(self._words, tf.float32) / words_to_train)
  235. self._lr = lr
  236. optimizer = tf.train.GradientDescentOptimizer(lr)
  237. train = optimizer.minimize(loss,
  238. global_step=self.global_step,
  239. gate_gradients=optimizer.GATE_NONE)
  240. self._train = train
  241. def build_eval_graph(self):
  242. """Build the eval graph."""
  243. # Eval graph
  244. # Each analogy task is to predict the 4th word (d) given three
  245. # words: a, b, c. E.g., a=italy, b=rome, c=france, we should
  246. # predict d=paris.
  247. # The eval feeds three vectors of word ids for a, b, c, each of
  248. # which is of size N, where N is the number of analogies we want to
  249. # evaluate in one batch.
  250. analogy_a = tf.placeholder(dtype=tf.int32) # [N]
  251. analogy_b = tf.placeholder(dtype=tf.int32) # [N]
  252. analogy_c = tf.placeholder(dtype=tf.int32) # [N]
  253. # Normalized word embeddings of shape [vocab_size, emb_dim].
  254. nemb = tf.nn.l2_normalize(self._emb, 1)
  255. # Each row of a_emb, b_emb, c_emb is a word's embedding vector.
  256. # They all have the shape [N, emb_dim]
  257. a_emb = tf.gather(nemb, analogy_a) # a's embs
  258. b_emb = tf.gather(nemb, analogy_b) # b's embs
  259. c_emb = tf.gather(nemb, analogy_c) # c's embs
  260. # We expect that d's embedding vectors on the unit hyper-sphere is
  261. # near: c_emb + (b_emb - a_emb), which has the shape [N, emb_dim].
  262. target = c_emb + (b_emb - a_emb)
  263. # Compute cosine distance between each pair of target and vocab.
  264. # dist has shape [N, vocab_size].
  265. dist = tf.matmul(target, nemb, transpose_b=True)
  266. # For each question (row in dist), find the top 4 words.
  267. _, pred_idx = tf.nn.top_k(dist, 4)
  268. # Nodes for computing neighbors for a given word according to
  269. # their cosine distance.
  270. nearby_word = tf.placeholder(dtype=tf.int32) # word id
  271. nearby_emb = tf.gather(nemb, nearby_word)
  272. nearby_dist = tf.matmul(nearby_emb, nemb, transpose_b=True)
  273. nearby_val, nearby_idx = tf.nn.top_k(nearby_dist,
  274. min(1000, self._options.vocab_size))
  275. # Nodes in the construct graph which are used by training and
  276. # evaluation to run/feed/fetch.
  277. self._analogy_a = analogy_a
  278. self._analogy_b = analogy_b
  279. self._analogy_c = analogy_c
  280. self._analogy_pred_idx = pred_idx
  281. self._nearby_word = nearby_word
  282. self._nearby_val = nearby_val
  283. self._nearby_idx = nearby_idx
  284. def build_graph(self):
  285. """Build the graph for the full model."""
  286. opts = self._options
  287. # The training data. A text file.
  288. (words, counts, words_per_epoch, self._epoch, self._words, examples,
  289. labels) = word2vec.skipgram_word2vec(filename=opts.train_data,
  290. batch_size=opts.batch_size,
  291. window_size=opts.window_size,
  292. min_count=opts.min_count,
  293. subsample=opts.subsample)
  294. (opts.vocab_words, opts.vocab_counts,
  295. opts.words_per_epoch) = self._session.run([words, counts, words_per_epoch])
  296. opts.vocab_size = len(opts.vocab_words)
  297. print("Data file: ", opts.train_data)
  298. print("Vocab size: ", opts.vocab_size - 1, " + UNK")
  299. print("Words per epoch: ", opts.words_per_epoch)
  300. self._examples = examples
  301. self._labels = labels
  302. self._id2word = opts.vocab_words
  303. for i, w in enumerate(self._id2word):
  304. self._word2id[w] = i
  305. true_logits, sampled_logits = self.forward(examples, labels)
  306. loss = self.nce_loss(true_logits, sampled_logits)
  307. tf.summary.scalar("NCE loss", loss)
  308. self._loss = loss
  309. self.optimize(loss)
  310. # Properly initialize all variables.
  311. tf.global_variables_initializer().run()
  312. self.saver = tf.train.Saver()
  313. def save_vocab(self):
  314. """Save the vocabulary to a file so the model can be reloaded."""
  315. opts = self._options
  316. with open(os.path.join(opts.save_path, "vocab.txt"), "w") as f:
  317. for i in xrange(opts.vocab_size):
  318. vocab_word = tf.compat.as_text(opts.vocab_words[i]).encode("utf-8")
  319. f.write("%s %d\n" % (vocab_word,
  320. opts.vocab_counts[i]))
  321. def _train_thread_body(self):
  322. initial_epoch, = self._session.run([self._epoch])
  323. while True:
  324. _, epoch = self._session.run([self._train, self._epoch])
  325. if epoch != initial_epoch:
  326. break
  327. def train(self):
  328. """Train the model."""
  329. opts = self._options
  330. initial_epoch, initial_words = self._session.run([self._epoch, self._words])
  331. summary_op = tf.summary.merge_all()
  332. summary_writer = tf.summary.FileWriter(opts.save_path, self._session.graph)
  333. workers = []
  334. for _ in xrange(opts.concurrent_steps):
  335. t = threading.Thread(target=self._train_thread_body)
  336. t.start()
  337. workers.append(t)
  338. last_words, last_time, last_summary_time = initial_words, time.time(), 0
  339. last_checkpoint_time = 0
  340. while True:
  341. time.sleep(opts.statistics_interval) # Reports our progress once a while.
  342. (epoch, step, loss, words, lr) = self._session.run(
  343. [self._epoch, self.global_step, self._loss, self._words, self._lr])
  344. now = time.time()
  345. last_words, last_time, rate = words, now, (words - last_words) / (
  346. now - last_time)
  347. print("Epoch %4d Step %8d: lr = %5.3f loss = %6.2f words/sec = %8.0f\r" %
  348. (epoch, step, lr, loss, rate), end="")
  349. sys.stdout.flush()
  350. if now - last_summary_time > opts.summary_interval:
  351. summary_str = self._session.run(summary_op)
  352. summary_writer.add_summary(summary_str, step)
  353. last_summary_time = now
  354. if now - last_checkpoint_time > opts.checkpoint_interval:
  355. self.saver.save(self._session,
  356. os.path.join(opts.save_path, "model.ckpt"),
  357. global_step=step.astype(int))
  358. last_checkpoint_time = now
  359. if epoch != initial_epoch:
  360. break
  361. for t in workers:
  362. t.join()
  363. return epoch
  364. def _predict(self, analogy):
  365. """Predict the top 4 answers for analogy questions."""
  366. idx, = self._session.run([self._analogy_pred_idx], {
  367. self._analogy_a: analogy[:, 0],
  368. self._analogy_b: analogy[:, 1],
  369. self._analogy_c: analogy[:, 2]
  370. })
  371. return idx
  372. def eval(self):
  373. """Evaluate analogy questions and reports accuracy."""
  374. # How many questions we get right at precision@1.
  375. correct = 0
  376. try:
  377. total = self._analogy_questions.shape[0]
  378. except AttributeError as e:
  379. raise AttributeError("Need to read analogy questions.")
  380. start = 0
  381. while start < total:
  382. limit = start + 2500
  383. sub = self._analogy_questions[start:limit, :]
  384. idx = self._predict(sub)
  385. start = limit
  386. for question in xrange(sub.shape[0]):
  387. for j in xrange(4):
  388. if idx[question, j] == sub[question, 3]:
  389. # Bingo! We predicted correctly. E.g., [italy, rome, france, paris].
  390. correct += 1
  391. break
  392. elif idx[question, j] in sub[question, :3]:
  393. # We need to skip words already in the question.
  394. continue
  395. else:
  396. # The correct label is not the precision@1
  397. break
  398. print()
  399. print("Eval %4d/%d accuracy = %4.1f%%" % (correct, total,
  400. correct * 100.0 / total))
  401. def analogy(self, w0, w1, w2):
  402. """Predict word w3 as in w0:w1 vs w2:w3."""
  403. wid = np.array([[self._word2id.get(w, 0) for w in [w0, w1, w2]]])
  404. idx = self._predict(wid)
  405. for c in [self._id2word[i] for i in idx[0, :]]:
  406. if c not in [w0, w1, w2]:
  407. print(c)
  408. break
  409. print("unknown")
  410. def nearby(self, words, num=20):
  411. """Prints out nearby words given a list of words."""
  412. ids = np.array([self._word2id.get(x, 0) for x in words])
  413. vals, idx = self._session.run(
  414. [self._nearby_val, self._nearby_idx], {self._nearby_word: ids})
  415. for i in xrange(len(words)):
  416. print("\n%s\n=====================================" % (words[i]))
  417. for (neighbor, distance) in zip(idx[i, :num], vals[i, :num]):
  418. print("%-20s %6.4f" % (self._id2word[neighbor], distance))
  419. def _start_shell(local_ns=None):
  420. # An interactive shell is useful for debugging/development.
  421. import IPython
  422. user_ns = {}
  423. if local_ns:
  424. user_ns.update(local_ns)
  425. user_ns.update(globals())
  426. IPython.start_ipython(argv=[], user_ns=user_ns)
  427. def main(_):
  428. """Train a word2vec model."""
  429. if not FLAGS.train_data or not FLAGS.eval_data or not FLAGS.save_path:
  430. print("--train_data --eval_data and --save_path must be specified.")
  431. sys.exit(1)
  432. opts = Options()
  433. with tf.Graph().as_default(), tf.Session() as session:
  434. with tf.device("/cpu:0"):
  435. model = Word2Vec(opts, session)
  436. model.read_analogies() # Read analogy questions
  437. for _ in xrange(opts.epochs_to_train):
  438. model.train() # Process one epoch
  439. model.eval() # Eval analogies.
  440. # Perform a final save.
  441. model.saver.save(session,
  442. os.path.join(opts.save_path, "model.ckpt"),
  443. global_step=model.global_step)
  444. if FLAGS.interactive:
  445. # E.g.,
  446. # [0]: model.analogy(b'france', b'paris', b'russia')
  447. # [1]: model.nearby([b'proton', b'elephant', b'maxwell'])
  448. _start_shell(locals())
  449. if __name__ == "__main__":
  450. tf.app.run()