【1】引言
前序學習進程中,已經學習CountVectorizer文本處理的簡單技巧,先相關文章鏈接為:
python學智能算法(十四)|機器學習樸素貝葉斯方法進階-CountVectorizer文本處理簡單測試-CSDN博客
此次繼續深入,研究多文本的綜合處理。
【2】代碼測試
首先相對于單文本測試,直接將文本改成多行文本:
# 引入必要的模塊
from sklearn.feature_extraction.text import CountVectorizer# 單個文檔
document = ["Python programming is fun and useful for data science.","Python is a great programming language for data science.","Data science uses Python for machine learning and AI.","AI and machine learning are fun with Python.","AI is popular at this time."]# 創建向量化器
vectorizer = CountVectorizer()
print('vetorizer=', vectorizer)
# 擬合并轉換文檔
X = vectorizer.fit_transform(document)
print('X=', X)
# 查看詞匯表
print("詞匯表:\n", vectorizer.get_feature_names_out())# 查看向量表示
print("向量表示:\n", X.toarray())
?嘗試運行一下:
X=? ?(0, 14)? ? 1
? (0, 13)? ? 1
? (0, 8)? ? 1
? (0, 6)? ? 1
? (0, 1)? ? 1
? (0, 18)? ? 1
? (0, 5)? ? 1
? (0, 4)? ? 1
? (0, 15)? ? 1
? (1, 14)? ? 1
? (1, 13)? ? 1
? (1, 8)? ? 1
? (1, 5)? ? 1
? (1, 4)? ? 1
? (1, 15)? ? 1
? (1, 7)? ? 1
? (1, 9)? ? 1
? (2, 14)? ? 1
? (2, 1)? ? 1
? (2, 5)? ? 1
? (2, 4)? ? 1
? (2, 15)? ? 1
? (2, 19)? ? 1
? (2, 11)? ? 1
? (2, 10)? ? 1
? (2, 0)? ? 1
? (3, 14)? ? 1
? (3, 6)? ? 1
? (3, 1)? ? 1
? (3, 11)? ? 1
? (3, 10)? ? 1
? (3, 0)? ? 1
? (3, 2)? ? 1
? (3, 20)? ? 1
? (4, 8)? ? 1
? (4, 0)? ? 1
? (4, 12)? ? 1
? (4, 3)? ? 1
? (4, 16)? ? 1
? (4, 17)? ? 1
詞匯表:
?['ai' 'and' 'are' 'at' 'data' 'for' 'fun' 'great' 'is' 'language'
?'learning' 'machine' 'popular' 'programming' 'python' 'science' 'this'
?'time' 'useful' 'uses' 'with']
向量表示:
?[[0 1 0 0 1 1 1 0 1 0 0 0 0 1 1 1 0 0 1 0 0]
?[0 0 0 0 1 1 0 1 1 1 0 0 0 1 1 1 0 0 0 0 0]
?[1 1 0 0 1 1 0 0 0 0 1 1 0 0 1 1 0 0 0 1 0]
?[1 1 1 0 0 0 1 0 0 0 1 1 0 0 1 0 0 0 0 0 1]
?[1 0 0 1 0 0 0 0 1 0 0 0 1 0 0 0 1 1 0 0 0]]?
最開始的X出現“(0,14),1”解讀:
0表示(Python programming is fun and useful for data science.)是第0行樣本,實際上從1開始計數是第1行樣本;
14表示樣本中的第一個詞,也就是Python,在按照所有文本中所有單詞首字母順序排列后,將位于第14號位置,實際上從1開始計數是第15個,后面的1表示Python這個詞在第0行樣本中出現了一次。
其余數據意義類似。
輸出的詞匯表是將所有文本中所有單詞首字母順序排列后獲得的結果。
向量表示則按照行的形式,將每一行的列數都擴充或者說是廣播到所有文本中所有單詞合并同類項后的數量,所有單詞合并同類項后剛好是17個數據,所以每一行都有17個數據,在對應行樣本中未出現的詞就會自動計數0。
【3】總結
使用CountVectorizer開展了多文簡單測試。