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

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

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

 
 
  • 1

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

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

 
 
  • 1

同时,我们可以发现在上面两个样本中,第一个样本的长度为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]]
 #每个数字都对应单词在字典中的位置

 
 
  • 1
  • 2
  • 3

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

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

 
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
print(vocab_processor.vocabulary_.get('路口')) # 14 
print(vocab_processor.vocabulary_.__len__())# 18 (包含 'UNK')

 
 
  • 1
  • 2

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

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值