TensorFlow词汇处理器

17

我正在关注wildml博客上使用tensorflow进行文本分类的内容。我无法理解代码语句中max_document_length的目的:

vocab_processor = learn.preprocessing.VocabularyProcessor(max_document_length)

还有,我如何从vocab_processor中提取词汇表?


1
我正在尝试按照同样的教程进行操作,但有一些我不理解的地方。也许你可以看看我的问题,帮我解决一下? - Stefan Falk
2个回答

29
我已经想出如何从vocabularyprocessor对象中提取词汇。这对我来说运行得非常完美。
import numpy as np
from tensorflow.contrib import learn

x_text = ['This is a cat','This must be boy', 'This is a a dog']
max_document_length = max([len(x.split(" ")) for x in x_text])

## Create the vocabularyprocessor object, setting the max lengh of the documents.
vocab_processor = learn.preprocessing.VocabularyProcessor(max_document_length)

## Transform the documents using the vocabulary.
x = np.array(list(vocab_processor.fit_transform(x_text)))    

## Extract word:id mapping from the object.
vocab_dict = vocab_processor.vocabulary_._mapping

## Sort the vocabulary dictionary on the basis of values(id).
## Both statements perform same task.
#sorted_vocab = sorted(vocab_dict.items(), key=operator.itemgetter(1))
sorted_vocab = sorted(vocab_dict.items(), key = lambda x : x[1])

## Treat the id's as index into list and create a list of words in the ascending order of id's
## word with id i goes at index i of the list.
vocabulary = list(list(zip(*sorted_vocab))[0])

print(vocabulary)
print(x)

如果你看到vocab_dict,你会发现"This"被索引为1,"is"被索引为2等等。我想传递自己的索引。例如,基于频率的索引。你知道怎么做吗? - pnv

2
无法理解max_document_length的目的。
VocabularyProcessor将您的文本文档映射到向量中,您需要这些向量具有一致的长度。
您的输入数据记录可能不是(或可能不会)全部具有相同的长度。例如,如果您正在处理情感分析的句子,则它们将具有各种长度。
您提供此参数给VocabularyProcessor,以便它可以调整输出向量的长度。根据文档,max_document_length是文档的最大长度。如果文档过长,则会被剪裁;如果太短,则会填充。
请查看源代码。
  def transform(self, raw_documents):
    """Transform documents to word-id matrix.
    Convert words to ids with vocabulary fitted with fit or the one
    provided in the constructor.
    Args:
      raw_documents: An iterable which yield either str or unicode.
    Yields:
      x: iterable, [n_samples, max_document_length]. Word-id matrix.
    """
    for tokens in self._tokenizer(raw_documents):
      word_ids = np.zeros(self.max_document_length, np.int64)
      for idx, token in enumerate(tokens):
        if idx >= self.max_document_length:
          break
        word_ids[idx] = self.vocabulary_.get(token)
      yield word_ids

注意代码中的这一行:word_ids = np.zeros(self.max_document_length)
变量raw_documents中的每一行都将被映射为一个长度为max_document_length的向量。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接