无监督关键词提取算法:TF-IDF、TextRank、RAKE、YAKE、 keyBERT

2024-01-01 17:41:52

TF-IDF

TF-IDF是一种经典的基于统计的方法,TF(Term frequency)是指一个单词在一个文档中出现的次数,通常一个单词在一个文档中出现的次数越多说明该词越重要。IDF(Inverse document frequency)是所有文档数比上出现某单词的个数,通常一个单词在整个文本集合中出现的文本数越少,这个单词就越能表示其所在文本的特点,重要性就越高;IDF计算一般会再取对数,设总文档数为N,出现单词t的文档数为 d f t df_t dft?(为了防止分母为0,一般会对分母加一):
i d f t = l o g N d f t + 1 idf_t = log \frac{N}{df_t + 1} idft?=logdft?+1N?
TF-IDF是TF和IDF两部分的乘积,是一个综合重要度,通常IDF会在尽可能大的文档集合来计算得出。TF-IDF的好处是原理简单好解释,但是因为使用了词频来衡量词的重要性,可能会漏掉一些出现次数不多但是相对重要的词,另外它也没有考虑到单词的位置信息。

使用Scikit-Learns利用TF-IDF提取关键词的代码如下:

from sklearn.feature_extraction.text import TfidfTransformer
from sklearn.feature_extraction.text import CountVectorizer

def sort_coo(coo_matrix):
    tuples = zip(coo_matrix.col, coo_matrix.data)
    return sorted(tuples, key=lambda x: (x[1], x[0]), reverse=True)
def extract_topn_from_vector(feature_names, sorted_items, topn=10):
    """get the feature names and tf-idf score of top n items"""
    #use only topn items from vector
    sorted_items = sorted_items[:topn]
    score_vals = []
    feature_vals = []

    for idx, score in sorted_items:
        fname = feature_names[idx]
        #keep track of feature name and its corresponding score
        score_vals.append(round(score, 3))
        feature_vals.append(feature_names[idx])
    #create a tuples of feature,score
    #results = zip(feature_vals,score_vals)
    results= {}
    for idx in range(len(feature_vals)):
        results[feature_vals[idx]]=score_vals[idx]
    return json.dumps(results)


#docs 集合,如果是中文可以先分词或者在CountVectorizer里定义tokenizer
docs=[]

#创建单词词汇表, 忽略在85%的文档中出现的词
cv=CountVectorizer(max_df=0.85)
word_count_vector=cv.fit_transform(docs)
print(word_count_vector.shape)

tfidf_transformer=TfidfTransformer(smooth_idf=True,use_idf=True)
tfidf_transformer.fit(word_count_vector)
tfidf_transformer.idf_

# 单词名
feature_names=cv.get_feature_names_out()
# tf-idf计算
tf_idf_vector=tfidf_transformer.transform(word_count_vector)

results=[]
for i in range(tf_idf_vector.shape[0]):
    # 获取单个文档的向量
    curr_vector=tf_idf_vector[i]
    #根据tfidf分数对向量进行排序
    sorted_items=sort_coo(curr_vector.tocoo())
    # 取top 10 的关键词
    keywords=extract_topn_from_vector(feature_names, sorted_items, 10) 
    results.append(keywords)

TextRank

TextRank 出自2004年的论文《TextRank: Bringing Order into Text》,它是一种基于图的排序算法,其思想借鉴了PageRank算法(当然除了PageRank之外,也可以用其他的图排序算法来计算节点的权重)。

使用TextRank进行关键词提取的步骤如下:

  1. 对文本进行分词,并对单词进行词性标注,只保留指定词性如名词和动词作为图的节点。

  2. 根据单词之间的共现关系进行构图:使用一个大小为N的滑动窗口(N一般取2到10),如果两个节点同时出现在一个滑动窗口中,则说明两个节点之间可以构成一条边。具体构图时按是否考虑单词之间的先后顺序来构建无向图或有向图,按照是否考虑单词之间共现次数构建加权图或无权重图。

  3. 对已经构建好的图按照下式来迭代计算重要度直到收敛,式中d是阻尼系数,取值为[0, 1],一般取0.85。 I n ( V i ) In(V_i) In(Vi?)表示某节点的入边集合, O u t ( V j ) Out(V_j) Out(Vj?)表示某节点的出边集合, w j i w_{ji} wji?是节点j到i的权重,对于无权图 w j i = 1 w_{ji}=1 wji?=1
    W S ( V i ) = ( 1 ? d ) + d ? ? ∑ V j ∈ I n ( V i ) w j i ∑ V k ∈ O u t ( V j ) w j k W S ( V j ) WS(V_i) = (1-d) + d\ * \sum_{V_j \in In(V_i)} \frac{w_{ji}}{\sum_{V_k \in Out(V_j)} w_{jk}} WS(V_j) WS(Vi?)=(1?d)+d??Vj?In(Vi?)?Vk?Out(Vj?)?wjk?wji??WS(Vj?)

  4. 按照计算好的重要度进行倒序排序,挑选出重要度最大的T个词(T可考虑根据根据文本长度来决定),并将挑选出的词还原到原文本中,将位置相邻的词合并成一个词。

