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

用TextRank算法實(shí)現(xiàn)自動文本摘要

譯文
開發(fā) 后端 算法
通過本文,我們將探討文本摘要所涉及的領(lǐng)域,了解 TextRank 算法的工作原理,并用 Python 實(shí)現(xiàn)該算法。

【51CTO.com快譯】1. 引言

文本摘要是自然語言處理(NLP)領(lǐng)域中的應(yīng)用之一,它必將對我們的生活產(chǎn)生巨大影響。隨著數(shù)字媒體和出 版業(yè)的不斷發(fā)展,誰還有時間瀏覽整篇文章/文檔/書籍來決定它們是否有用?值得慶幸的是 - 我們已經(jīng)有了 文本摘要技術(shù)。

您是否用過一款名為 inshorts 的移動 APP?這是一個非常有創(chuàng)意的新聞 APP,能將新聞文章轉(zhuǎn)換為 60 字的 摘要。這正是我們將在本文中學(xué)習(xí)的內(nèi)容 - 自動文本摘要。

用TextRank算法實(shí)現(xiàn)自動文本摘要

自動文本摘要是自然語言處理(NLP)領(lǐng)域中***挑戰(zhàn)性和最有趣的問題之一。這是一個從多種文本資源(如 書籍,新聞文章,博客文章,研究論文,電子郵件和推文)生成簡明而有意義的文本摘要的過程。

由于我們面臨著大量的文本數(shù)據(jù),近來對自動文本摘要系統(tǒng)的需求十分驚人。

通過本文,我們將探討文本摘要所涉及的領(lǐng)域,了解 TextRank 算法的工作原理,并用 Python 實(shí)現(xiàn)該算法。

2. 文本摘要方法

自動文本摘要早在 20 世紀(jì) 50 年代就引起了人們的關(guān)注。由 Hans Peter Luhn 在 20 世紀(jì) 50 年代末出版的題 為“文學(xué)摘要的自動創(chuàng)建”的研究論文,使用詞頻和短語頻率等特征從文本中提取重要句子以概括文章。

Harold P Edmundson 在 1960 年代后期進(jìn)行的另一項(xiàng)重要研究使用了諸如句中是否包含關(guān)鍵詞、文本中是否 出現(xiàn)標(biāo)題所含單詞以及句子在文本中的位置等方法提取重要句子來生成文本摘要。從那時起,許多重要且令 人興奮的研究陸續(xù)發(fā)表,以應(yīng)對自動文本摘要領(lǐng)域的挑戰(zhàn)。

文本摘要大致可以分為兩類 - 抽取摘要和抽象摘要。

  1. 抽取摘要:這些方法依賴于從一段文本中提取幾個部分,例如短語和句子,并將它們堆疊在一起以創(chuàng)建 摘要。因此,在提取方法中識別正確的摘要句子是至關(guān)重要的。
  2. 抽象摘要:這些方法使用高級 NLP 技術(shù)生成全新的摘要。這些摘要的某些部分甚至可能沒有在原始文 本中出現(xiàn)。

在本文中,我們將重點(diǎn)介紹抽取摘要技術(shù)。

3. 理解 TextRank 算法

在開始使用 TextRank 算法之前,我們應(yīng)該了解另一種算法 - PageRank 算法。事實(shí)上,TextRank 算法也是 在此基礎(chǔ)上開發(fā)的!PageRank 主要用于在網(wǎng)頁搜索結(jié)果中對網(wǎng)頁進(jìn)行排名。讓我們借助一個例子快速理解這 個算法的基礎(chǔ)知識。

3.1. PageRank 算法

假設(shè)我們有 4 個網(wǎng)頁 - w1,w2,w3 和 w4。這些網(wǎng)頁包含指向其它網(wǎng)頁的鏈接。但其中有些頁面可能沒有指 向其它網(wǎng)頁的鏈接 - 這些網(wǎng)頁被稱為懸空頁面(dangling pages)。

  • 網(wǎng)頁 w1 有指向網(wǎng)頁 w2 和 w4 的鏈接
  • 網(wǎng)頁 w2 有指向網(wǎng)頁 w3 和 w1 的鏈接
  • 網(wǎng)頁 w4 有指向網(wǎng)頁 w1 的鏈接
  • 網(wǎng)頁 w3 沒有指向其它網(wǎng)頁的鏈接,因此它是一個懸空網(wǎng)頁(dangling page)

