日本综合一区二区|亚洲中文天堂综合|日韩欧美自拍一区|男女精品天堂一区|欧美自拍第6页亚洲成人精品一区|亚洲黄色天堂一区二区成人|超碰91偷拍第一页|日韩av夜夜嗨中文字幕|久久蜜综合视频官网|精美人妻一区二区三区

RELATEED CONSULTING
相關(guān)咨詢
選擇下列產(chǎn)品馬上在線溝通
服務(wù)時間:8:30-17:00
你可能遇到了下面的問題
關(guān)閉右側(cè)工具欄

新聞中心

這里有您想知道的互聯(lián)網(wǎng)營銷解決方案
基于Python的簡單自然語言處理實踐

基于 Python 的簡單自然語言處理

成都創(chuàng)新互聯(lián)是專業(yè)的召陵網(wǎng)站建設(shè)公司,召陵接單;提供網(wǎng)站建設(shè)、成都網(wǎng)站設(shè)計,網(wǎng)頁設(shè)計,網(wǎng)站設(shè)計,建網(wǎng)站,PHP網(wǎng)站建設(shè)等專業(yè)做網(wǎng)站服務(wù);采用PHP框架,可快速的進(jìn)行召陵網(wǎng)站開發(fā)網(wǎng)頁制作和功能擴(kuò)展;專業(yè)做搜索引擎喜愛的網(wǎng)站,專業(yè)的做網(wǎng)站團(tuán)隊,希望更多企業(yè)前來合作!

本文是對于基于 Python 進(jìn)行簡單自然語言處理任務(wù)的介紹,本文的所有代碼放置在這里。建議前置閱讀 Python 語法速覽與機器學(xué)習(xí)開發(fā)環(huán)境搭建,更多機器學(xué)習(xí)資料參考機器學(xué)習(xí)、深度學(xué)習(xí)與自然語言處理領(lǐng)域推薦的書籍列表以及面向程序猿的數(shù)據(jù)科學(xué)與機器學(xué)習(xí)知識體系及資料合集。

Twenty News Group 語料集處理

20 Newsgroup 數(shù)據(jù)集包含了約 20000 篇來自于不同的新聞組的文檔,最早由 Ken Lang 搜集整理。本部分包含了對于數(shù)據(jù)集的抓取、特征提取、簡單分類器訓(xùn)練、主題模型訓(xùn)練等。本部分代碼包括主要的處理代碼封裝庫與基于 Notebook 的交互示范。我們首先需要進(jìn)行數(shù)據(jù)抓?。?/p>

 
 
 
 
  1. def fetch_data(self, subset='train', categories=None): 
  2.        """return data 
  3.        執(zhí)行數(shù)據(jù)抓取操作 
  4.        Arguments: 
  5.        subset -> string -- 抓取的目標(biāo)集合 train / test / all 
  6.        """ 
  7.        rand = np.random.mtrand.RandomState(8675309) 
  8.        data = fetch_20newsgroups(subset=subset, 
  9.                                  categories=categories, 
  10.                                  shuffle=True, 
  11.                                  random_state=rand) 
  12.  
  13.        self.data[subset] = data 

然后在 Notebook 中交互查看數(shù)據(jù)格式:

 
 
 
 
  1. # 實例化對象 
  2. twp = TwentyNewsGroup() 
  3. # 抓取數(shù)據(jù) 
  4. twp.fetch_data() 
  5. twenty_train = twp.data['train'] 
  6. print("數(shù)據(jù)集結(jié)構(gòu)", "->", twenty_train.keys()) 
  7. print("文檔數(shù)目", "->", len(twenty_train.data)) 
  8. print("目標(biāo)分類", "->",[ twenty_train.target_names[t] for t in twenty_train.target[:10]]) 
  9.  
  10. 數(shù)據(jù)集結(jié)構(gòu) -> dict_keys(['data', 'filenames', 'target_names', 'target', 'DESCR', 'description']) 
  11. 文檔數(shù)目 -> 11314 
  12. 目標(biāo)分類 -> ['sci.space', 'comp.sys.mac.hardware', 'sci.electronics', 'comp.sys.mac.hardware', 'sci.space', 'rec.sport.hockey', 'talk.religion.misc', 'sci.med', 'talk.religion.misc', 'talk.politics.guns'] 

