1. 程式人生 > >sklearn: CountVectorize處理及一些使用引數

sklearn: CountVectorize處理及一些使用引數

### sklearn: CountVectorize處理及一些使用引數 CountVectorizer是屬於常見的特徵數值計算類,是一個文字特徵提取方法。對於每一個訓練文字,它只考慮每種詞彙在該訓練文字中出現的頻率。 CountVectorizer會將文字中的詞語轉換為詞頻矩陣,它通過fit_transform函式計算各個詞語出現的次數。 ```python CountVectorizer(analyzer='word', binary=False, decode_error='strict', dtype=, encoding='utf-8', input='content', lowercase=True, max_df=1.0, max_features=None, min_df=1, ngram_range=(1, 1), preprocessor=None, stop_words=None, strip_accents=None, token_pattern='(?u)\\b\\w\\w+\\b', tokenizer=None, vocabulary=None) ``` CountVectorizer類的引數很多,分為三個處理步驟:preprocessing、tokenizing、n-grams generation. 一般要設定的引數是:**ngram_range,max_df,min_df,max_features,analyzer,stop_words,token_pattern等,具體情況具體分析** 。 1. **ngram_range** : 例如ngram_range(min,max),是指將text分成min,min+1,min+2,.........max 個不同的片語。比如 '我 愛 中國' 中ngram_range(1,3)之後可得到'我' '愛' '中國' '我 愛' '愛 中國' 和'我 愛 中國',如果是ngram_range (1,1) 則只能得到單個單詞'我' '愛'和'中國'。 2. **max_df:**可以設定為範圍在[0.0 1.0]的float,也可以設定為沒有範圍限制的int,預設為1.0。 這個引數的作用是作為一個閾值,當構造語料庫的關鍵詞集的時候,如果某個詞的document frequence大於max_df,這個詞不會被當作關鍵詞。如果這個引數是float,則表示詞出現的次數與語料庫文件數的百分比,如果是int,則表示詞出現的次數。如果引數中已經給定了vocabulary,則這個引數無效。 3. min_df: 類似於max_df,不同之處在於如果某個詞的document frequence小於min_df,則這個詞不會被當作關鍵詞。 4. **max_features:**預設為None,可設為int,對所有關鍵詞的term frequency進行降序排序,只取前max_features個作為關鍵詞集。 5. **analyzer:**一般使用預設,可設定為string型別,如’word’, ‘char’, ‘char_wb’,還可設定為callable型別,比如函式是一個callable型別。 6. **stop_words:**設定停用詞,設為english將使用內建的英語停用詞,設為一個list可自定義停用詞,設為None不使用停用詞,設為None且max_df∈[0.7, 1.0)將自動根據當前的語料庫建立停用詞表。 7. **token_pattern:**過濾規則,表示token的正則表示式,需要設定analyzer == ‘word’,預設的正則表示式選擇2個及以上的字母或數字作為token,標點符號預設當作token分隔符,而不會被當作token。 8. **decode_error:**預設為strict,遇到不能解碼的字元將報UnicodeDecodeError錯誤,設為ignore將會忽略解碼錯誤,還可以設為replace,作用尚不明確。 9. **binary:**預設為False,一個關鍵詞在一篇文件中可能出現n次,如果binary=True,非零的n將全部置為1,這對需要布林值輸入的離散概率模型的有用的。 ### 例項: ```python from sklearn.feature_extraction.text import CountVectorizer corpus = ['我 愛 中國 中國','爸爸 媽媽 愛 我','爸爸 媽媽 愛 中國'] # corpus = ['我愛中國','爸爸媽媽愛我','爸爸媽媽愛中國'] vectorizer = CountVectorizer(min_df=1, ngram_range=(1, 1)) ##建立詞袋資料結構,裡面相應引數設定 features = vectorizer.fit_transform(corpus) #擬合模型,並返回文字矩陣 print("CountVectorizer:") print(vectorizer.get_feature_names()) #顯示所有文字的詞彙,列表型別 #詞表 #['中國', '媽媽', '爸爸'] print(vectorizer.vocabulary_) #詞彙表,字典型別 #key:詞,value:對應編號 #{'中國': 0, '爸爸': 2, '媽媽': 1} print(features) #文字矩陣 #第一行 (0, 0) 2 表示為:第0個列表元素,**詞典中索引為0的元素**, 詞頻為2 # (0, 0) 2 # (1, 1) 1 # (1, 2) 1 # (2, 1) 1 # (2, 2) 1 # (2, 0) 1 print(features.toarray()) #.toarray() 是將結果轉化為稀疏矩陣 #將結果轉化為稀疏矩陣 #[[2 0 0] # [0 1 1] # [1 1 1]] print(features.toarray().sum(axis=0)) #統計每個詞在所有文件中的詞頻 #文字中的詞頻 #[3