自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

基于Python的簡(jiǎn)單自然語(yǔ)言處理實(shí)踐

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

基于 Python 的簡(jiǎn)單自然語(yǔ)言處理

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

Twenty News Group 語(yǔ)料集處理

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

  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. # 實(shí)例化對(duì)象 
  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)分類(lèi)""->",[ 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)分類(lèi) -> ['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'

接下來(lái)我們可以對(duì)語(yǔ)料集中的特征進(jìn)行提?。?/p>

  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. # 查看某個(gè)詞在詞表中的下標(biāo) 
  14. print("詞對(duì)應(yīng)下標(biāo)","->", count_vect.vocabulary_.get(u'algorithm')) 
  15.  
  16. DTM 結(jié)構(gòu) -> (11314, 130107) 
  17. 詞對(duì)應(yīng)下標(biāo) -> 27366 

為了將文檔用于進(jìn)行分類(lèi)任務(wù),還需要使用 TF-IDF 等常見(jiàn)方法將其轉(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 

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

  1. def extract_feature(self): 
  2.         ""
  3.         從語(yǔ)料集中抽取文檔特征 
  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)練出分類(lèi)器 
  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)練出分類(lèi)器 
  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ù)測(cè)與評(píng)價(jià):

  1. # 訓(xùn)練分類(lèi)器 
  2. twp.train_classifier() 
  3.  
  4. # 執(zhí)行預(yù)測(cè) 
  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í)行模型評(píng)測(cè) 
  12. twp.fetch_data(subset='test'
  13.  
  14. predicted = twp.predict(twp.data['test'].data) 
  15.  
  16. import numpy as np 
  17.  
  18. # 誤差計(jì)算 
  19.  
  20. # 簡(jiǎn)單誤差均值 
  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]]) 

我們也可以對(duì)文檔集進(jìn)行主題提?。?/p>

# 進(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 

常見(jiàn)自然語(yǔ)言處理工具封裝

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

  1. class Wiki(object): 
  2.     ""
  3.     維基百科語(yǔ)料集處理 
  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("請(qǐng)輸入 Wiki 壓縮文件路徑或者前往 https://dumps.wikimedia.org/zhwiki/ 下載"
  14.             exit() 
  15.  
  16.         # 構(gòu)建維基語(yǔ)料集 
  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("處理完畢,請(qǐng)使用 OpenCC 轉(zhuǎn)化為簡(jiǎn)體字"

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

  1. class CorpusProcessor: 
  2.     ""
  3.     語(yǔ)料集處理 
  4.     ""
  5.  
  6.     def corpus2bow(self, tokenized_corpus=default_documents): 
  7.         """returns (vocab,corpus_in_bow) 
  8.         將語(yǔ)料集轉(zhuǎn)化為 BOW 形式 
  9.         Arguments: 
  10.         tokenized_corpus -- 經(jīng)過(guò)分詞的文檔列表 
  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.         將語(yǔ)料集轉(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)建語(yǔ)料集統(tǒng)計(jì)向量 
  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.         # 對(duì)于數(shù)據(jù)進(jìn)行分析 
  53.         DTM = vec.fit_transform(documents) 
  54.  
  55.         # 獲取詞表 
  56.         vocab = vec.get_feature_names() 
  57.  
  58.         return (vocab, DTM) 

我們也可以對(duì)分詞之后的文檔進(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)過(guò)分詞的文件并且對(duì)其進(jìn)行 LDA 訓(xùn)練 
  4.         Arguments: 
  5.         tokenized_corpus_path -> string -- 經(jīng)過(guò)分詞的語(yǔ)料集地址 
  6.         num_topics -> integer -- 主題數(shù)目 
  7.         num_words -> integer -- 主題詞數(shù)目 
  8.         max_lines -> integer -- 每次讀入的***行數(shù) 
  9.         split -> string -- 文檔的詞之間的分隔符 
  10.         max_df -> integer -- 避免常用詞,過(guò)濾超過(guò)該閾值的詞 
  11.         ""
  12.  
  13.         # 存放所有語(yǔ)料集信息 
  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)容添加到語(yǔ)料集中 
  27.                 corpus.append(re.split(split, document)) 
  28.  
  29.                 flag = flag + 1 
  30.  
  31.         # 構(gòu)建語(yǔ)料集的 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)用,傳入分詞之后的文件。我們也可以對(duì)其語(yǔ)料集建立詞向量,代碼參考這里;如果對(duì)于詞向量基本使用尚不熟悉的同學(xué)可以參考基于 Gensim 的 Word2Vec 實(shí)踐:

  1. def wv_train(self, tokenized_text_path, output_model_path='./wv_model.bin'): 
  2.        ""
  3.        對(duì)于文本進(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=["中國(guó)""航空"]): 
  15.        ""
  16.        根據(jù)輸入的詞搜索鄰近詞然后可視化展示 
  17.        參數(shù): 
  18.            model_path: Word2Vec 模型地址 
  19.        ""
  20.  
  21.        # 加載模型 
  22.        model = word2vec.Word2Vec.load(model_path) 
  23.  
  24.        # 尋找出最相似的多個(gè)詞 
  25.        words = [wp[0] for wp in model.most_similar(word, topn=20)] 
  26.  
  27.        # 提取出詞對(duì)應(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.        # 遍歷所有的詞添加點(diǎn)注釋 
  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()

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

戳這里,看該作者更多好文

責(zé)任編輯:武曉燕 來(lái)源: 51CTO專(zhuān)欄
相關(guān)推薦

2020-04-24 10:53:08

自然語(yǔ)言處理NLP是人工智能

2021-11-12 15:43:10

Python自然語(yǔ)言數(shù)據(jù)

2021-05-13 07:17:13

Snownlp自然語(yǔ)言處理庫(kù)

2017-10-19 17:05:58

深度學(xué)習(xí)自然語(yǔ)言

2024-04-24 11:38:46

語(yǔ)言模型NLP人工智能

2024-02-05 14:18:07

自然語(yǔ)言處理

2021-05-17 09:00:00

自然語(yǔ)言人工智能技術(shù)

2020-11-12 18:57:14

摘要PythonNLP

2017-05-05 15:34:49

自然語(yǔ)言處理

2020-02-25 12:00:53

自然語(yǔ)言開(kāi)源工具

2020-02-25 23:28:50

工具代碼開(kāi)發(fā)

2025-01-26 12:34:46

AI運(yùn)維配置

2021-05-18 07:15:37

Python

2020-08-30 14:26:30

自然語(yǔ)言處理書(shū)籍NLP

2024-11-07 15:49:34

2017-04-10 16:15:55

人工智能深度學(xué)習(xí)應(yīng)用

2020-09-23 10:45:45

人工智能自然語(yǔ)言NLP

2021-03-03 09:00:00

自然語(yǔ)言數(shù)據(jù)科學(xué)人工智能

2018-02-27 09:32:13

神經(jīng)網(wǎng)絡(luò)自然語(yǔ)言初探

2021-09-03 12:01:07

模型自然語(yǔ)言
點(diǎn)贊
收藏

51CTO技術(shù)棧公眾號(hào)