Keras文本预处理详解

汇总

Tokenizer分词器(类)

Tokenizer.fit_on_texts分词器方法:实现分词

Tokenizer.texts_to_sequences分词器方法:输出向量序列

pad_sequences进行padding

具体示例和代码分析

分词器分词和向量化

主要的类是Tokenizer,用到其中的一些方法将文本转换为序列。需要注意的是这个类的一些默认方法

  • filters:默认会过滤一些标点符号,标点符号和单词之间没有空格也没关系。内部代码是先把标点符号替换为空格,然后进行分词,所以的这样的:"eat!Some"也可以正确识别
  • lower=True:默认会转为小写
  • split=" ":默认是空格

这些方法都已经实现,所以在可以不用自己写,直接设置参数就行。另外两个参数:

  • num_words:处理的最大单词数量。
  • char_level: 默认False,如果是True,返回字符向量化结果(char embedding的时候可以用到)

还有就是注意必须先进行fit_on_texts方法,然后进行texts_to_sequencesfit_on_texts后有两个有用的输出:

  • word_counts:词频统计结果
  • word_index:词和index的对应关系

texts_to_sequences输出的是根据对应关系输出的向量序列,是不定长的,跟句子的长度有关系。

from keras.preprocessing.text import Tokenizer
text1='Some ThING to eat !'
text2='some thing to drink .'
texts=[text1,text2]
print(texts)
#out:['Some ThING to eat !', 'some thing to drink .']
tokenizer = Tokenizer(num_words=100) #num_words:None或整数,处理的最大单词数量。少于此数的单词丢掉
tokenizer.fit_on_texts(texts)
print( tokenizer.word_counts) 
#out:OrderedDict([('some', 2), ('thing', 2), ('to', 2), ('eat', 1), ('drink', 1)])
print( tokenizer.word_index) 
#out:{'some': 1, 'thing': 2, 'to': 3, 'eat': 4, 'drink': 5}
sequences = tokenizer.texts_to_sequences(texts)
word_index = tokenizer.word_index
print(sequences)
#out:[[1, 2, 3, 4], [1, 2, 3, 5]] 转换为序列,注意这里句子等长,所以输出一样,但是不等长句子输出的长度是不一样的
print('Found %s unique tokens.' % len(word_index))
#out:Found 5 unique tokens.

填充至等长

pad_sequences,对上面生成的不定长序列进行补全。可以手动设定每个句子的最大长度参数,大于这个长度截断,小于这个长度填充。注意:默认补全和截断都是在句子前面进行填充和截断。这里是用0进行填充,也就是空格,这也是为什么上面序列index起始是1的原因。

#接上面的代码
SEQ_LEN = 10
data = pad_sequences(sequences, maxlen=SEQ_LEN)
print(data)
#out:[[0 0 0 0 0 0 1 2 3 4]
# [0 0 0 0 0 0 1 2 3 5]]

来自 https://zhuanlan.zhihu.com/p/55412623