天天看點

Keras學習之一:文本與序列預處理

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,)  #[7, 9, 3, 4]
print T.one_hot(text2,)  #[7, 9, 3, 1]

tokenizer = Tokenizer(num_words=)
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) #
[[ ,  ,  ,  ,  ,  ,  ,  ,  ,  ],
 [ ,  ,  ,  ,  ,  ,  ,  ,  ,  ]]
           

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([[,,]],,padding='post')
# [[1, 2, 3, 0, 0, 0, 0, 0, 0, 0]]
           

繼續閱讀