Keras学习之一:文本与序列预处理

11 篇文章 5 订阅

1 简介

在进行自然语言处理之前,需要对文本进行处理。
本文介绍keras提供的预处理包keras.preproceing下的text与序列处理模块sequence模块

2 text模块提供的方法

  • text_to_word_sequence(text,fileter) 可以简单理解此函数功能类str.split
  • one_hot(text,vocab_size) 基于hash函数(桶大小为vocab_size),将一行文本转换向量表示

3 text.Tokenizer类

这个类用来对文本中的词进行统计计数,生成文档词典,以支持基于词典位序生成文本的向量表示。
init(num_words) 构造函数,传入词典的最大值

3.1 成员函数

  • fit_on_text(texts) 使用一系列文档来生成token词典,texts为list类,每个元素为一个文档。
  • texts_to_sequences(texts) 将多个文档转换为word下标的向量形式,shape为[len(texts),len(text)]
  • texts_to_matrix(texts) 将多个文档转换为矩阵表示,shape为[len(texts),num_words]

3.2 成员变量

  • document_count 处理的文档数量
  • word_index 一个dict,保存所有word对应的编号id,从1开始
  • word_counts 一个dict,保存每个word在所有文档中出现的次数
  • word_docs 一个dict,保存每个word出现的文档的数量
  • index_docs 一个dict,保存word的id出现的文档的数量

3.3 示例

import keras.preprocessing.text as T
from keras.preprocessing.text import Tokenizer

text1='some thing to eat'
text2='some thing to drink'
texts=[text1,text2]

print T.text_to_word_sequence(text1)  #['some', 'thing', 'to', 'eat']
print T.one_hot(text1,10)  #[7, 9, 3, 4]
print T.one_hot(text2,10)  #[7, 9, 3, 1]

tokenizer = Tokenizer(num_words=10)
tokenzier.fit_on_text(texts)
print tokenizer.word_count #[('some', 2), ('thing', 2), ('to', 2), ('eat', 1), ('drink', 1)]
print tokenizer.word_index #{'some': 1, 'thing': 2,'to': 3 ','eat': 4, drink': 5}
print tokenizer.word_docs #{'some': 2, 'thing': 2, 'to': 2, 'drink': 1,  'eat': 1}
print tokenizer.index_docs #{1: 2, 2: 2, 3: 2, 4: 1, 5: 1}

print tokenizer.text_to_sequences(texts) #[[1, 2, 3, 4], [1, 2, 3, 5]]
print tokenizer.text_to_matrix(texts) #
[[ 0.,  1.,  1.,  1.,  1.,  0.,  0.,  0.,  0.,  0.],
 [ 0.,  1.,  1.,  1.,  0.,  1.,  0.,  0.,  0.,  0.]]

4 sequence模块

4.1 模块提供的方法

  • pad_sequences(sequences, maxlen, padding=’pre’, truncating=’pre’, value=0.) 将序列填充到maxlen长度,padding取值有pre|post,value指定用何值填充的值

4.2 示例

import keras.preprocessing.sequence as S
S.pad_sequences([[1,2,3]],10,padding='post')
# [[1, 2, 3, 0, 0, 0, 0, 0, 0, 0]]
  • 2
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值