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  '''

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM