encoder_manager.py 4.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135
  1. # Copyright 2017 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. """Manager class for loading and encoding with multiple skip-thoughts models.
  16. If multiple models are loaded at once then the encode() function returns the
  17. concatenation of the outputs of each model.
  18. Example usage:
  19. manager = EncoderManager()
  20. manager.load_model(model_config_1, vocabulary_file_1, embedding_matrix_file_1,
  21. checkpoint_path_1)
  22. manager.load_model(model_config_2, vocabulary_file_2, embedding_matrix_file_2,
  23. checkpoint_path_2)
  24. encodings = manager.encode(data)
  25. """
  26. from __future__ import absolute_import
  27. from __future__ import division
  28. from __future__ import print_function
  29. import collections
  30. import numpy as np
  31. import tensorflow as tf
  32. from skip_thoughts import skip_thoughts_encoder
  33. class EncoderManager(object):
  34. """Manager class for loading and encoding with skip-thoughts models."""
  35. def __init__(self):
  36. self.encoders = []
  37. self.sessions = []
  38. def load_model(self, model_config, vocabulary_file, embedding_matrix_file,
  39. checkpoint_path):
  40. """Loads a skip-thoughts model.
  41. Args:
  42. model_config: Object containing parameters for building the model.
  43. vocabulary_file: Path to vocabulary file containing a list of newline-
  44. separated words where the word id is the corresponding 0-based index in
  45. the file.
  46. embedding_matrix_file: Path to a serialized numpy array of shape
  47. [vocab_size, embedding_dim].
  48. checkpoint_path: SkipThoughtsModel checkpoint file or a directory
  49. containing a checkpoint file.
  50. """
  51. tf.logging.info("Reading vocabulary from %s", vocabulary_file)
  52. with tf.gfile.GFile(vocabulary_file, mode="r") as f:
  53. lines = list(f.readlines())
  54. reverse_vocab = [line.decode("utf-8").strip() for line in lines]
  55. tf.logging.info("Loaded vocabulary with %d words.", len(reverse_vocab))
  56. tf.logging.info("Loading embedding matrix from %s", embedding_matrix_file)
  57. # Note: tf.gfile.GFile doesn't work here because np.load() calls f.seek()
  58. # with 3 arguments.
  59. with open(embedding_matrix_file, "r") as f:
  60. embedding_matrix = np.load(f)
  61. tf.logging.info("Loaded embedding matrix with shape %s",
  62. embedding_matrix.shape)
  63. word_embeddings = collections.OrderedDict(
  64. zip(reverse_vocab, embedding_matrix))
  65. g = tf.Graph()
  66. with g.as_default():
  67. encoder = skip_thoughts_encoder.SkipThoughtsEncoder(word_embeddings)
  68. restore_model = encoder.build_graph_from_config(model_config,
  69. checkpoint_path)
  70. sess = tf.Session(graph=g)
  71. restore_model(sess)
  72. self.encoders.append(encoder)
  73. self.sessions.append(sess)
  74. def encode(self,
  75. data,
  76. use_norm=True,
  77. verbose=False,
  78. batch_size=128,
  79. use_eos=False):
  80. """Encodes a sequence of sentences as skip-thought vectors.
  81. Args:
  82. data: A list of input strings.
  83. use_norm: If True, normalize output skip-thought vectors to unit L2 norm.
  84. verbose: Whether to log every batch.
  85. batch_size: Batch size for the RNN encoders.
  86. use_eos: If True, append the end-of-sentence word to each input sentence.
  87. Returns:
  88. thought_vectors: A list of numpy arrays corresponding to 'data'.
  89. Raises:
  90. ValueError: If called before calling load_encoder.
  91. """
  92. if not self.encoders:
  93. raise ValueError(
  94. "Must call load_model at least once before calling encode.")
  95. encoded = []
  96. for encoder, sess in zip(self.encoders, self.sessions):
  97. encoded.append(
  98. np.array(
  99. encoder.encode(
  100. sess,
  101. data,
  102. use_norm=use_norm,
  103. verbose=verbose,
  104. batch_size=batch_size,
  105. use_eos=use_eos)))
  106. return np.concatenate(encoded, axis=1)
  107. def close(self):
  108. """Closes the active TensorFlow Sessions."""
  109. for sess in self.sessions:
  110. sess.close()