用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,然后才能将数据转换成神经网络需要的格式。

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值