為了對這些頁面進(jìn)行排名,我們必須計(jì)算一個稱為 PageRank score 的分?jǐn)?shù)。該分?jǐn)?shù)是用戶訪問該頁面的概率。 為了獲得用戶從一個頁面跳轉(zhuǎn)到另一個頁面的概率,我們創(chuàng)建一個 n 行 n 列的方陣 M,其中 n 是網(wǎng)頁的數(shù)量。

該矩陣的每個元素表示用戶從一個網(wǎng)頁跳轉(zhuǎn)到另一個網(wǎng)頁的概率。例如,下圖高亮的單元格表示從網(wǎng)頁 w1 跳 轉(zhuǎn)到網(wǎng)頁 w2 的概率。

網(wǎng)頁跳轉(zhuǎn)概率的初始化方法如下:

  1. 從頁面 i 跳轉(zhuǎn)到頁面 j 的概率,即 M[i][j] ,用 1 /(網(wǎng)頁 wi 中的不重復(fù)的總鏈接數(shù))初始化
  2. 如果頁面 i 和 j 之間沒有鏈接,則概率將初始化為 0
  3. 如果用戶訪問的是懸空頁面,則假設(shè)他跳轉(zhuǎn)到其它任何頁面的概率都相等。因此,M[i][j] 將用 1 /(網(wǎng) 頁總數(shù))初始化

因此,在我們的例子中,矩陣 M 將初始化如下:

該矩陣中的值將不斷迭代更新,以進(jìn)行***的網(wǎng)頁排名。

4. TextRank 算法

在掌握了 PageRank 算法的基本思想后,現(xiàn)在讓我們來理解 TextRank 算法吧。我將兩種算法之間的關(guān)聯(lián)列 出如下:

  • 我們將研究的是句子,而不再是網(wǎng)頁
  • 兩個句子之間的相似度可以理解成網(wǎng)頁之間的跳轉(zhuǎn)概率
  • 句子間的相似度得分存儲在方陣中,類似于 PageRank 算法中的方陣 M

TextRank 算法是一種基于抽取和無監(jiān)督的文本摘要技術(shù)。讓我們來看看 TextRank 算法的流程:

  1. ***步是獲取文章中包含的所有文本。
  2. 然后將文本拆分成單個句子。
  3. 下一步是,找到每個句子的向量表示。
  4. 然后計(jì)算句子向量之間的相似度并將其存儲在矩陣中。 5. 然后將相似度矩陣轉(zhuǎn)換成圖,其中圖中頂點(diǎn)表示句子,圖中邊表示句子間的相似度,用于后續(xù)句子排名 的計(jì)算。
  5. ***,最終摘要中包含排名***的幾個句子。 所以,不用多說,讓我們啟動 Jupyter Notebook 開始編碼吧! 注意:如果您想學(xué)習(xí)有關(guān) Graph Theory 的更多內(nèi)容,那么我建議您查看這篇文章。

5. 問題描述

作為一個網(wǎng)球愛好者,我總是通過閱讀盡可能多的有關(guān)網(wǎng)球的在線文章來讓自己了解網(wǎng)球運(yùn)動中最近發(fā)生的 事情。然而,事實(shí)證明這是一項(xiàng)相當(dāng)困難的工作!因?yàn)榫W(wǎng)上的資源太多但是我的時間卻相當(dāng)有限。

因此,我決定設(shè)計(jì)一個系統(tǒng),可以通過掃描多篇文章然后為我提供一份文章摘要。怎樣去做這件事?這就是我 將在本教程中向您展示的內(nèi)容。我們將在一份網(wǎng)球文本數(shù)據(jù)集上運(yùn)用 TextRank 算法,目標(biāo)是為這些文本創(chuàng) 建一個簡潔明了的摘要。

請注意,這實(shí)際上是一個單領(lǐng)域多文檔的摘要任務(wù),即我們將多篇文章作為輸入并生成單個目標(biāo)主題的摘要。 本文不涉及多領(lǐng)域文本摘要,但您可以自己去了解相關(guān)內(nèi)容。

您可以從此處下載我們將使用的數(shù)據(jù)集。

