【问题标题】:Tensorflow vocabularyprocessorTensorFlow 词汇处理器
【发布时间】:2017-04-01 09:29:56
【问题描述】:

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

vocab_processor = learn.preprocessing.VocabularyProcessor(max_document_length)

另外,我如何从 vocab_processor 中提取词汇

【问题讨论】:

  • 我正在尝试遵循相同的教程,但有一些我不明白的东西。也许你可以take a look at my question 帮助我?

标签: tensorflow vocabulary


【解决方案1】:

我已经弄清楚如何从词汇处理器对象中提取词汇。这对我来说非常有效。

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,依此类推。我想传递我自己的索引。例如,基于频率。你知道怎么做吗?
【解决方案2】:

无法理解 max_document_length 的用途

VocabularyProcessor 将您的文本文档映射为向量,并且您需要这些向量具有一致的长度。

您的输入数据记录可能不会(或可能不会)都具有相同的长度。例如,如果您使用句子进行情感分析,它们的长度会不同。

您将此参数提供给VocabularyProcessor,以便它可以调整输出向量的长度。根据the documentation

ma​​x_document_length:文档的最大长度。如果文件是 更长,它们将被修剪,如果更短 - 填充。

查看source code

  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 的向量。

【讨论】:

    猜你喜欢
    • 2017-02-11
    • 1970-01-01
    • 2017-06-23
    • 2021-08-02
    • 2020-08-19
    • 1970-01-01
    • 1970-01-01
    • 2018-08-21
    • 2020-03-22
    相关资源
    最近更新 更多