【1】引用
前序學習文章中,已經對拉普拉斯平滑和簡單二元分類進行了初步探索,相關文章鏈接為:
python學智能算法(十二)|機器學習樸素貝葉斯方法初步-拉普拉斯平滑計算條件概率-CSDN博客
python學智能算法(十三)|機器學習樸素貝葉斯方法進階-簡單二元分類-CSDN博客
在實踐應用中也會發現,樸素貝葉斯方法還能對文本進行分類,今天的學習目標就是學習簡單的文本操作技巧,需要使用sklearn里面的CountVectorizer包。
【2】代碼學習
首先是引入必要的模塊或者說庫:
# 引入必要的模塊
from sklearn.feature_extraction.text import CountVectorizer
輸入待處理的文本:
# 單個文檔
document = ["Python programming is fun and useful for data science."]
這里只有一個句子:Python programming is fun and useful for data science.
直接創建一個文本處理器:
# 創建向量化器
vectorizer = CountVectorizer()
CountVectorizer是 scikit-learn 庫中用于文本向量化的工具,將文本轉換為詞頻矩陣。CountVectorizer()滿足默認配置:
- 自動將文本轉為小寫。
- 按空格分詞。
- 不處理停用詞。
- 只考慮單個詞。
- ?
實際上,vectorizer在這里被定義為一個工具,通過這個工具才可以調用具體的文本處理命令。
然后就是:
X = vectorizer.fit_transform(document)
這里的fit_transform是由fit和transform兩個命令合并在一起的快捷操作:
fit命令的作用是分析文本中有哪些詞;
transform命令的作用是將文本轉化為詞頻矩陣,有合并同類項的功能。
CountVectorizer()是類的構造函數,vectorizer是實例,fit和transform是實例方法。
然后是查看詞匯表操作:
# 查看詞匯表
print("詞匯表:", vectorizer.get_feature_names_out())
這里的vectorizer.get_feature_names_out()執行后,會按照各個詞匯首字母的順序將組成句子的詞依次輸出,比如上方的句子Python programming is fun and useful for data science會輸出為:['and' 'data' 'for' 'fun' 'is' 'programming' 'python' 'science' 'useful']。
最后的向量輸出為:
# 查看向量表示
print("向量表示:", X.toarray())
X.toarray()本質上是輸出各個詞在句子中出現的次數。
比如上方的句子Python programming is fun and useful for data science,X.toarray()會輸出一系列1,因為每個單詞出現的頻次都是1。
完整代碼為:
# 引入必要的模塊
from sklearn.feature_extraction.text import CountVectorizer# 單個文檔
document = ["Python programming is fun and useful for data science."]# 創建向量化器
vectorizer = CountVectorizer()
print('vetorizer=',vectorizer)
# 擬合并轉換文檔
X = vectorizer.fit_transform(document)
print('X=',X)
# 查看詞匯表
print("詞匯表:", vectorizer.get_feature_names_out())# 查看向量表示
print("向量表示:", X.toarray())
代碼運行后的輸出為:
vetorizer= CountVectorizer()
X=? ?(0, 6)? ? 1
? (0, 5)? ? 1
? (0, 4)? ? 1
? (0, 3)? ? 1
? (0, 0)? ? 1
? (0, 8)? ? 1
? (0, 2)? ? 1
? (0, 1)? ? 1
? (0, 7)? ? 1
詞匯表: ['and' 'data' 'for' 'fun' 'is' 'programming' 'python' 'science' 'useful']
向量表示: [[1 1 1 1 1 1 1 1 1]]
【3】代碼測試
實際上要想測試代碼非常簡單,只需要改變初始句子即可,比如把句子改成:
# 單個文檔
document = ["Python programming is fun and useful for data science and math."]
此時的輸出就會變成:
詞匯表: ['and' 'data' 'for' 'fun' 'is' 'math' 'programming' 'python' 'science'
?'useful']
向量表示: [[2 1 1 1 1 1 1 1 1 1]]
顯然,出現了兩個and后,向量表示的頻次會自動增加。
?【4】細節說明
代碼中文本后面的點號不是必須的。
【5】總結
學習了CountVectorizer文本處理的簡單應用。
?