TextRank相比于TF-IDF考虑了词汇之间的关系,把文章中的词组成了一个图,从全局角度来考虑不同词的重要性。

RAKE

RAKE(rapid automatic keyword extraction)出自2010年的论文《Automatic Keyword Extraction from Individual Documents》,作者们基于关键词一般包括多个单词并且不包含停用词标点符号的观察,提出了RAKE算法。

  1. RAKE首先用停用词和标点符号将文本分割成候选词序列
Compatibility of systems of linear constraints over the set of natural numbers Criteria of compatibility of a system of linear Diophantine equations, strict inequations, and nonstrict inequations are considered. Upper bounds for components of a minimal set of solutions and algorithms of construction of minimal generating sets of solutions for all types of systems are given. These criteria and the corresponding algorithms for constructing a minimal supporting set of solutions can be used in solving all the considered types of systems and systems of mixed types.

对于上面一段文本,分割之后将得到

Compatibility – systems – linear constraints – set – natural numbers – Criteria – compatibility – system – linear Diophantine equations – strict inequations – nonstrict inequations – Upper bounds – components – minimal set – solutions – algorithms – minimal generating sets – solutions – systems – criteria – corresponding algorithms – constructing – minimal supporting set – solving – systems – systems
  1. 对分割得到的候选词序列生成词共现图,也就是如果两个词同时出现,两者之间就构成一条边,并计算每个词之间的共现次数。比如上面的例子得到的图对应的邻接矩阵示意如下(对角线即每个单词本身出现的次数,图片来自论文):
    在这里插入图片描述

  2. 计算每个关键词的分数,设每个单词的词频为 f r e q ( w ) freq(w) freq(w),单词在生成的图里对应的度为 d e g ( w ) deg(w) deg(w),则每个单词的分数为 d e g ( w ) / f r e q ( w ) deg(w)/freq(w) deg(w)/freq(w),而每个候选关键词的分数为其所有单词之和。上面例子中对应的计算结果如下图:

在这里插入图片描述

  1. 考虑到有时候关键词可能会包括停用词,比如“axis of evil”,RAKE规定如果一对候选关键词出现在文章中相邻的位置至少2次以上,就将他们合并成一个关键词,其分数是其合并前的关键词分数之和。
  2. 挑选出分数最大的T个词作为关键词。

YAKE

YAKE出自2018年的论文《A Text Feature Based Automatic Keyword Extraction Method for Single Documents》且有开源github

