本文主要参考 keras中文文档
1.句子分割text_to_word_sequence
keras.preprocessing.text.text_to_word_sequence(text,
filters='!"#$%&()*+,-./:;<=>?@[\]^_`{|}~\t\n',
lower=True,
split=" ")
将一个句子拆分成单词构成的列表
text:字符串,待处理的文本
filters:需要滤除的字符的列表或连接形成的字符串,例如标点符号。默认值为'!"#$%&()*+,-./:;<=>?@[]^_`{|}~\t\n',
包含标点符号,制表符和换行符等
lower:布尔值,是否将序列设为小写形式
split:字符串,单词的分隔符,如空格
2. one-hot编码
keras.preprocessing.text.one_hot(text,
n,
filters='!"#$%&()*+,-./:;<=>?@[\]^_`{|}~\t\n',
lower=True,
split=" ")
从定义上,当字典长为n时,每个单词应形成一个长为n的向量,其中仅有单词本身在字典中下标的位置为1,其余均为0,这称为one-hot。为了方便起见,函数在这里仅把“1”的位置,即字典中词的下标记录下来
n:整数,字典长度
其他参数同 #1
返回值:整数列表,每个整数是[1,n]之间的值,代表一个单词(不保证唯一性,即如果词典长度不够,不同的单词可能会被编为同一个码)。
3. 分词器Tokenizer
keras.preprocessing.text.Tokenizer(num_words=None,
filters='!"#$%&()*+,-./:;<=>?@[\]^_`{|}~\t\n',
lower=True,
split=" ",
char_level=False)
Tokenizer是一个用于向量化文本,或将文本转换为序列(即单词在字典中的下标构成的列表,从1算起)的类。
num_words:None或整数,处理的最大单词数量。若被设置为整数,则分词器将被限制为待处理数据集中最常见的num_words个单词,设置此参数texts_to_sequences
和texts_to_matrix
方法将受影响,即序列化后列表中的数字都不会超过num_words
char_level: 如果为 True, 每个字符将被视为一个标记
3.1 类方法
fit_on_text(texts)
使用一系列文档来生成token词典,texts为list类,每个元素为一个文档texts_to_sequences(texts)
将多个文档转换为索引向量形式,shape为[len(texts),len(text)] – (文档数,每条文档的长度)
返回值:序列的列表,列表中每个序列对应于一段输入文本texts_to_matrix(texts)
将多个文档转换为矩阵表示,shape为[len(texts),num_words]texts_to_sequences_generator(texts)
本函数是texts_to_sequences的生成器函数版
texts:待转为序列的文本列表
返回值:每次调用返回对应于一段输入文本的序列
import keras.preprocessing.text as text
text1 = "i love china"
text2 = "i love ningguo"
text3 = "i china i"
txt = [text1, text2, text3]
# 类的实例化
tokenizer = text.Tokenizer()
# 训练
tokenizer.fit_on_texts(txt)
seq = tokenizer.texts_to_sequences(txt)
matrix = tokenizer.texts_to_matrix(txt)
print("seq:",seq, type(seq))
print("matrix:", matrix, type(matrix))
输出
seq: [[1, 2, 3], [1, 2, 4], [1, 3, 1]] <class 'list'>
matrix: [[0. 1. 1. 1. 0.]
[0. 1. 1. 0. 1.]
[0. 1. 0. 1. 0.]] <class 'numpy.ndarray'>
3.2 属性
word_counts
:字典,将单词映射为它们在训练期间出现的次数。仅在调用fit_on_texts之后设置,返回dict{单词:频次}word_docs
: 字典,将单词映射为它们在训练期间所出现的文档或文本的数量。仅在调用fit_on_texts之后设置,返回dict{单词:包含该单词的文档数}word_index
: 字典,将单词映射为它们的排名或者索引。仅在调用fit_on_texts之后设置。返回dict{单词:索引}document_count
: 整数。分词器被训练的文档(文本或者序列)数量。仅在调用fit_on_texts或fit_on_sequences之后设置。返回文档总数
import keras.preprocessing.text as text
text1 = "i love china"
text2 = "i love ningguo"
text3 = "i china i"
txt = [text1, text2, text3]
tokenizer = text.Tokenizer()
tokenizer.fit_on_texts(txt)
print(tokenizer.word_index)
print(tokenizer.word_counts)
print(tokenizer.word_docs)
print(tokenizer.document_count)
输出:
{'i': 1, 'love': 2, 'china': 3, 'ningguo': 4}
OrderedDict([('i', 4), ('love', 2), ('china', 2), ('ningguo', 1)])
defaultdict(<class 'int'>, {'love': 2, 'china': 2, 'i': 3, 'ningguo':1})
3
4. 填充序列pad_sequences
keras.preprocessing.sequence.pad_sequences(sequences,
maxlen=None,
dtype='int32',
padding='pre',
truncating='pre',
value=0.)
将长为nb_samples
的序列(标量序列)转化为形如(nb_samples,nb_timesteps)2D numpy array
。如果提供了参数maxlen
,nb_timesteps=maxlen
,否则其值为最长序列的长度。其他短于该长度的序列都会在后部填充0以达到该长度。长于nb_timesteps的序列将会被截断,以使其匹配目标长度。padding和截断发生的位置分别取决于padding和truncating
.
参数
sequences:浮点数或整数构成的两层嵌套列表[num_docs, doc_length]
maxlen:None或整数,设定序列的最大长度。大于此长度的序列将被截短,小于此长度的序列将在后部填0.
dtype:返回的numpy array的数据类型
padding:‘pre’或‘post’,确定当需要补0时,在序列的起始还是结尾补, pre是在最前面补0,post是在最后面补零
truncating:‘pre’或‘post’,确定当需要截断序列时,从起始还是结尾截断
value:浮点数,此值将在填充时代替默认的填充值0
返回值
返回形如(nb_samples,nb_timesteps)
的2D张量
import keras.preprocessing.text as text
from keras.preprocessing.sequence import pad_sequences
text1 = "i love china shanghai"
text2 = "i love ningguo"
text3 = "i china"
txt = [text1, text2, text3]
# 类的实例化
tokenizer = text.Tokenizer()
# # 训练
tokenizer.fit_on_texts(txt)
seq = tokenizer.texts_to_sequences(txt)
print("seq:",seq, type(seq))
matrix = pad_sequences(seq)
print("pad:", matrix)
输出:
seq: [[1, 2, 3, 4], [1, 2, 5], [1, 3]] <class 'list'>
pad: [[1 2 3 4]
[0 1 2 5]
[0 0 1 3]]
import keras.preprocessing.text as text
from keras.preprocessing.sequence import pad_sequences
text1 = "i love china shanghai"
text2 = "i love ningguo"
text3 = "i china"
txt = [text1, text2, text3]
# 类的实例化
tokenizer = text.Tokenizer()
# # 训练
tokenizer.fit_on_texts(txt)
seq = tokenizer.texts_to_sequences(txt)
print("seq:",seq, type(seq))
matrix = pad_sequences(seq, maxlen=3, padding="post", truncating="post")
print("pad:", matrix)
seq: [[1, 2, 3, 4], [1, 2, 5], [1, 3]] <class 'list'>
pad: [[1 2 3]
[1 2 5]
[1 3 0]]