Keras文本预处理

学习了Keras文档里的文本预处理部分,参考网上代码写了个例子

 1 import keras.preprocessing.text as T
 2 from keras.preprocessing.text import Tokenizer
 3 
 4 text1='some thing to eat'
 5 text2='some thing to drink'
 6 texts=[text1,text2]
 7 
 8 #文本到文本列表
 9 print (T.text_to_word_sequence(text1))  #以空格区分,中文也不例外 ['some', 'thing', 'to', 'eat']
10 
11 #文本的ont-hot编码
12 print (T.one_hot(text1,10))  #[7, 9, 3, 4] -- (10表示数字化向量为10以内的数字)
13 print (T.one_hot(text2,10))  #[7, 9, 3, 1]
14 
15 tokenizer = Tokenizer(num_words=None) #num_words:None或整数,处理的最大单词数量。少于此数的单词丢掉
16 tokenizer.fit_on_texts(texts)
17 
18 #word_counts:字典,将单词(字符串)映射为它们在训练期间出现的次数。仅在调用fit_on_texts之后设置。
19 print( tokenizer.word_counts) #[('some', 2), ('thing', 2), ('to', 2), ('eat', 1), ('drink', 1)]
20 
21 #word_index: 字典,将单词(字符串)映射为它们的排名或者索引。仅在调用fit_on_texts之后设置
22 print( tokenizer.word_index) #{'some': 1, 'thing': 2,'to': 3 ','eat': 4, drink': 5}
23 
24 #word_docs: 字典,将单词(字符串)映射为它们在训练期间所出现的文档或文本的数量。仅在调用fit_on_texts之后设置。
25 print( tokenizer.word_docs) #{'some': 2, 'thing': 2, 'to': 2, 'drink': 1,  'eat': 1}
26 
27 
28 print( tokenizer.index_docs) #{1: 2, 2: 2, 3: 2, 4: 1, 5: 1}
29 
30 # num_words=多少会影响下面的结果,行数=num_words
31 
32 #序列的列表,列表中每个序列对应于一段输入文本
33 print( tokenizer.texts_to_sequences(texts)) #得到词索引[[1, 2, 3, 4], [1, 2, 3, 5]]
34 #形如(len(sequences), nb_words)的numpy array
35 print( tokenizer.texts_to_matrix(texts))  # 矩阵化=one_hot
36 '''
37 [[ 0.,  1.,  1.,  1.,  1.,  0.,  0.,  0.,  0.,  0.],
38  [ 0.,  1.,  1.,  1.,  0.,  1.,  0.,  0.,  0.,  0.]]
39  '''

 

posted @ 2018-04-16 22:11  cn_XuYang  阅读(2744)  评论(0编辑  收藏  举报