在本文中,筆者將會緊接著上文提及的3個概念,拓展到文本挖掘中一個重要的概念 ---(文本)向量空間,它是將自然語言轉化為機器可識別符號的關鍵一步,文本相似度、文本聚類、文本分類等實際應用皆以此為基礎。
培養碼代碼的好習慣,設置日誌,列印程序運行中的細節,以便調試代碼。
import logginglogging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO)import osimport tempfileTEMP_FOLDER = tempfile.gettempdir()print('文件夾"{}" 將被用來存儲語料和臨時性的字典'.format(TEMP_FOLDER))文件夾"C:\Users\hp\AppData\Local\Temp" 將被用來存儲語料和臨時性的字典
一、從字符串到向量(From Strings to Vectors)
這次,筆者還是使用之前關於「知識圖譜」報導的標題語料庫作為示例:
from gensim import corporaimport jieba2019-05-06 09:59:43,964 : INFO : 'pattern' package not found; tag filters are not available for English
根據列印出的日誌可知,'pattern'沒正確安裝上,這個庫是自然語言處理裡一個很棒的庫,不過目前沒怎麼更新了,且對中文的支持不給力,所以不影響接下來的分析。
jieba.add_word('知識圖譜')
docs = ['商業新知:知識圖譜為內核,構建商業創新服務完整生態。','如何更好利用知識圖譜技術做反欺詐? 360金融首席數據科學家沈贇開講。','知識管理 | 基於知識圖譜的國際知識管理領域可視化分析。','一文詳解達觀數據知識圖譜技術與應用。','知識圖譜技術落地金融行業的關鍵四步。','一文讀懂知識圖譜的商業應用進程及技術背景。','海雲數據CPO王斌:打造大數據可視分析與AI應用的高科技企業。','智能產業|《人工智慧標準化白皮書2018》帶來創新創業新技術標準。','國家語委重大科研項目「中華經典詩詞知識圖譜構建技術研究」開題。','最全知識圖譜介紹:關鍵技術、開放數據集、應用案例匯總。','中譯語通Jove Mind知識圖譜平臺 引領企業智能化發展。','知識圖譜:知識圖譜賦能企業數位化轉型,為企業升級轉型注入新能量。']再對文本進行分詞,用空格隔開變成字符串,方便進行下一步的處理:
documents = [' '.join(jieba.lcut(i)) for i in docs]documents['商業 新知 : 知識圖譜 為 內核 , 構建 商業 創新 服務 完整 生態 。',
'如何 更好 利用 知識圖譜 技術 做 反 欺詐 ? 360 金融 首席 數據 科學家 沈贇 開講 。',
'知識 管理 | 基於 知識圖譜 的 國際 知識 管理 領域 可視化 分析 。',
'一文 詳解 達觀 數據 知識圖譜 技術 與 應用 。',
'知識圖譜 技術 落地 金融 行業 的 關鍵 四步 。',
'一文 讀懂 知識圖譜 的 商業 應用 進程 及 技術 背景 。',
'海雲 數據 CPO 王斌 : 打造 大 數據 可視 分析 與 AI 應用 的 高科技 企業 。',
'智能 產業 | 《 人工智慧 標準化 白皮書 2018 》 帶來 創新 創業 新 技術標準 。',
'國家語委 重大 科研項目 「 中華 經典 詩詞 知識圖譜 構建 技術 研究 」 開題 。',
'最全 知識圖譜 介紹 : 關鍵技術 、 開放 數據 集 、 應用 案例 匯總 。',
'中譯 語通 Jove Mind 知識圖譜 平臺 引領 企業 智能化 發展 。',
'知識圖譜 : 知識圖譜 賦能 企業 數位化 轉型 , 為 企業 升級 轉型 注入 新 能量 。']這是一個包含12個文檔的小型語料,每個文檔僅包含1個語句。
首先,對這些文檔進行分詞處理,移除停用詞,並去掉那些僅在本語料中出現一次的詞彙:
# 移除常用詞以及分詞stoplist = [i.strip() for i in open('datasets/stopwords_zh.txt',encoding='utf-8').readlines()]texts = [[word for word in document.lower().split() if word not in stoplist]for document in documents]
# 移除僅出現一次的詞彙from collections import defaultdictfrequency = defaultdict(int)for text in texts:for token in text: frequency[token] += 1
texts = [[token for token in text if frequency[token] > 1] for text in texts]
from pprint import pprint pprint(texts)[['商業', '知識圖譜', '商業', '創新'],
['知識圖譜', '技術', '金融', '數據'],
['知識', '管理', '知識圖譜', '知識', '管理', '分析'],
['一文', '數據', '知識圖譜', '技術'],
['知識圖譜', '技術', '金融'],
['一文', '知識圖譜', '商業', '技術'],
['數據', '數據', '分析', '企業'],
['創新'],
['知識圖譜', '技術'],
['知識圖譜', '數據'],
['知識圖譜', '企業'],
['知識圖譜', '知識圖譜', '企業', '轉型', '企業', '轉型']]處理文檔的方式需要因時制宜,隨機應變,尤其是在不同的應用場景中,比如電商評論、博客長文以及微博內容都需要使用不同的預處理方法,筆者會在後面的文章中提及這些技巧。在這裡,基於上面的分詞,筆者僅用空格分開,然後對語句中的西文詞彙進行「小寫化(Lowercasing)」。
機器是看不懂人類的自然語言(自然語言通常是指一種自然地隨文化演化的語言。例如,英語、漢語、日語為自然語言的例子,而世界語則為人造語言,即是一種為某些特定目的而創造的語言),若要機器「讀懂」自然語言,則需要將其轉換為機器可識別的符號,比如"0"和"1",且這種轉換的過程中需要最大限度保留自然語言特有的語義特徵,這是一個很有難度的任務。在這裡,筆者介紹一種常見的文本表示方法 --- 稱為詞袋模型,即Bag-of-Words)。
在詞袋模型模型下,像是句子或是文件這樣的文字可以用一個袋子裝著這些詞的方式表現,這種表現方式不考慮文法以及詞的順序。https://baike.baidu.com/item/%E8%AF%8D%E8%A2%8B%E6%A8%A1%E5%9E%8B/22776998?fr=aladdin後面還會有很多不同的文本表示方法,比如TF-IDF、LSA、LSI、LDA、HDP、NMF、Word2vec等。但是,請記住,不同的應用場景需要不同的文本特徵,沒有百試不爽的方法,並且,請一如既往的記住這句名言:
垃圾入,垃圾出(garbage in, garbage out)。
使用詞袋模型將多個文檔轉換為向量,每個文檔由一個向量表示,其中向量元素「i」表示第i個單詞出現在文檔中的次數。
僅通過它們的(整型)id來表徵詞彙是有利的, 問題和ID之間的映射稱為字典(dictionary):
dictionary = corpora.Dictionary(texts)dictionary.save(os.path.join(TEMP_FOLDER, 'deerwester.dict')) # 保存字典,以備後續查找之用print(dictionary)2019-05-06 15:58:09,861 : INFO : adding document #0 to Dictionary(0 unique tokens: [])
2019-05-06 15:58:09,867 : INFO : built Dictionary(12 unique tokens: ['創新', '商業', '知識圖譜', '技術', '數據']...) from 12 documents (total 42 corpus positions)
2019-05-06 15:58:09,873 : INFO : saving Dictionary object under C:\Users\hp\AppData\Local\Temp\deerwester.dict, separately None
2019-05-06 15:58:09,879 : INFO : saved C:\Users\hp\AppData\Local\Temp\deerwester.dictDictionary(12 unique tokens: ['創新', '商業', '知識圖譜', '技術', '數據']...)
在這裡,我們通過gensim.corpora.dictionary.Dictionary這個類為處理過的語料庫中出現的每個詞彙分配一個獨一無二的整數ID 。這會掃描整個文本,統計所有的詞彙計數和詞彙相關數據。最後,我們看到在處理的語料庫中有12個不同的詞彙,這意味著每個文檔將由12個數字表示(即12-D向量)。下面,查看每個詞彙與其對應ID之間的映射關係:
print(dictionary.token2id){'創新': 0, '商業': 1, '知識圖譜': 2, '技術': 3, '數據': 4, '金融': 5, '分析': 6, '知識': 7, '管理': 8, '一文': 9, '企業': 10, '轉型': 11}
將分詞後的文檔實際轉換為向量:
new_doc = "知識圖譜 為 企業 轉型 助力"new_vec = dictionary.doc2bow(new_doc.lower().split())print(new_vec)[(2, 1), (10, 1), (11, 1)]
函數doc2bow()只是計算每個不同詞彙的出現次數,將詞彙轉換為整數詞彙id,並將結果作為一個詞袋(bag-of-words)--- 一個稀疏向量返回,形式為( word_id1,word_count1),( word_id2,word_count2),( word_id3,word_count3)...
在token_id中,「創新」對應的為0,「商業」為1,...,'轉型'為11。因而,新文檔「知識圖譜 為 企業 轉型 助力(知識圖譜為企業轉型助力)」將被轉換為[(2, 1), (10, 1), (11, 1)]。"知識圖譜"、「企業」、「轉型」 出現在詞典中並出現一次。因此,它們在稀疏向量中分別變為(2, 1), (10, 1), (11, 1)。「為」、「轉型」、「助力」等詞彙在字典中不存在,因此不會出現在稀疏向量中。 詞彙計數為0的詞彙不會出現在稀疏向量中,並且稀疏向量中將永遠不會出現像(3,0)這樣的元素。
對於熟悉scikit-learn的人來說,doc2bow()與在CountVectorizer上調用transform()有類似的作用(http://scikit-learn.org/stable/modules/generated/sklearn.feature_extraction.text.CountVectorizer.html)。 doc2bow()也可以像fit_transform()那樣運作,相關詳細信息,請參閱gensim API Doc(https://radimrehurek.com/gensim/corpora/dictionary.html#gensim.corpora.dictionary.Dictionary.doc2bow)。
corpus = [dictionary.doc2bow(text) for text in texts]corpora.MmCorpus.serialize(os.path.join(TEMP_FOLDER, 'deerwester.mm'), corpus) #保存到本地,以作後用for c in corpus:print(c)2019-05-06 16:00:28,683 : INFO : storing corpus in Matrix Market format to C:\Users\hp\AppData\Local\Temp\deerwester.mm
2019-05-06 16:00:28,688 : INFO : saving sparse matrix to C:\Users\hp\AppData\Local\Temp\deerwester.mm
2019-05-06 16:00:28,690 : INFO : PROGRESS: saving document #0
2019-05-06 16:00:28,693 : INFO : saved 12x12 matrix, density=24.306% (35/144)
2019-05-06 16:00:28,695 : INFO : saving MmCorpus index to C:\Users\hp\AppData\Local\Temp\deerwester.mm.index[(0, 1), (1, 2), (2, 1)]
[(2, 1), (3, 1), (4, 1), (5, 1)]
[(2, 1), (6, 1), (7, 2), (8, 2)]
[(2, 1), (3, 1), (4, 1), (9, 1)]
[(2, 1), (3, 1), (5, 1)]
[(1, 1), (2, 1), (3, 1), (9, 1)]
[(4, 2), (6, 1), (10, 1)]
[(0, 1)]
[(2, 1), (3, 1)]
[(2, 1), (4, 1)]
[(2, 1), (10, 1)]
[(2, 2), (10, 2), (11, 2)]到目前為止,應該清楚的是,帶有id = 10的向量特徵表示文檔中出現「企業」一詞的次數---在這12個文檔中, 只有倒數前2個和和倒數第6個的值為1,其他皆為0。
二、語料庫流(Corpus Streaming) --- 每次僅調用一個文檔請注意,上面的語料(corpus)完全駐留在內存中,作為普通的Python列表而存在。在這個簡單的例子中,它並不重要,只是為了闡述方便。讓我們假想,手頭的語料庫中有數千萬個文檔,要將所有這些文檔都存儲在RAM中是行不通的,這會消耗大量的計算資源,速度奇慢!相反,我們假設文檔存儲在本地的單個文件中,每行一個文檔。Gensim只要求語料庫在需要使用時,能夠一次返回一個文檔向量:
from smart_open import smart_openclass MyCorpus(object):def __iter__(self):for line in smart_open('datasets/mycorpus.txt', 'r',encoding='utf-8'):# 假設每一行一個文檔,用jieba進行分詞yield dictionary.doc2bow(' '.join(jieba.lcut(line)).lower().split())每個文檔佔用單個文件中一行的假設並不重要; 你可以設計__iter__函數以適合你的特定輸入格式,比如文檔目錄、待解析的XML、可訪問的網絡節點...只需解析你的輸入以檢索每個文檔中的所用詞彙,然後通過字典將這些詞彙轉換為它們對應的整數ID,並在__iter__中產生具有生成器屬性的稀疏向量。
corpus_memory_friendly = MyCorpus() print(corpus_memory_friendly)<__main__.MyCorpus object at 0x00000160C6575320>
現在,corpus_memory_friendly是一個對象。我們沒有定義任何列印(print)方式,因此print只輸出對象在內存中的地址, 這看起來沒啥用。要查看其中的向量構成,需要遍歷語料庫,並列印每個文檔向量(一次一個):
for vector in corpus_memory_friendly: print(vector)[(0, 1), (1, 2), (2, 1), (3, 1)]
[(2, 1), (3, 1), (4, 1), (5, 1), (6, 1)]
[(2, 1), (3, 3), (7, 1), (8, 2)]
[(2, 1), (3, 1), (4, 1), (5, 1), (9, 1)]
[(2, 1), (3, 1), (4, 1), (6, 1)]
[(1, 1), (2, 1), (3, 1), (4, 1), (9, 1)]
[(5, 2), (7, 1), (10, 1)]
[(0, 1)]
[(2, 1), (3, 1), (4, 1)]
[(2, 1), (3, 1), (5, 1)]
[(2, 1), (3, 1), (10, 1)]
[(2, 2), (3, 2), (10, 1)]儘管輸出與普通的Python列表的輸出相同,但此時的語料庫對內存更友好 --- 一次最多只有一個向量駐留在RAM中, 現在,你的語料庫想用多大就用多大,哪怕是成千上萬個文檔,只是速度稍慢罷了。
我們將使用mycorpus.txt這個文件來創建字典(Dictionary),但不是將整個文件加載到本地內存中。然後,我們將過濾掉語料中的停用詞以及詞頻為1的詞彙,從而得到「淨化」後的語料。
請記住,dictionary.filter_tokens(或者dictionary.add_document)將調用dictionary.compactify()來刪除詞彙id序列中的間隙,空置的佔位符("")將會被剔除。
from six import iteritemsfrom smart_open import smart_open#收集所有詞彙的統計信息dictionary = corpora.Dictionary(' '.join(jieba.lcut(line)).lower().split() for line in smart_open('datasets/mycorpus.txt', 'r',encoding='utf-8'))
#停用詞和低頻詞(這裡指僅出現1次的詞彙)的ID集合stop_ids = [dictionary.token2id[stopword] for stopword in stoplist if stopword in dictionary.token2id]once_ids = [tokenid for tokenid, docfreq in iteritems(dictionary.dfs) if docfreq == 1]
#真正實施去停用詞和低頻次的操作dictionary.filter_tokens(stop_ids + once_ids)print(dictionary)2019-05-06 15:44:52,297 : INFO : adding document #0 to Dictionary(0 unique tokens: [])
2019-05-06 15:44:52,303 : INFO : built Dictionary(100 unique tokens: [',', ':', '。', '為', '內核']...) from 12 documents (total 164 corpus positions)Dictionary(10 unique tokens: ['創新', '商業', '圖譜', '知識', '技術']...)
到這裡,詞袋錶示(Bag-of-words Representation)的原理和操作就說完了。當然,我們用這種語料庫可以做什麼是另一個問題; 計算不同單詞的出現頻率可能是有用的,但在實際場景中,這還不夠。
事實證明,我們經常需要對這個簡單的表示進行轉換(Transformation),之後才能進行文檔相似度、文本聚類或者文本分類這樣的任務。轉換後面會提到,但在此之前,讓我們將注意力集中在語料庫持久性(Corpus Persistency)上。
三、語料格式(Corpus Formats)存在幾種用於將向量空間(Vector Space)語料庫(向量序列)序列化到本地的文件格式。 Gensim通過前面提到的流式語料庫接口(Streaming Corpus Interface)實現:以惰性方式(A Lazy Fashion)從本地讀取大量語料,一次一個文檔,而不是一次性將整個語料庫讀入本地內存中,這在語料庫極為龐大時是很折騰電腦的。
其中,一種比較值得注意的文件格式是Matrix Market格式(http://math.nist.gov/MatrixMarket/formats.html)。
下面,將文檔以Matrix Market格式保存:
#創建一個包含2個文檔的微小語料,以一個python列表呈現
corpus = [[(1, 0.5)], []] # 其中一個文檔故意搞成空的
corpora.MmCorpus.serialize(os.path.join(TEMP_FOLDER, 'corpus.mm'), corpus)2019-05-06 16:36:54,265 : INFO : storing corpus in Matrix Market format to C:\Users\hp\AppData\Local\Temp\corpus.mm
2019-05-06 16:36:54,281 : INFO : saving sparse matrix to C:\Users\hp\AppData\Local\Temp\corpus.mm
2019-05-06 16:36:54,285 : INFO : PROGRESS: saving document #0
2019-05-06 16:36:54,290 : INFO : saved 2x2 matrix, density=25.000% (1/4)
2019-05-06 16:36:54,293 : INFO : saving MmCorpus index to C:\Users\hp\AppData\Local\Temp\corpus.mm.index其他的存儲格式還有Joachim’s SVMlight format(http://svmlight.joachims.org/)、 Blei’s LDA-C format(http://www.cs.columbia.edu/~blei/lda-c/) 和 GibbsLDA++ format(http://gibbslda.sourceforge.net/)。
corpora.SvmLightCorpus.serialize(os.path.join(TEMP_FOLDER, 'corpus.svmlight'), corpus)corpora.BleiCorpus.serialize(os.path.join(TEMP_FOLDER, 'corpus.lda-c'), corpus)corpora.LowCorpus.serialize(os.path.join(TEMP_FOLDER, 'corpus.low'), corpus)2019-05-06 16:39:11,653 : INFO : converting corpus to SVMlight format: C:\Users\hp\AppData\Local\Temp\corpus.svmlight
2019-05-06 16:39:11,659 : INFO : saving SvmLightCorpus index to C:\Users\hp\AppData\Local\Temp\corpus.svmlight.index
2019-05-06 16:39:11,662 : INFO : no word id mapping provided; initializing from corpus
2019-05-06 16:39:11,666 : INFO : storing corpus in Blei's LDA-C format into C:\Users\hp\AppData\Local\Temp\corpus.lda-c
2019-05-06 16:39:11,671 : INFO : saving vocabulary of 2 words to C:\Users\hp\AppData\Local\Temp\corpus.lda-c.vocab
2019-05-06 16:39:11,676 : INFO : saving BleiCorpus index to C:\Users\hp\AppData\Local\Temp\corpus.lda-c.index
2019-05-06 16:39:11,681 : INFO : no word id mapping provided; initializing from corpus
2019-05-06 16:39:11,684 : INFO : storing corpus in List-Of-Words format into C:\Users\hp\AppData\Local\Temp\corpus.low
2019-05-06 16:39:11,690 : WARNING : List-of-words format can only save vectors with integer elements; 1 float entries were truncated to integer value
2019-05-06 16:39:11,693 : INFO : saving LowCorpus index to C:\Users\hp\AppData\Local\Temp\corpus.low.index反向操作,從Matrix Market文件加載語料庫迭代器(Corpus Iterator):
corpus = corpora.MmCorpus(os.path.join(TEMP_FOLDER, 'corpus.mm'))2019-05-06 16:40:06,275 : INFO : loaded corpus index from C:\Users\hp\AppData\Local\Temp\corpus.mm.index
2019-05-06 16:40:06,278 : INFO : initializing cython corpus reader from C:\Users\hp\AppData\Local\Temp\corpus.mm
2019-05-06 16:40:06,281 : INFO : accepted corpus with 2 documents, 2 features, 1 non-zero entries語料庫對象是流式的(Streams),因此,我們通常無法直接列印它們,只有通過遍歷才能看到其中的元素:
MmCorpus(2 documents, 2 features, 1 non-zero entries)
通過迭代器列表化來查看語料庫中的元素:
# 一種列印語料庫的方式是 --- 將其整個載入內存中print(list(corpus))[[(1, 0.5)], []]
或者這樣:
# 另一種方法:一次列印一個文檔for doc in corpus:print(doc)[(1, 0.5)]
[]顯然,第二種方式對內存更友好,但是出於測試和開發的目的,沒有什麼比調用list(corpus)更簡單、快捷!。
接下來,以Blei的LDA-C格式保存相同的Matrix Market文檔流:
corpora.BleiCorpus.serialize(os.path.join(TEMP_FOLDER, 'corpus.lda-c'), corpus)2019-05-06 16:46:55,322 : INFO : no word id mapping provided; initializing from corpus
2019-05-06 16:46:55,325 : INFO : storing corpus in Blei's LDA-C format into C:\Users\hp\AppData\Local\Temp\corpus.lda-c
2019-05-06 16:46:55,329 : INFO : saving vocabulary of 2 words to C:\Users\hp\AppData\Local\Temp\corpus.lda-c.vocab
2019-05-06 16:46:55,332 : INFO : saving BleiCorpus index to C:\Users\hp\AppData\Local\Temp\corpus.lda-c.index通過這種方式,gensim也可以用作內存高效的I / O格式轉換工具:只需使用一種格式加載文檔流,然後立即以另一種格式進行保存。
四、與NumPy、SciPy的兼容性Gensim還囊括許多高效且實用的函數,可以在(http://radimrehurek.com/gensim/matutils.html) 看到,通過這些函數,我們可以輕鬆的進行numpy矩陣的轉換:
import gensimimport numpy as npnumpy_matrix = np.random.randint(10, size=[5,2])array([[0, 4],
[0, 7],
[8, 2],
[7, 0],
[2, 1]])corpus = gensim.matutils.Dense2Corpus(numpy_matrix)numpy_matrix_dense = gensim.matutils.corpus2dense(corpus, num_terms=10)D:\anaconda20190415\lib\site-packages\gensim\matutils.py:503: FutureWarning: arrays to stack must be passed as a "sequence" type such as list or tuple. Support for non-sequence iterables such as generators is deprecated as of NumPy 1.16 and will raise an error in the future.
result = np.column_stack(sparse2full(doc, num_terms) for doc in corpus)array([[0., 4.],
[0., 7.],
[8., 2.],
[7., 0.],
[2., 1.],
[0., 0.],
[0., 0.],
[0., 0.],
[0., 0.],
[0., 0.]], dtype=float32)與scipy.sparse矩陣相互轉換:
import scipy.sparsescipy_sparse_matrix = scipy.sparse.random(5,2)<5x2 sparse matrix of type '<class 'numpy.float64'>'
with 0 stored elements in COOrdinate format>corpus = gensim.matutils.Sparse2Corpus(scipy_sparse_matrix)<gensim.matutils.Sparse2Corpus at 0x160c65759e8>
scipy_csc_matrix = gensim.matutils.corpus2csc(corpus)<0x2 sparse matrix of type '<class 'numpy.float64'>'
with 0 stored elements in Compressed Sparse Column format>要獲得完整的參考(想要將字典的規模精簡下以節約內存?優化語料庫和NumPy / SciPy數組之間的轉換?),請參閱gensim的API文檔。
在下一篇文章中,筆者會接著本次的主題,說說關於主題模型和文本數據轉換,即TF-IDF模型、潛在語義索引(LSI)、隨機映射(Random Projections)、隱狄利克雷分配模型(Latent Dirichlet Allocation, LDA)、層次狄利克雷過程(Hierarchical Dirichlet Process,HDP)的教程。
註:以上內容大部分來自gensim的英文文檔,筆者只是用中文語料進行了新的詮釋,後續還會有更多的內容,筆者將不定期更新,動力來自於讀者的熱情,想讓筆者持續更新的請在下方留言,可以說說自己感興趣的點,比如文本聚類和文本分類...
- End -
發求職介紹,聯繫小編!
發內推職位,聯繫小編!
直播分享經驗,聯繫小編!
加群交流(禁廣告),聯繫小編!
微信L23683716