tensorflow.contrib.learn.preprocessing.VocabularyProcessor

版权声明:转载请注明出处 https://blog.csdn.net/The_lastest/article/details/81771723

今天要记录的是TensorFlow中的一个非常有用的函数,以前都是自己手动现在这一功能,没想到居然有现成的。它就是learn.preprocessing.VocabularyProcessor,其作用,用官方的一句话来说就是 Learn the vocabulary dictionary and return indexies of words.

实现的功能就是,根据所有已分词好的文本建立好一个词典,然后找出每个词在词典中对应的索引,不足长度或者不存在的词补0

例如,现在有如下两个分词后的文档,即两个样本:

[['我 可以 跟 在 你 身后 像 影子 追着 光 梦游'],['我 可以 等 在 这 路口 不管 你 会不会 经过']]

根据这些样本我们可以建立如下的一个词典

dic = [UNK 我 可以 跟 在 你 身后 像 影子 追着 光 梦游 等 这 路口 不管 会不会 经过]

同时,我们可以发现在上面两个样本中,第一个样本的长度为11,第二个样本的长度为10,那到底用哪个呢? 答案是都行,甚至自己设定一个都行。比如我们这儿将11定为标准。则上个面两个样本转化之后的形式如下:

[[ 1  2  3  4  5  6  7  8  9 10 11]
 [ 1  2 12  4 13 14 15  5 16 17  0]]
 #每个数字都对应单词在字典中的位置

二者,只需要三行代码来实现:

s = ['我 可以 跟 在 你 身后 像 影子 追着 光 梦游',
     '我 可以 等 在 这 路口 不管 你 会不会 经过']
max_document_length = 11
vocab_processor = learn.preprocessing.VocabularyProcessor(max_document_length)
x = np.array(list(vocab_processor.fit_transform(s)))
print(x)
print(vocab_processor.vocabulary_.get('路口')) # 14 
print(vocab_processor.vocabulary_.__len__())# 18 (包含 'UNK')

另外,我们在上面建立字典的时候,只要这个词出现了我们就列入了字典中。但你可以设定一个频率,比如出现次数小于1的不要。

s = ['我 可以 跟 在 你 身后 像 影子 追着 光 梦游',
     '我 可以 等 在 这 路口 不管 你 会不会 经过']
max_document_length = 11
vocab_processor = learn.preprocessing.VocabularyProcessor(max_document_length=max_document_length,
                                                          min_frequency=1)
x = np.array(list(vocab_processor.fit_transform(s)))
print(x)
print(vocab_processor.vocabulary_.__len__())

#结果(不存在词典中的词也补0[[4 2 0 3 1 0 0 0 0 0 0]
 [4 2 0 3 0 0 0 1 0 0 0]]
5

猜你喜欢

转载自blog.csdn.net/The_lastest/article/details/81771723