YAKE是一种基于统计的关键词提取方法,分成四个主要的部分:(1) 文本预处理;(2) 特征提取;(3)单词权重计算;(4)候选关键词生成。

  1. 文本预处理,因为这篇论文提出背景主要使用于西方文字系统,所以仅仅使用空格或其他字符如括号逗号句号等将文本切分成单个单词。

  2. 特征提取,提出了5种特征来捕获每个term的特征。

  • Casing( W C a s e W_{Case} WCase?): 关注一个词以大写字母开头(句子中以大写字母开头的词不算)或是缩略词(一个词全部由大写字母组成)的次数。设 T F ( U ( w ) ) TF(U(w)) TF(U(w))是单词w以大写字母开头的次数, T F ( A ( w ) ) TF(A(w)) TF(A(w))是单词w被标记为缩略词的次数, T F ( w ) TF(w) TF(w)是单词w的词频:
    W C a s e = m a x ( T F ( U ( w ) ) , T F ( A ( w ) ) ) l o g 2 ( T F ( w ) ) W_{Case} = \frac {max(TF(U(w)), TF(A(w)))}{log_2(TF(w))} WCase?=log2?(TF(w))max(TF(U(w)),TF(A(w)))?

  • Word Position( W P o s i t i o n W_{Position} WPosition?):单词在文档中的位置可能是一个关键词提取的重要特征,因为通常出现在文档前面的单词是关键词的概率更大。设 M e d i a n Median Median是中位数, S e n w Sen_w Senw?是单词w出现过的句子集的位置。 W P o s i t i o n W_{Position} WPosition? 的定义如下(定义中的2是为了保证 W P o s i t i o n > 0 W_{Position}>0 WPosition?>0):
    W P o s i t i o n = l o g 2 ( l o g 2 ( 2 + M e d i a n ( S e n w ) ) ) W_{Position} = log_2(log_2(2 + Median(Sen_w))) WPosition?=log2?(log2?(2+Median(Senw?)))

  • Word Frequency( W F r e q W_{Freq} WFreq?):通常一个单词出现越多说明其越重要,为了减少因为长文档使词频偏大的偏差,计算词频时将除去平均词频(MeanTF)和词频标准差( σ \sigma σ)之和:
    W F r e q = T F ( w ) M e a n T F + 1 ? σ W_{Freq} = \frac{TF(w)} {MeanTF + 1*\sigma } WFreq?=MeanTF+1?σTF(w)?

  • Word Relatedness to Context( W R e l W_{Rel} WRel?):量化一个词是否与停用词相似。设WL[WR]是候选单词w左侧(右侧)n大小窗口内与候选单词共现的不同单词的个数比上与候选单词共现过的所有单词的个数。 TF是单词w的词频,MaxTF是所有单词里的最大词频。PL[PR]是候选单词w左侧(右侧)n大小窗口内与候选单词共现的不同单词的个数比上MaxTF,与停用词相似的单词的分数会越大:
    W R e l = ( 0.5 + ( ( W L ? T F ( w ) M a x T F ) + P L ) ) + ( 0.5 + ( ( W R ? T F ( w ) M a x T F ) + P R ) ) W_{Rel} = \left( 0.5 + \left( \left( WL * \frac{TF(w)}{MaxTF} \right) + PL \right) \right) + \left( 0.5 + \left( \left( WR * \frac{TF(w)}{MaxTF} \right) + PR \right) \right) WRel?=(0.5+((WL?MaxTFTF(w)?)+PL))+(0.5+((WR?MaxTFTF(w)?)+PR))

  • Word DifSentence( W D i f S e n t e n c e ) W_{DifSentence}) WDifSentence?)):量化一个单词在不同句子中出现的次数, S F ( w ) SF(w) SF(w)是单词w出现在句子中的频次, # S e n t e n c e s \#Sentences #Sentences 是文本中的总句子数。
    W D i f S e n t e n c e = S F ( w ) # S e n t e n c e s W_{DifSentence} = \frac {SF(w)} {\#Sentences} WDifSentence?=#SentencesSF(w)?

  1. 单词权重计算: 按照下式来计算每个单词w的分数 S ( w ) S(w) S(w) S ( w ) S(w) S(w)越小,则单词w越重要。
    S ( w ) = W R e l ? W P o s i t i o n W C a s e + W F r e q W R e l + W D i f S e n t e n c e W R e l S(w) = \frac {W_{Rel} * W_{Position}} {W_{Case} + \frac{W_{Freq}}{W_{Rel}} + \frac{W_{DifSentence}}{W_{Rel}} } S(w)=WCase?+WRel?WFreq??+WRel?WDifSentence??WRel??WPosition??

  2. 候选关键词生成: 因为关键词通常不仅仅由一个单词构成,所以使用一个大小为3的滑动窗口,不考虑停用词,生成长度为1、2、3的候选关键词,每个候选关键词的分数 S ( k w ) S(kw) S(kw)(越小越重要)计算如下:
    S ( k w ) = ∏ w ∈ k w S ( w ) T F ( k w ) ? ( 1 + ∑ w ∈ k w S ( w ) ) S(kw) = \frac {\prod_{w \in kw} S(w)} {TF(kw) * (1 + \sum_{w \in kw} S(w))} S(kw)=TF(kw)?(1+wkw?S(w))wkw?S(w)?
    为了过滤掉相似候选词,使用编辑距离Levenshtein distance来判断两个候选词的相似性,如果相似性高于指定阈值,则只保留 S ( k w ) S(kw) S(kw)更低的候选词。最后算法将输出一个重要性靠前的关键词列表。

keyBERT

keyBERT是一个使用BERT embedding向量来生成关键词的工具,其思路是对文档用BERT编码成向量,再将文档使用Scikit-Learns 的 CountVectorizer 对文档进行分词,然后比较文档中的每个单词向量与文档向量之间的相似度,选择相似度最大的一些词作为关键词。