接下來我們可以對語料集中的特征進(jìn)行提取:

 
 
 
 
  1. # 進(jìn)行特征提取 
  2.  
  3. # 構(gòu)建文檔-詞矩陣(Document-Term Matrix) 
  4.  
  5. from sklearn.feature_extraction.text import CountVectorizer 
  6.  
  7. count_vect = CountVectorizer() 
  8.  
  9. X_train_counts = count_vect.fit_transform(twenty_train.data) 
  10.  
  11. print("DTM 結(jié)構(gòu)","->",X_train_counts.shape) 
  12.  
  13. # 查看某個詞在詞表中的下標(biāo) 
  14. print("詞對應(yīng)下標(biāo)","->", count_vect.vocabulary_.get(u'algorithm')) 
  15.  
  16. DTM 結(jié)構(gòu) -> (11314, 130107) 
  17. 詞對應(yīng)下標(biāo) -> 27366 

為了將文檔用于進(jìn)行分類任務(wù),還需要使用 TF-IDF 等常見方法將其轉(zhuǎn)化為特征向量:

 
 
 
 
  1. # 構(gòu)建文檔的 TF 特征向量 
  2. from sklearn.feature_extraction.text import TfidfTransformer 
  3.  
  4. tf_transformer = TfidfTransformer(use_idf=False).fit(X_train_counts) 
  5. X_train_tf = tf_transformer.transform(X_train_counts) 
  6.  
  7. print("某文檔 TF 特征向量","->",X_train_tf) 
  8.  
  9. # 構(gòu)建文檔的 TF-IDF 特征向量 
  10. from sklearn.feature_extraction.text import TfidfTransformer 
  11.  
  12. tf_transformer = TfidfTransformer().fit(X_train_counts) 
  13. X_train_tfidf = tf_transformer.transform(X_train_counts) 
  14.  
  15. print("某文檔 TF-IDF 特征向量","->",X_train_tfidf) 
  16.  
  17. 某文檔 TF 特征向量 ->   (0, 6447)    0.0380693493813 
  18.   (0, 37842)    0.0380693493813 

我們可以將特征提取、分類器訓(xùn)練與預(yù)測封裝為單獨函數(shù):

 
 
 
 
  1. def extract_feature(self): 
  2.         """ 
  3.         從語料集中抽取文檔特征 
  4.         """ 
  5.  
  6.         # 獲取訓(xùn)練數(shù)據(jù)的文檔-詞矩陣 
  7.         self.train_dtm = self.count_vect.fit_transform(self.data['train'].data) 
  8.  
  9.         # 獲取文檔的 TF 特征 
  10.  
  11.         tf_transformer = TfidfTransformer(use_idf=False) 
  12.  
  13.         self.train_tf = tf_transformer.transform(self.train_dtm) 
  14.  
  15.         # 獲取文檔的 TF-IDF 特征 
  16.  
  17.         tfidf_transformer = TfidfTransformer().fit(self.train_dtm) 
  18.  
  19.         self.train_tfidf = tf_transformer.transform(self.train_dtm) 
  20.  
  21.     def train_classifier(self): 
  22.         """ 
  23.         從訓(xùn)練集中訓(xùn)練出分類器 
  24.         """ 
  25.  
  26.         self.extract_feature(); 
  27.  
  28.         self.clf = MultinomialNB().fit( 
  29.             self.train_tfidf, self.data['train'].target) 
  30.  
  31.     def predict(self, docs): 
  32.         """ 
  33.         從訓(xùn)練集中訓(xùn)練出分類器 
  34.         """ 
  35.  
  36.         X_new_counts = self.count_vect.transform(docs) 
  37.  
  38.         tfidf_transformer = TfidfTransformer().fit(X_new_counts) 
  39.          
  40.         X_new_tfidf = tfidf_transformer.transform(X_new_counts) 
  41.  
  42.         return self.clf.predict(X_new_tfidf) 