6. TextRank 算法的實(shí)現(xiàn)

讓我們打開 Jupyter Notebooks,將剛才學(xué)到的東西實(shí)現(xiàn)出來吧。

6.1. 導(dǎo)入必要的庫

首先我們需要導(dǎo)入一些將要使用的庫: 

  1. import numpy as np  
  2. import pandas as pd  
  3. import nltk  
  4. nltk.download('punkt') # one time execution  
  5. import re  

6.2. 讀入數(shù)據(jù)

現(xiàn)在需要讀入數(shù)據(jù)集,我在前一個部分提供了該數(shù)據(jù)集的下載鏈接 (防止你沒有看見它) 

  1. df = pd.read_csv("tennis_articles_v4.csv"

6.3. 查看數(shù)據(jù)

我們快速瀏覽一下數(shù)據(jù)的大致樣子吧。 

  1. df.head() 

該數(shù)據(jù)集包含 3 列:“article_id”,“article_text”和“source”。我們對‘article_text’列最感興趣,因?yàn)樗? 含文章的文本。我們可以打印出變量的一些值,看看它們的樣子。 

  1. df['article_text'][0] 

輸出: 

  1. "Maria Sharapova has basically no friends as tennis players on the WTA Tour. The Russian player has no problems in openly speaking about it and in a recent interview she said: 'I don't really hide any feelings too much. I think everyone knows this is my job here. When I'm on the courts or when I'on the court playing, I'm a competitor and I want to beat every single person whether they're in the locker room or across the net... 

 

  1. df['article_text'][1] 

輸出: 

  1. BASEL, Switzerland (AP), Roger Federer advanced to the 14th Swiss Indoors final of his career by beating seventh-seeded Daniil Medvedev 6-1, 6-4 on Saturday. Seeking a ninth title at his hometown event, and a 99th overall, Federer will play 93th-ranked Marius Copil on Sunday. Federer dominated the 20th-ranked Medvedev and had his first match-point chance to break serve again at 5-1... 

現(xiàn)在我們有兩個選擇:我們可以單獨(dú)為每篇文章生成一個摘要,也可以為所有文章生成一個摘要??紤]我們的 問題需求,我們將做后者。

6.4. 將文本分成句子

接下來的步驟是將文本分成單個的句子,我們可以使用 nltk 庫中的 sent_tokenize() 函數(shù)。 

  1. from nltk.tokenize import sent_tokenize  
  2. sentences = []  
  3. for s in df['article_text']:  
  4.     sentences.append(sent_tokenize(s))  
  5. sentences = [y for x in sentences for y in x] # flatten list  

我們打印出 sentences 列表的一些元素: 

  1. sentences[:5] 

