2016-11-17 3 views
14

Я следую за блоком wildml по классификации текста, используя тензор. Я не в состоянии понять цель max_document_length в заявлении Код:Tensorflow vocabularyprocessor

vocab_processor = learn.preprocessing.VocabularyProcessor(max_document_length) 

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

+1

Я пытаюсь следовать тому же учебнику, но есть несколько вещей, которые я не понимаю. Может быть, вы можете [взглянуть на мой вопрос] (http://stackoverflow.com/questions/41665109/trying-to-understand-cnns-for-nlp-tutorial-using-tensorflow) и помочь мне? – displayname

ответ

24

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

Если вы видите vocab_dict, вы можете увидеть, что «Это» индексируется как 1, «есть» как 2 и так далее. Я хотел бы передать свой собственный индекс. Например, основанная на частоте. Вы знаете, как это сделать? – user1930402

1

не в состоянии понять цель max_document_length

The VocabularyProcessor отображает текстовые документы в векторы, и вам нужны эти векторы быть последовательной длины.

Ваши записи входных данных не могут (или, вероятно, не будут) иметь одинаковую длину. Например, если вы работаете с предложениями для анализа настроений, они будут иметь разную длину.

Вы предоставляете этот параметр VocabularyProcessor, чтобы он мог регулировать длину выходных векторов. По the documentation,

max_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.