然后執(zhí)行訓(xùn)練并且進(jìn)行預(yù)測與評價:

 
 
 
 
  1. # 訓(xùn)練分類器 
  2. twp.train_classifier() 
  3.  
  4. # 執(zhí)行預(yù)測 
  5. docs_new = ['God is love', 'OpenGL on the GPU is fast'] 
  6. predicted = twp.predict(docs_new) 
  7.  
  8. for doc, category in zip(docs_new, predicted): 
  9.     print('%r => %s' % (doc, twenty_train.target_names[category])) 
  10.      
  11. # 執(zhí)行模型評測 
  12. twp.fetch_data(subset='test') 
  13.  
  14. predicted = twp.predict(twp.data['test'].data) 
  15.  
  16. import numpy as np 
  17.  
  18. # 誤差計算 
  19.  
  20. # 簡單誤差均值 
  21. np.mean(predicted == twp.data['test'].target)    
  22.  
  23. # Metrics 
  24.  
  25. from sklearn import metrics 
  26.  
  27. print(metrics.classification_report( 
  28.     twp.data['test'].target, predicted, 
  29.     target_names=twp.data['test'].target_names)) 
  30.  
  31. # Confusion Matrix 
  32. metrics.confusion_matrix(twp.data['test'].target, predicted) 
  33.  
  34. 'God is love' => soc.religion.christian 
  35. 'OpenGL on the GPU is fast' => rec.autos 
  36.                           precision    recall  f1-score   support 
  37.  
  38.              alt.atheism       0.79      0.50      0.61       319 
  39.            ... 
  40.       talk.religion.misc       1.00      0.08      0.15       251 
  41.  
  42.              avg / total       0.82      0.79      0.77      7532 
  43.  
  44. Out[16]: 
  45. array([[158,   0,   1,   1,   0,   1,   0,   3,   7,   1,   2,   6,   1, 
  46.           8,   3, 114,   6,   7,   0,   0], 
  47.        ... 
  48.        [ 35,   3,   1,   0,   0,   0,   1,   4,   1,   1,   6,   3,   0, 
  49.           6,   5, 127,  30,   5,   2,  21]]) 

我們也可以對文檔集進(jìn)行主題提取:

# 進(jìn)行主題提取

 
 
 
 
  1. # 進(jìn)行主題提取 
  2.  
  3. twp.topics_by_lda() 
  4.  
  5. Topic 0 : stream s1 astronaut zoo laurentian maynard s2 gtoal pem fpu 
  6. Topic 1 : 145 cx 0d bh sl 75u 6um m6 sy gld 
  7. Topic 2 : apartment wpi mars nazis monash palestine ottoman sas winner gerard 
  8. Topic 3 : livesey contest satellite tamu mathew orbital wpd marriage solntze pope 
  9. Topic 4 : x11 contest lib font string contrib visual xterm ahl brake 
  10. Topic 5 : ax g9v b8f a86 1d9 pl 0t wm 34u giz 
  11. Topic 6 : printf null char manes behanna senate handgun civilians homicides magpie 
  12. Topic 7 : buf jpeg chi tor bos det que uwo pit blah 
  13. Topic 8 : oracle di t4 risc nist instruction msg postscript dma convex 
  14. Topic 9 : candida cray yeast viking dog venus bloom symptoms observatory roby 
  15. Topic 10 : cx ck hz lk mv cramer adl optilink k8 uw 
  16. Topic 11 : ripem rsa sandvik w0 bosnia psuvm hudson utk defensive veal 
  17. Topic 12 : db espn sabbath br widgets liar davidian urartu sdpa cooling 
  18. Topic 13 : ripem dyer ucsu carleton adaptec tires chem alchemy lockheed rsa 
  19. Topic 14 : ingr sv alomar jupiter borland het intergraph factory paradox captain 
  20. Topic 15 : militia palestinian cpr pts handheld sharks igc apc jake lehigh 
  21. Topic 16 : alaska duke col russia uoknor aurora princeton nsmca gene stereo 
  22. Topic 17 : uuencode msg helmet eos satan dseg homosexual ics gear pyron 
  23. Topic 18 : entries myers x11r4 radar remark cipher maine hamburg senior bontchev 
  24. Topic 19 : cubs ufl vitamin temple gsfc mccall astro bellcore uranium wesleyan 

常見自然語言處理工具封裝

經(jīng)過上面對于 20NewsGroup 語料集處理的介紹我們可以發(fā)現(xiàn)常見自然語言處理任務(wù)包括,數(shù)據(jù)獲取、數(shù)據(jù)預(yù)處理、數(shù)據(jù)特征提取、分類模型訓(xùn)練、主題模型或者詞向量等高級特征提取等等。筆者還習(xí)慣用 python-fire 將類快速封裝為可通過命令行調(diào)用的工具,同時也支持外部模塊調(diào)用使用。本部分我們主要以中文語料集為例,譬如我們需要對中文維基百科數(shù)據(jù)進(jìn)行分析,可以使用 gensim 中的維基百科處理類:

 
 
 
 
  1. class Wiki(object): 
  2.     """ 
  3.     維基百科語料集處理 
  4.     """ 
  5.      
  6.     def wiki2texts(self, wiki_data_path, wiki_texts_path='./wiki_texts.txt'): 
  7.         """ 
  8.         將維基百科數(shù)據(jù)轉(zhuǎn)化為文本數(shù)據(jù) 
  9.         Arguments: 
  10.         wiki_data_path -- 維基壓縮文件地址 
  11.         """ 
  12.         if not wiki_data_path: 
  13.             print("請輸入 Wiki 壓縮文件路徑或者前往 https://dumps.wikimedia.org/zhwiki/ 下載") 
  14.             exit() 
  15.  
  16.         # 構(gòu)建維基語料集 
  17.         wiki_corpus = WikiCorpus(wiki_data_path, dictionary={}) 
  18.         texts_num = 0 
  19.  
  20.         with open(wiki_text_path, 'w', encoding='utf-8') as output: 
  21.             for text in wiki_corpus.get_texts(): 
  22.                 output.write(b' '.join(text).decode('utf-8') + '\n') 
  23.                 texts_num += 1 
  24.                 if texts_num % 10000 == 0: 
  25.                     logging.info("已處理 %d 篇文章" % texts_num) 
  26.  
  27.         print("處理完畢,請使用 OpenCC 轉(zhuǎn)化為簡體字") 

