word2vec_optimized.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440
  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 unbatched 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 true SGD (i.e. no minibatching). To do this efficiently, custom
  21. ops are used to sequentially process data within a 'batch'.
  22. The key ops used are:
  23. * skipgram custom op that does input processing.
  24. * neg_train custom op that efficiently calculates and applies the gradient using
  25. true SGD.
  26. """
  27. from __future__ import absolute_import
  28. from __future__ import division
  29. from __future__ import print_function
  30. import os
  31. import sys
  32. import threading
  33. import time
  34. from six.moves import xrange # pylint: disable=redefined-builtin
  35. import numpy as np
  36. import tensorflow as tf
  37. word2vec = tf.load_op_library(os.path.join(os.path.dirname(os.path.realpath(__file__)), 'word2vec_ops.so'))
  38. flags = tf.app.flags
  39. flags.DEFINE_string("save_path", None, "Directory to write the model.")
  40. flags.DEFINE_string(
  41. "train_data", None,
  42. "Training data. E.g., unzipped file http://mattmahoney.net/dc/text8.zip.")
  43. flags.DEFINE_string(
  44. "eval_data", None, "Analogy questions. "
  45. "See README.md for how to get 'questions-words.txt'.")
  46. flags.DEFINE_integer("embedding_size", 200, "The embedding dimension size.")
  47. flags.DEFINE_integer(
  48. "epochs_to_train", 15,
  49. "Number of epochs to train. Each epoch processes the training data once "
  50. "completely.")
  51. flags.DEFINE_float("learning_rate", 0.025, "Initial learning rate.")
  52. flags.DEFINE_integer("num_neg_samples", 25,
  53. "Negative samples per training example.")
  54. flags.DEFINE_integer("batch_size", 500,
  55. "Numbers of training examples each step processes "
  56. "(no minibatching).")
  57. flags.DEFINE_integer("concurrent_steps", 12,
  58. "The number of concurrent training steps.")
  59. flags.DEFINE_integer("window_size", 5,
  60. "The number of words to predict to the left and right "
  61. "of the target word.")
  62. flags.DEFINE_integer("min_count", 5,
  63. "The minimum number of word occurrences for it to be "
  64. "included in the vocabulary.")
  65. flags.DEFINE_float("subsample", 1e-3,
  66. "Subsample threshold for word occurrence. Words that appear "
  67. "with higher frequency will be randomly down-sampled. Set "
  68. "to 0 to disable.")
  69. flags.DEFINE_boolean(
  70. "interactive", False,
  71. "If true, enters an IPython interactive session to play with the trained "
  72. "model. E.g., try model.analogy(b'france', b'paris', b'russia') and "
  73. "model.nearby([b'proton', b'elephant', b'maxwell'])")
  74. FLAGS = flags.FLAGS
  75. class Options(object):
  76. """Options used by our word2vec model."""
  77. def __init__(self):
  78. # Model options.
  79. # Embedding dimension.
  80. self.emb_dim = FLAGS.embedding_size
  81. # Training options.
  82. # The training text file.
  83. self.train_data = FLAGS.train_data
  84. # Number of negative samples per example.
  85. self.num_samples = FLAGS.num_neg_samples
  86. # The initial learning rate.
  87. self.learning_rate = FLAGS.learning_rate
  88. # Number of epochs to train. After these many epochs, the learning
  89. # rate decays linearly to zero and the training stops.
  90. self.epochs_to_train = FLAGS.epochs_to_train
  91. # Concurrent training steps.
  92. self.concurrent_steps = FLAGS.concurrent_steps
  93. # Number of examples for one training step.
  94. self.batch_size = FLAGS.batch_size
  95. # The number of words to predict to the left and right of the target word.
  96. self.window_size = FLAGS.window_size
  97. # The minimum number of word occurrences for it to be included in the
  98. # vocabulary.
  99. self.min_count = FLAGS.min_count
  100. # Subsampling threshold for word occurrence.
  101. self.subsample = FLAGS.subsample
  102. # Where to write out summaries.
  103. self.save_path = FLAGS.save_path
  104. if not os.path.exists(self.save_path):
  105. os.makedirs(self.save_path)
  106. # Eval options.
  107. # The text file for eval.
  108. self.eval_data = FLAGS.eval_data
  109. class Word2Vec(object):
  110. """Word2Vec model (Skipgram)."""
  111. def __init__(self, options, session):
  112. self._options = options
  113. self._session = session
  114. self._word2id = {}
  115. self._id2word = []
  116. self.build_graph()
  117. self.build_eval_graph()
  118. self.save_vocab()
  119. def read_analogies(self):
  120. """Reads through the analogy question file.
  121. Returns:
  122. questions: a [n, 4] numpy array containing the analogy question's
  123. word ids.
  124. questions_skipped: questions skipped due to unknown words.
  125. """
  126. questions = []
  127. questions_skipped = 0
  128. with open(self._options.eval_data, "rb") as analogy_f:
  129. for line in analogy_f:
  130. if line.startswith(b":"): # Skip comments.
  131. continue
  132. words = line.strip().lower().split(b" ")
  133. ids = [self._word2id.get(w.strip()) for w in words]
  134. if None in ids or len(ids) != 4:
  135. questions_skipped += 1
  136. else:
  137. questions.append(np.array(ids))
  138. print("Eval analogy file: ", self._options.eval_data)
  139. print("Questions: ", len(questions))
  140. print("Skipped: ", questions_skipped)
  141. self._analogy_questions = np.array(questions, dtype=np.int32)
  142. def build_graph(self):
  143. """Build the model graph."""
  144. opts = self._options
  145. # The training data. A text file.
  146. (words, counts, words_per_epoch, current_epoch, total_words_processed,
  147. examples, labels) = word2vec.skipgram_word2vec(filename=opts.train_data,
  148. batch_size=opts.batch_size,
  149. window_size=opts.window_size,
  150. min_count=opts.min_count,
  151. subsample=opts.subsample)
  152. (opts.vocab_words, opts.vocab_counts,
  153. opts.words_per_epoch) = self._session.run([words, counts, words_per_epoch])
  154. opts.vocab_size = len(opts.vocab_words)
  155. print("Data file: ", opts.train_data)
  156. print("Vocab size: ", opts.vocab_size - 1, " + UNK")
  157. print("Words per epoch: ", opts.words_per_epoch)
  158. self._id2word = opts.vocab_words
  159. for i, w in enumerate(self._id2word):
  160. self._word2id[w] = i
  161. # Declare all variables we need.
  162. # Input words embedding: [vocab_size, emb_dim]
  163. w_in = tf.Variable(
  164. tf.random_uniform(
  165. [opts.vocab_size,
  166. opts.emb_dim], -0.5 / opts.emb_dim, 0.5 / opts.emb_dim),
  167. name="w_in")
  168. # Global step: scalar, i.e., shape [].
  169. w_out = tf.Variable(tf.zeros([opts.vocab_size, opts.emb_dim]), name="w_out")
  170. # Global step: []
  171. global_step = tf.Variable(0, name="global_step")
  172. # Linear learning rate decay.
  173. words_to_train = float(opts.words_per_epoch * opts.epochs_to_train)
  174. lr = opts.learning_rate * tf.maximum(
  175. 0.0001,
  176. 1.0 - tf.cast(total_words_processed, tf.float32) / words_to_train)
  177. # Training nodes.
  178. inc = global_step.assign_add(1)
  179. with tf.control_dependencies([inc]):
  180. train = word2vec.neg_train_word2vec(w_in,
  181. w_out,
  182. examples,
  183. labels,
  184. lr,
  185. vocab_count=opts.vocab_counts.tolist(),
  186. num_negative_samples=opts.num_samples)
  187. self._w_in = w_in
  188. self._examples = examples
  189. self._labels = labels
  190. self._lr = lr
  191. self._train = train
  192. self.global_step = global_step
  193. self._epoch = current_epoch
  194. self._words = total_words_processed
  195. def save_vocab(self):
  196. """Save the vocabulary to a file so the model can be reloaded."""
  197. opts = self._options
  198. with open(os.path.join(opts.save_path, "vocab.txt"), "w") as f:
  199. for i in xrange(opts.vocab_size):
  200. vocab_word = tf.compat.as_text(opts.vocab_words[i]).encode("utf-8")
  201. f.write("%s %d\n" % (vocab_word,
  202. opts.vocab_counts[i]))
  203. def build_eval_graph(self):
  204. """Build the evaluation graph."""
  205. # Eval graph
  206. opts = self._options
  207. # Each analogy task is to predict the 4th word (d) given three
  208. # words: a, b, c. E.g., a=italy, b=rome, c=france, we should
  209. # predict d=paris.
  210. # The eval feeds three vectors of word ids for a, b, c, each of
  211. # which is of size N, where N is the number of analogies we want to
  212. # evaluate in one batch.
  213. analogy_a = tf.placeholder(dtype=tf.int32) # [N]
  214. analogy_b = tf.placeholder(dtype=tf.int32) # [N]
  215. analogy_c = tf.placeholder(dtype=tf.int32) # [N]
  216. # Normalized word embeddings of shape [vocab_size, emb_dim].
  217. nemb = tf.nn.l2_normalize(self._w_in, 1)
  218. # Each row of a_emb, b_emb, c_emb is a word's embedding vector.
  219. # They all have the shape [N, emb_dim]
  220. a_emb = tf.gather(nemb, analogy_a) # a's embs
  221. b_emb = tf.gather(nemb, analogy_b) # b's embs
  222. c_emb = tf.gather(nemb, analogy_c) # c's embs
  223. # We expect that d's embedding vectors on the unit hyper-sphere is
  224. # near: c_emb + (b_emb - a_emb), which has the shape [N, emb_dim].
  225. target = c_emb + (b_emb - a_emb)
  226. # Compute cosine distance between each pair of target and vocab.
  227. # dist has shape [N, vocab_size].
  228. dist = tf.matmul(target, nemb, transpose_b=True)
  229. # For each question (row in dist), find the top 4 words.
  230. _, pred_idx = tf.nn.top_k(dist, 4)
  231. # Nodes for computing neighbors for a given word according to
  232. # their cosine distance.
  233. nearby_word = tf.placeholder(dtype=tf.int32) # word id
  234. nearby_emb = tf.gather(nemb, nearby_word)
  235. nearby_dist = tf.matmul(nearby_emb, nemb, transpose_b=True)
  236. nearby_val, nearby_idx = tf.nn.top_k(nearby_dist,
  237. min(1000, opts.vocab_size))
  238. # Nodes in the construct graph which are used by training and
  239. # evaluation to run/feed/fetch.
  240. self._analogy_a = analogy_a
  241. self._analogy_b = analogy_b
  242. self._analogy_c = analogy_c
  243. self._analogy_pred_idx = pred_idx
  244. self._nearby_word = nearby_word
  245. self._nearby_val = nearby_val
  246. self._nearby_idx = nearby_idx
  247. # Properly initialize all variables.
  248. tf.global_variables_initializer().run()
  249. self.saver = tf.train.Saver()
  250. def _train_thread_body(self):
  251. initial_epoch, = self._session.run([self._epoch])
  252. while True:
  253. _, epoch = self._session.run([self._train, self._epoch])
  254. if epoch != initial_epoch:
  255. break
  256. def train(self):
  257. """Train the model."""
  258. opts = self._options
  259. initial_epoch, initial_words = self._session.run([self._epoch, self._words])
  260. workers = []
  261. for _ in xrange(opts.concurrent_steps):
  262. t = threading.Thread(target=self._train_thread_body)
  263. t.start()
  264. workers.append(t)
  265. last_words, last_time = initial_words, time.time()
  266. while True:
  267. time.sleep(5) # Reports our progress once a while.
  268. (epoch, step, words, lr) = self._session.run(
  269. [self._epoch, self.global_step, self._words, self._lr])
  270. now = time.time()
  271. last_words, last_time, rate = words, now, (words - last_words) / (
  272. now - last_time)
  273. print("Epoch %4d Step %8d: lr = %5.3f words/sec = %8.0f\r" % (epoch, step,
  274. lr, rate),
  275. end="")
  276. sys.stdout.flush()
  277. if epoch != initial_epoch:
  278. break
  279. for t in workers:
  280. t.join()
  281. def _predict(self, analogy):
  282. """Predict the top 4 answers for analogy questions."""
  283. idx, = self._session.run([self._analogy_pred_idx], {
  284. self._analogy_a: analogy[:, 0],
  285. self._analogy_b: analogy[:, 1],
  286. self._analogy_c: analogy[:, 2]
  287. })
  288. return idx
  289. def eval(self):
  290. """Evaluate analogy questions and reports accuracy."""
  291. # How many questions we get right at precision@1.
  292. correct = 0
  293. try:
  294. total = self._analogy_questions.shape[0]
  295. except AttributeError as e:
  296. raise AttributeError("Need to read analogy questions.")
  297. start = 0
  298. while start < total:
  299. limit = start + 2500
  300. sub = self._analogy_questions[start:limit, :]
  301. idx = self._predict(sub)
  302. start = limit
  303. for question in xrange(sub.shape[0]):
  304. for j in xrange(4):
  305. if idx[question, j] == sub[question, 3]:
  306. # Bingo! We predicted correctly. E.g., [italy, rome, france, paris].
  307. correct += 1
  308. break
  309. elif idx[question, j] in sub[question, :3]:
  310. # We need to skip words already in the question.
  311. continue
  312. else:
  313. # The correct label is not the precision@1
  314. break
  315. print()
  316. print("Eval %4d/%d accuracy = %4.1f%%" % (correct, total,
  317. correct * 100.0 / total))
  318. def analogy(self, w0, w1, w2):
  319. """Predict word w3 as in w0:w1 vs w2:w3."""
  320. wid = np.array([[self._word2id.get(w, 0) for w in [w0, w1, w2]]])
  321. idx = self._predict(wid)
  322. for c in [self._id2word[i] for i in idx[0, :]]:
  323. if c not in [w0, w1, w2]:
  324. print(c)
  325. break
  326. print("unknown")
  327. def nearby(self, words, num=20):
  328. """Prints out nearby words given a list of words."""
  329. ids = np.array([self._word2id.get(x, 0) for x in words])
  330. vals, idx = self._session.run(
  331. [self._nearby_val, self._nearby_idx], {self._nearby_word: ids})
  332. for i in xrange(len(words)):
  333. print("\n%s\n=====================================" % (words[i]))
  334. for (neighbor, distance) in zip(idx[i, :num], vals[i, :num]):
  335. print("%-20s %6.4f" % (self._id2word[neighbor], distance))
  336. def _start_shell(local_ns=None):
  337. # An interactive shell is useful for debugging/development.
  338. import IPython
  339. user_ns = {}
  340. if local_ns:
  341. user_ns.update(local_ns)
  342. user_ns.update(globals())
  343. IPython.start_ipython(argv=[], user_ns=user_ns)
  344. def main(_):
  345. """Train a word2vec model."""
  346. if not FLAGS.train_data or not FLAGS.eval_data or not FLAGS.save_path:
  347. print("--train_data --eval_data and --save_path must be specified.")
  348. sys.exit(1)
  349. opts = Options()
  350. with tf.Graph().as_default(), tf.Session() as session:
  351. with tf.device("/cpu:0"):
  352. model = Word2Vec(opts, session)
  353. model.read_analogies() # Read analogy questions
  354. for _ in xrange(opts.epochs_to_train):
  355. model.train() # Process one epoch
  356. model.eval() # Eval analogies.
  357. # Perform a final save.
  358. model.saver.save(session, os.path.join(opts.save_path, "model.ckpt"),
  359. global_step=model.global_step)
  360. if FLAGS.interactive:
  361. # E.g.,
  362. # [0]: model.analogy(b'france', b'paris', b'russia')
  363. # [1]: model.nearby([b'proton', b'elephant', b'maxwell'])
  364. _start_shell(locals())
  365. if __name__ == "__main__":
  366. tf.app.run()