Tensorflow vocabularyprocessor

Я следую блогу wildml по классификации текста с помощью tensorflow. Я не могу понять цель max_document_length в инструкции кода:

vocab_processor = learn.preprocessing.VocabularyProcessor(max_document_length)

также, как я могу извлечь словарь из vocab_processor

2 ответов


я выяснил, как извлечь словарь из объекта 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)

не в состоянии понять цель 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.