其基本用法:

from keybert import KeyBERT

# 英文文档关键词提取示例,不指定embedding模型,默认使用sentence-transformers的all-MiniLM-L6-v2模型
doc = """
When we want to understand key information from specific documents, we typically turn towards keyword extraction. Keyword extraction is the automated process of extracting the words and phrases that are most relevant to an input text.
      """
kw_model = KeyBERT()
keywords = kw_model.extract_keywords(doc)

# 中文文档关键词提取示例
# 中文需要自定义CountVectorizer,并为它指定分词器,比如下面示例中使用了jieba来分词
from sklearn.feature_extraction.text import CountVectorizer
import jieba
def tokenize_zh(text):
    words = jieba.lcut(text)
    return words
vectorizer = CountVectorizer(tokenizer=tokenize_zh)
kw_model = KeyBERT(model='paraphrase-multilingual-MiniLM-L12-v2')
doc = """
    强化学习是机器通过与环境交互来实现目标的一种计算方法。机器和环境的一轮交互是指,机器在环境的一个状态下做一个动作决策,把这个动作作用到环境当中,这个环境发生相应的改变并且将相应的奖励反馈和下一轮状态传回机器。这种交互是迭代进行的,机器的目标是最大化在多轮交互过程中获得的累积奖励的期望。"""
keywords = kw_model.extract_keywords(doc, vectorizer=vectorizer)

如果我们只选择那些与文档最相似的一些词来作为关键词,很可能会使挑选出的关键词之间的相似度比较高,所以keyBert的作者实现了下面两种来算法来使选择的关键词更多样化一些:

  • Max Sum Distance:设生成关键词个数为 t o p _ n top\_n top_n, 选择一个比 t o p _ n top\_n top_n大的数 n r _ c a n d i d a t e s nr\_candidates nr_candidates,先从文档中挑选出与文档最相似的 n r _ c a n d i d a t e s nr\_candidates nr_candidates个候选词,然后从 n r _ c a n d i d a t e s nr\_candidates nr_candidates个词选择 t o p _ n top\_n top_n个词的所有组合中选择两两相似度之和最小的组合作为返回的关键词。因此 n r _ c a n d i d a t e s nr\_candidates nr_candidates越大选择出来的关键词更多样化,但也可能会选择出一些并不能代表文档的词,作者的建议是 n r _ c a n d i d a t e s nr\_candidates nr_candidates不要超过文档中词汇个数的20%。

    # 代码来自keyBERT 源码 https://github.com/MaartenGr/KeyBERT/blob/master/keybert/_maxsum.py
    import numpy as np
    import itertools
    from sklearn.metrics.pairwise import cosine_similarity
    from typing import List, Tuple
    
    
    def max_sum_distance(
        doc_embedding: np.ndarray,
        word_embeddings: np.ndarray,
        words: List[str],
        top_n: int,
        nr_candidates: int,
    ) -> List[Tuple[str, float]]:
        """Calculate Max Sum Distance for extraction of keywords
    
        We take the 2 x top_n most similar words/phrases to the document.
        Then, we take all top_n combinations from the 2 x top_n words and
        extract the combination that are the least similar to each other
        by cosine similarity.
    
        This is O(n^2) and therefore not advised if you use a large `top_n`
    
        Arguments:
            doc_embedding: The document embeddings
            word_embeddings: The embeddings of the selected candidate keywords/phrases
            words: The selected candidate keywords/keyphrases
            top_n: The number of keywords/keyhprases to return
            nr_candidates: The number of candidates to consider
    
        Returns:
             List[Tuple[str, float]]: The selected keywords/keyphrases with their distances
        """
        if nr_candidates < top_n:
            raise Exception(
                "Make sure that the number of candidates exceeds the number "
                "of keywords to return."
            )
        elif top_n > len(words):
            return []
    
        # Calculate distances and extract keywords
        distances = cosine_similarity(doc_embedding, word_embeddings)
        distances_words = cosine_similarity(word_embeddings, word_embeddings)
    
        # Get 2*top_n words as candidates based on cosine similarity
        words_idx = list(distances.argsort()[0][-nr_candidates:])
        words_vals = [words[index] for index in words_idx]
        candidates = distances_words[np.ix_(words_idx, words_idx)]
    
        # Calculate the combination of words that are the least similar to each other
        min_sim = 100_000
        candidate = None
        for combination in itertools.combinations(range(len(words_idx)), top_n):
            sim = sum(
                [candidates[i][j] for i in combination for j in combination if i != j]
            )
            if sim < min_sim:
                candidate = combination
                min_sim = sim
    
        return [
            (words_vals[idx], round(float(distances[0][words_idx[idx]]), 4))
            for idx in candidate
        ]
    
    
  • Maximal Marginal Relevance (MMR):除了使关键词与文档尽可能的相似之外,同时降低关键词之间的相似性或者冗余度。参数diversity来控制候选词的多样性,diversity越小,则候选关键词之间可能更相似,而diversity越大,则关键词之间的冗余度更小。算法具体为:1. 先生成候选词与文档相似度矩阵、候选词之间的相似度矩阵。2. 挑选与文档最相似的候选词作为第一个关键词。3. 其余关键词逐一挑选,挑选规则为:设剩余候选词与文档相似性矩阵为 c a n _ s i m can\_sim can_sim,剩余候选词与已挑选的关键词最大相似度矩阵为 t a r _ s i m tar\_sim tar_sim,按公式 m m r = ( 1 ? d i v e r s i t y ) ? c a n _ s i m ? d i v e r s i t y ? t a r _ s i m mmr = (1-diversity)*can\_sim - diversity*tar\_sim mmr=(1?diversity)?can_sim?diversity?tar_sim 计算mmr,挑选mmr最大的候选词作为下一个关键词。