抓取完畢后,我們還需要用 OpenCC 轉(zhuǎn)化為簡體字。抓取完畢后我們可以使用結(jié)巴分詞對生成的文本文件進(jìn)行分詞,代碼參考這里,我們直接使用 python chinese_text_processor.py tokenize_file /output.txt 直接執(zhí)行該任務(wù)并且生成輸出文件。獲取分詞之后的文件,我們可以將其轉(zhuǎn)化為簡單的詞袋表示或者文檔-詞向量,詳細(xì)代碼參考這里:

 
 
 
 
  1. class CorpusProcessor: 
  2.     """ 
  3.     語料集處理 
  4.     """ 
  5.  
  6.     def corpus2bow(self, tokenized_corpus=default_documents): 
  7.         """returns (vocab,corpus_in_bow) 
  8.         將語料集轉(zhuǎn)化為 BOW 形式 
  9.         Arguments: 
  10.         tokenized_corpus -- 經(jīng)過分詞的文檔列表 
  11.         Return: 
  12.         vocab -- {'human': 0, ... 'minors': 11} 
  13.         corpus_in_bow -- [[(0, 1), (1, 1), (2, 1)]...] 
  14.         """ 
  15.         dictionary = corpora.Dictionary(tokenized_corpus) 
  16.  
  17.         # 獲取詞表 
  18.         vocab = dictionary.token2id 
  19.  
  20.         # 獲取文檔的詞袋表示 
  21.         corpus_in_bow = [dictionary.doc2bow(text) for text in tokenized_corpus] 
  22.  
  23.         return (vocab, corpus_in_bow) 
  24.  
  25.     def corpus2dtm(self, tokenized_corpus=default_documents, min_df=10, max_df=100): 
  26.         """returns (vocab, DTM) 
  27.         將語料集轉(zhuǎn)化為文檔-詞矩陣 
  28.         - dtm -> matrix: 文檔-詞矩陣 
  29.                 I    like    hate    databases 
  30.         D1    1      1          0            1 
  31.         D2    1      0          1            1 
  32.         """ 
  33.  
  34.         if type(tokenized_corpus[0]) is list: 
  35.             documents = [" ".join(document) for document in tokenized_corpus] 
  36.         else: 
  37.             documents = tokenized_corpus 
  38.  
  39.         if max_df == -1: 
  40.             max_df = round(len(documents) / 2) 
  41.  
  42.         # 構(gòu)建語料集統(tǒng)計向量 
  43.         vec = CountVectorizer(min_df=min_df, 
  44.                               max_df=max_df, 
  45.                               analyzer="word", 
  46.                               token_pattern="[\S]+", 
  47.                               tokenizer=None, 
  48.                               preprocessor=None, 
  49.                               stop_words=None 
  50.                               ) 
  51.  
  52.         # 對于數(shù)據(jù)進(jìn)行分析 
  53.         DTM = vec.fit_transform(documents) 
  54.  
  55.         # 獲取詞表 
  56.         vocab = vec.get_feature_names() 
  57.  
  58.         return (vocab, DTM) 