輸出: 

  1. ['Maria Sharapova has basically no friends as tennis players on the WTA Tour.'"The Russian player has no problems in openly speaking about it and in a recent interview she said: 'I don't really hide any feelings too much."'I think everyone knows this is my job here.'"When I'm on the courts or when I'm on the court playing, I'm a competitor and I want to beat every single person whether they're in the locker room or across the net.So I'm not the one to strike up a conversation about the weather and know that in the next few minutes I have to go and try to win a tennis match.""I'm a pretty competitive girl."

6.5. 下載 GloVe 詞向量

GloVe 詞向量是單詞的向量表示。這些單詞向量將用于后續(xù)創(chuàng)建句子向量。我們也可以使用 Bag-of-Words 或 TF-IDF 方法為我們的句子創(chuàng)建特征,但是這些方法忽略了單詞的順序(并且特征的數(shù)量通常非常大)。

我們將使用此處提供的預(yù)訓(xùn)練的 Wikipedia 2014 + Gigaword 5 GloVe 向量。注意,這些詞向量的大小為 822 MB。 

  1. !wget http://nlp.stanford.edu/data/glove.6B.zip  
  2. !unzip glove*.zip  

我們需要提取出詞向量: 

  1. # Extract word vectors  
  2. word_embeddings = {}  
  3. f = open('glove.6B.100d.txt', encoding='utf-8' 
  4. for line in f:  
  5.   values = line.split()  
  6.   word = values[0]  
  7.   coefs = np.asarray(values[1:], dtype='float32' 
  8.   word_embeddings[word] = coefs  
  9. f.close()  
  10. len(word_embeddings)  

輸出: 

  1. 400000 

我們現(xiàn)在已經(jīng)有了詞典中包含的 400000 個單詞的詞向量了。

6.6. 文本預(yù)處理

盡可能使文本數(shù)據(jù)沒有噪音始終是一種很好的做法。所以,讓我們做一些基本的文本清理工作。 

  1. # remove punctuations, numbers and special characters  
  2. clean_sentences = pd.Series(sentences).str.replace("[^a-zA-Z]"" " 
  3. # make alphabets lowercase  
  4. clean_sentences = [s.lower() for s in clean_sentences] 

 

去除停用詞(停用詞是一種語言中最常用的一些詞, 像英文中的 am, the, of, in 等)。如果您還沒有下載 nltkstopwords,請執(zhí)行以下代碼: 

  1. nltk.download('stopwords'

現(xiàn)在導(dǎo)入停用詞列表: 

  1. from nltk.corpus import stopwords  
  2. stop_words = stopwords.words('english' 

定義一個函數(shù)用于從我們的數(shù)據(jù)集中去除停用詞。 

  1. function to remove stopwords  
  2. def remove_stopwords(sen):  
  3.       sen_new = " ".join([i for i in sen if i not in stop_words])  
  4.       return sen_new  
  5. # remove stopwords from the sentences  
  6. clean_sentences = [remove_stopwords(r.split()) for r in clean_sentences]  

在 GloVe 詞向量的幫助下,我們將使用 clean_sentences 為我們數(shù)據(jù)中的句子創(chuàng)建向量。

6.7. 句子的向量表示 

  1. # Extract word vectors  
  2. word_embeddings = {}  
  3. f = open('glove.6B.100d.txt', encoding='utf-8' 
  4. for line in f:  
  5.     values = line.split()  
  6.     word = values[0]  
  7.     coefs = np.asarray(values[1:], dtype='float32' 
  8.     word_embeddings[word] = coefs  
  9. f.close()  

現(xiàn)在,讓我們?yōu)榫渥觿?chuàng)建向量表示。我們將首先獲取組成句子的所有單詞的向量(每個向量為 100 維),然后 取這些向量的平均值來得到句子的向量。 

  1. sentence_vectors = []  
  2. for i in clean_sentences:  
  3.     if len(i) != 0:  
  4.        v = sum([word_embeddings.get(w, np.zeros((100,))) for w in i.split()])/(len(i.split())+0.001)  
  5.     else 
  6.        v = np.zeros((100,))  
  7. sentence_vectors.append(v)  

6.8. 準(zhǔn)備相似度矩陣

下一步是計(jì)算句子之間的相似度,我們將使用余弦相似度(cosine similarity)方法來計(jì)算句子向量間的相似 度。

讓我們首先定義維度為(n * n)的零矩陣。然后使用句子的余弦相似度分?jǐn)?shù)初始化該矩陣。這里,n 是句子 數(shù)。 

  1. # similarity matrix  
  2. sim_mat = np.zeros([len(sentences), len(sentences)])  
  3. from sklearn.metrics.pairwise import cosine_similarity  
  4. for i in range(len(sentences)):  
  5.      for j in range(len(sentences)):  
  6.           if i != j:  
  7.              sim_mat[i][j] = cosine_similarity(sentence_vectors[i].reshape(1,100), sentence_vectors[j].reshape(1,100))[0,0]  

6.9. 應(yīng)用 PageRank 算法

在繼續(xù)下一步之前,需要將相似度矩陣轉(zhuǎn)換為圖,圖中的頂點(diǎn)表示句子,邊表示句子間的相似度分?jǐn)?shù)。我們將 在這張圖上應(yīng)用 PageRank 算法來進(jìn)行句子的排名。 

  1. import networkx as nx  
  2. nx_graph = nx.from_numpy_array(sim_mat)  
  3. scores = nx.pagerank(nx_graph)  

6.10. 摘要抽取

***,從生成的摘要中抽取出排名前 N 的句子。 

  1. ranked_sentences = sorted(((scores[i],s)  
  2. for i,s in enumerate(sentences)), reverse=True 
  3. # Extract top 10 sentences as the summary  
  4. for i in range(10):  
  5.      print(ranked_sentences[i][1])  

輸出: 

  1. When I'm on the courts or when I'on the court playing, I'm a competitor and I want to beat every single person whether they're in the locker room or across the net.So I'm not the one to strike up a conversation about the weather and know that in the next few minutes I have to go and try to win a tennis match. 
  2. Major players feel that a big event in late November combined with one in January before the Australian Open will mean too much tennis and too little rest. 
  3. Speaking at the Swiss Indoors tournament where he will play in Sundays final against Romanian qualifier Marius Copil, the world number three said that given the impossibly short time frame to make a decision, he opted out of any commitment. 
  4. "I felt like the best weeks that I had to get to know players when I was playing were the Fed Cup weeks or the Olympic weeks, not necessarily during the tournaments. 
  5. Currently in ninth place, Nishikori with a win could move to within 125 points of the cut for the eight-man event in London next month
  6. He used his first break point to close out the first set before going up 3-0 in the second and wrapping up the win on his first match point. The Spaniard broke Anderson twice in the second but didn't get another chance on the South African's serve in the final set
  7. "We also had the impression that at this stage it might be better to play matches than to train. 
  8. The competition is set to feature 18 countries in the November 18-24 finals in Madrid next yearand will replace the classic home-and-away ties played four times per year for decades. 
  9. Federer said earlier this month in Shanghai in that his chances of playing the Davis Cup were all but non-existent.  

這樣,我們就得到了想要的文本摘要的結(jié)果。

7. What’s Next?

自動文本摘要是研究的熱門話題,我們在本文只討論了冰山一角。展望未來,我們將探索深度學(xué)習(xí)在其中起著 重要作用的抽象文本摘要技術(shù)。此外,我們還可以研究以下摘要任務(wù):

1. 特定問題的摘要任務(wù)

  • 多領(lǐng)域文本摘要
  • 單文檔摘要
  • 跨語言文本摘要(輸入是某種語言,生成另一種語言的摘要)

2. 特定算法的摘要任務(wù):

  • 使用 RNN 和 LSTM 網(wǎng)絡(luò)的文本摘要
  • 使用增強(qiáng)學(xué)習(xí)的文本摘要
  • 使用對抗生成網(wǎng)絡(luò)(GAN)的文本摘要

8. 結(jié)語

我希望這篇文章能幫助您理解自動文本摘要的概念。它有各種各樣的用例,并有人用此做出了非常成功的應(yīng) 用程序。無論是出于商業(yè)的考慮,還是僅僅出于學(xué)習(xí)知識的考慮,文本摘要技術(shù)都應(yīng)是 NLP 愛好者們應(yīng)該熟 悉的方法。

我將在以后的文章中嘗試使用高級技術(shù)來介紹抽象文本摘要技術(shù)。以上代碼可以在此Github中找到。

【51CTO譯稿,合作站點(diǎn)轉(zhuǎn)載請注明原文譯者和出處為51CTO.com】

 

責(zé)任編輯:龐桂玉 來源: 51CTO
相關(guān)推薦

2017-08-03 16:20:42

深度學(xué)習(xí)文本摘要遞歸神經(jīng)網(wǎng)絡(luò)

2022-03-25 14:24:18

谷歌自然語言算法

2024-04-10 08:40:18

2023-07-28 08:13:30

2023-06-09 07:29:03

模型文本document

2018-07-25 12:00:21

2011-06-27 13:57:42

JavaScript

2011-03-03 09:35:04

js

2024-12-19 08:00:00

FAST算法OpenCV目標(biāo)跟蹤

2022-03-03 10:49:46

Python自動追蹤代碼

2021-09-08 09:52:34

語言

2024-10-28 08:24:17

2021-08-30 10:16:19

代碼開發(fā)文本

2017-02-23 08:45:36

Python決策樹數(shù)據(jù)集

2020-06-11 08:32:50

Python遺傳算法代碼

2021-03-16 11:30:33

2022-03-10 12:03:33

Python算法代碼

2018-05-11 13:39:05

PythonCSV接口測試

2014-07-22 10:29:04

背包算法coffee

2018-05-11 08:29:10

Python自動化測試數(shù)據(jù)驅(qū)動
點(diǎn)贊
收藏

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