# 代码来自keyBERT 源码 https://github.com/MaartenGr/KeyBERT/blob/master/keybert/_mmr.py
def mmr(
    doc_embedding: np.ndarray,
    word_embeddings: np.ndarray,
    words: List[str],
    top_n: int = 5,
    diversity: float = 0.8,
) -> List[Tuple[str, float]]:
    """Calculate Maximal Marginal Relevance (MMR)
    between candidate keywords and the document.


    MMR considers the similarity of keywords/keyphrases with the
    document, along with the similarity of already selected
    keywords and keyphrases. This results in a selection of keywords
    that maximize their within diversity with respect to the document.

    Arguments:
        doc_embedding: The document embeddings
        word_embeddings: The embeddings of the selected candidate keywords/phrases
        words: The selected candidate keywords/keyphrases
        top_n: The number of keywords/keyhprases to return
        diversity: How diverse the select keywords/keyphrases are.
                   Values between 0 and 1 with 0 being not diverse at all
                   and 1 being most diverse.

    Returns:
         List[Tuple[str, float]]: The selected keywords/keyphrases with their distances

    """

    # Extract similarity within words, and between words and the document
    word_doc_similarity = cosine_similarity(word_embeddings, doc_embedding)
    word_similarity = cosine_similarity(word_embeddings)

    # Initialize candidates and already choose best keyword/keyphras
    keywords_idx = [np.argmax(word_doc_similarity)]
    candidates_idx = [i for i in range(len(words)) if i != keywords_idx[0]]

    for _ in range(min(top_n - 1, len(words) - 1)):
        # Extract similarities within candidates and
        # between candidates and selected keywords/phrases
        candidate_similarities = word_doc_similarity[candidates_idx, :]
        target_similarities = np.max(
            word_similarity[candidates_idx][:, keywords_idx], axis=1
        )

        # Calculate MMR
        mmr = (
            1 - diversity
        ) * candidate_similarities - diversity * target_similarities.reshape(-1, 1)
        mmr_idx = candidates_idx[np.argmax(mmr)]

        # Update keywords & candidates
        keywords_idx.append(mmr_idx)
        candidates_idx.remove(mmr_idx)

    # Extract and sort keywords in descending similarity
    keywords = [
        (words[idx], round(float(word_doc_similarity.reshape(1, -1)[0][idx]), 4))
        for idx in keywords_idx
    ]
    keywords = sorted(keywords, key=itemgetter(1), reverse=True)
    return keywords

理解了keyBERT的原理后,就发现keyBERT提取关键词的效果十分依赖于向量编码模型的质量,所以需要根据自己业务情况挑选适合的向量编码模型。

参考资料

  1. scikit-learn CountVectorizer文档scikit-learn TfiidfTransformer 文档tfidf提取关键字参考代码

  2. textrank的论文:TextRank: Bringing Order into Text textrank 的一些实现:textrankjieba中实现了textrank关键词提取

  3. RAKE python实现: RAKEmulti_rakeRAKE-turorial

  4. YAKE github

  5. keyBERT github知乎上关于keyBERT在实际应用的分享

文章来源:https://blog.csdn.net/beingstrong/article/details/135326517
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。