我們也可以對分詞之后的文檔進(jìn)行主題模型或者詞向量提取,這里使用分詞之后的文件就可以忽略中英文的差異:

 
 
 
 
  1. def topics_by_lda(self, tokenized_corpus_path, num_topics=20, num_words=10, max_lines=10000, split="\s+", max_df=100): 
  2.         """ 
  3.         讀入經(jīng)過分詞的文件并且對其進(jìn)行 LDA 訓(xùn)練 
  4.         Arguments: 
  5.         tokenized_corpus_path -> string -- 經(jīng)過分詞的語料集地址 
  6.         num_topics -> integer -- 主題數(shù)目 
  7.         num_words -> integer -- 主題詞數(shù)目 
  8.         max_lines -> integer -- 每次讀入的***行數(shù) 
  9.         split -> string -- 文檔的詞之間的分隔符 
  10.         max_df -> integer -- 避免常用詞,過濾超過該閾值的詞 
  11.         """ 
  12.  
  13.         # 存放所有語料集信息 
  14.         corpus = [] 
  15.  
  16.         with open(tokenized_corpus_path, 'r', encoding='utf-8') as tokenized_corpus: 
  17.  
  18.             flag = 0 
  19.  
  20.             for document in tokenized_corpus: 
  21.  
  22.                 # 判斷是否讀取了足夠的行數(shù) 
  23.                 if(flag > max_lines): 
  24.                     break 
  25.  
  26.                 # 將讀取到的內(nèi)容添加到語料集中 
  27.                 corpus.append(re.split(split, document)) 
  28.  
  29.                 flag = flag + 1 
  30.  
  31.         # 構(gòu)建語料集的 BOW 表示 
  32.         (vocab, DTM) = self.corpus2dtm(corpus, max_df=max_df) 
  33.  
  34.         # 訓(xùn)練 LDA 模型 
  35.  
  36.         lda = LdaMulticore( 
  37.             matutils.Sparse2Corpus(DTM, documents_columns=False), 
  38.             num_topics=num_topics, 
  39.             id2word=dict([(i, s) for i, s in enumerate(vocab)]), 
  40.             workers=4 
  41.         ) 
  42.  
  43.         # 打印并且返回主題數(shù)據(jù) 
  44.         topics = lda.show_topics( 
  45.             num_topics=num_topics, 
  46.             num_words=num_words, 
  47.             formatted=False, 
  48.             log=False) 
  49.  
  50.         for ti, topic in enumerate(topics): 
  51.             print("Topic", ti, ":", " ".join(word[0] for word in topic[1])) 

該函數(shù)同樣可以使用命令行直接調(diào)用,傳入分詞之后的文件。我們也可以對其語料集建立詞向量,代碼參考這里;如果對于詞向量基本使用尚不熟悉的同學(xué)可以參考基于 Gensim 的 Word2Vec 實踐:

 
 
 
 
  1. def wv_train(self, tokenized_text_path, output_model_path='./wv_model.bin'): 
  2.        """ 
  3.        對于文本進(jìn)行詞向量訓(xùn)練,并將輸出的詞向量保存 
  4.        """ 
  5.  
  6.        sentences = word2vec.Text8Corpus(tokenized_text_path) 
  7.  
  8.        # 進(jìn)行模型訓(xùn)練 
  9.        model = word2vec.Word2Vec(sentences, size=250) 
  10.  
  11.        # 保存模型 
  12.        model.save(output_model_path) 
  13.  
  14.    def wv_visualize(self, model_path, word=["中國", "航空"]): 
  15.        """ 
  16.        根據(jù)輸入的詞搜索鄰近詞然后可視化展示 
  17.        參數(shù): 
  18.            model_path: Word2Vec 模型地址 
  19.        """ 
  20.  
  21.        # 加載模型 
  22.        model = word2vec.Word2Vec.load(model_path) 
  23.  
  24.        # 尋找出最相似的多個詞 
  25.        words = [wp[0] for wp in model.most_similar(word, topn=20)] 
  26.  
  27.        # 提取出詞對應(yīng)的詞向量 
  28.        wordsInVector = [model[word] for word in words] 
  29.  
  30.        # 進(jìn)行 PCA 降維 
  31.        pca = PCA(n_components=2) 
  32.        pca.fit(wordsInVector) 
  33.        X = pca.transform(wordsInVector) 
  34.  
  35.        # 繪制圖形 
  36.        xs = X[:, 0] 
  37.        ys = X[:, 1] 
  38.  
  39.        plt.figure(figsize=(12, 8)) 
  40.        plt.scatter(xs, ys, marker='o') 
  41.  
  42.        # 遍歷所有的詞添加點注釋 
  43.        for i, w in enumerate(words): 
  44.            plt.annotate( 
  45.                w, 
  46.                xy=(xs[i], ys[i]), xytext=(6, 6), 
  47.                textcoords='offset points', ha='left', va='top', 
  48.                **dict(fontsize=10) 
  49.            ) 
  50.        plt.show()

【本文是專欄作者“張梓雄 ”的原創(chuàng)文章,如需轉(zhuǎn)載請通過與作者聯(lián)系】


本文標(biāo)題:基于Python的簡單自然語言處理實踐
地址分享:http://www.dlmjj.cn/article/cohojep.html