用TensorFlow中内置的vocabulary processor处理单词
一般我们在进行文本处理时,需要写方法建立词汇表和word到idx,以及idx到word的映射关系,这就需要统计词汇表中的所有单词并建立相应的词典。
在建立文档到idx的映射关系时,我们也可以用tensorflow内置的preprocessing.VocabularyProcessor来建立word到idx的映射关系。
VocabularyProcessor:Maps documents to sequences of word ids
class VocabularyProcessor(object):
"""Maps documents to sequences of word ids."""
def __init__(self,
max_document_length,
min_frequency=0,
vocabulary=None,
tokenizer_fn=None):
"""Initializes a VocabularyProcessor instance.
Args:
max_document_length: Maximum length of documents.
if documents are longer, they will be trimmed, if shorter - padded.
min_frequency: Minimum frequency of words in the vocabulary.
vocabulary: CategoricalVocabulary object.
Attributes:
vocabulary_: CategoricalVocabulary object.
"""
max_docyment_length:是文档的最大长度,如果一个句子超过了这个最大长度,则将会被截断,后面的不要。如果小于这个最大长度,则将会用0填充。
min_frequency:整个文档中单词出现的最小频数,如果出现频率小于这个设定值,则不会被加入到词表中。
vocab_processor=learn.preprocessing.VocabularyProcessor(max_document_length=max_sequence_length,min_frequency=min_word_frequency)
text_processed=np.array(list(vocab_processor.fit_transform(text_data_train)))
上面第一行代码最后返回的是一个CategoricalVocabulary 对象,通过fit_trainform方法将我们的文本数据fit到这个对象中,最终才能学习到这个文本对应的词汇表并返回单词对应的索引值。
我们使用这些索引值做embedding,然后才能将数据转换成神经网络需要的格式。