[sentence encoder] 使用Skip-Thought Vectors在自己的数据集上训练一个sentence encoder

Skip-Thought Vectors

Skip-Thoughts 模型是一个句子编码器。它学习将输入的句子编码成固定维度的向量表示,这些向量表示能够对许多任务有用,例如检测释义,或对产品评论进行积极或消极的分类等等。

有关模型架构和更多示例应用的详细信息,可以参阅Ryan Kiros 等人的 NIPS 论文 Skip-Thought Vectors

用法

Skip-Thought Vector 已经被收录到了TensorFlow的model里面,在这里已经很详细的说明了该模型的用法。
从准备数据到训练模型以及测试作者都已经写的很详细了,但是作者在训练完过后用在Google News dataset上预训练的模型对Vocabulary进行了扩展,但是笔者在使用过程中想完全用自己的数据集进行训练,于是就跳过了这一步。
但是笔者在使用时发现,到Evaluating a Model这一步时找不到所需要的Embeddings file

解决方法

笔者在看了对Vocabulary进行扩展部分的源码,发现他其实有从checkpoint中获取embedding file 的方法,但是如果你不对Vocabulary进行扩展的话是不会执行这个操作的,于是笔者就根据这个方法自己获取了embedding file

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import collections
import os.path


import numpy as np
import sklearn.linear_model
import tensorflow as tf
def _load_skip_thoughts_embeddings(checkpoint_path):
  """Loads the embedding matrix from a skip-thoughts model checkpoint.

  Args:
    checkpoint_path: Model checkpoint file or directory containing a checkpoint
        file.

  Returns:
    word_embedding: A numpy array of shape [vocab_size, embedding_dim].

  Raises:
    ValueError: If no checkpoint file matches checkpoint_path.
  """
  if tf.gfile.IsDirectory(checkpoint_path):
    checkpoint_file = tf.train.latest_checkpoint(checkpoint_path)
    if not checkpoint_file:
      raise ValueError("No checkpoint file found in %s" % checkpoint_path)
  else:
    checkpoint_file = checkpoint_path

  tf.logging.info("Loading skip-thoughts embedding matrix from %s",
                  checkpoint_file)
  reader = tf.train.NewCheckpointReader(checkpoint_file)
  word_embedding = reader.get_tensor("word_embedding")
  tf.logging.info("Loaded skip-thoughts embedding matrix of shape %s",
                  word_embedding.shape)

  return word_embedding

if __name__=="__main__":
    skip_thoughts_model = "./model423/train"
    emb = _load_skip_thoughts_embeddings(skip_thoughts_model)
    np.save("b.npy", emb)

这样就在不扩展Vocabulary的情况下获取到了embedding file 之后就可以使用在自己的数据集上训练的 Skip-Thought Vectors sentence encoder 模型了。

总结

笔者最开始不想对Vocabulary 进行扩展是想训练一个针对自己数据的 sentence encoder 模型,但是后来实验效果不理想,考虑到是不是因为自己的数据集太小,导致效果不好,又对Vocabulary进行了扩展,但是发现其实没什么影响,倒是在其他地方做改进实验效果有了提升。
但是当初找不到embedding file这个问题困扰了我很久,于是就写了出来。

猜你喜欢

转载自blog.csdn.net/sinat_29963957/article/details/81321999