突出网站建设 突出能力,南昌市经济技术开发区,个人网站怎么备案可以做哪些,公司网站建设的定位语要怎么取TF-IDF
TF-IDF是一种经典的基于统计的方法#xff0c;TF(Term frequency)是指一个单词在一个文档中出现的次数#xff0c;通常一个单词在一个文档中出现的次数越多说明该词越重要。IDF(Inverse document frequency)是所有文档数比上出现某单词的个数#xff0c;通常一个单词…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} idftlogdft1N TF-IDF是TF和IDF两部分的乘积是一个综合重要度通常IDF会在尽可能大的文档集合来计算得出。TF-IDF的好处是原理简单好解释但是因为使用了词频来衡量词的重要性可能会漏掉一些出现次数不多但是相对重要的词另外它也没有考虑到单词的位置信息。
使用Scikit-Learns利用TF-IDF提取关键词的代码如下
from sklearn.feature_extraction.text import TfidfTransformer
from sklearn.feature_extraction.text import CountVectorizerdef sort_coo(coo_matrix):tuples zip(coo_matrix.col, coo_matrix.data)return sorted(tuples, keylambda x: (x[1], x[0]), reverseTrue)
def extract_topn_from_vector(feature_names, sorted_items, topn10):get the feature names and tf-idf score of top n items#use only topn items from vectorsorted_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 scorescore_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%的文档中出现的词
cvCountVectorizer(max_df0.85)
word_count_vectorcv.fit_transform(docs)
print(word_count_vector.shape)tfidf_transformerTfidfTransformer(smooth_idfTrue,use_idfTrue)
tfidf_transformer.fit(word_count_vector)
tfidf_transformer.idf_# 单词名
feature_namescv.get_feature_names_out()
# tf-idf计算
tf_idf_vectortfidf_transformer.transform(word_count_vector)results[]
for i in range(tf_idf_vector.shape[0]):# 获取单个文档的向量curr_vectortf_idf_vector[i]#根据tfidf分数对向量进行排序sorted_itemssort_coo(curr_vector.tocoo())# 取top 10 的关键词keywordsextract_topn_from_vector(feature_names, sorted_items, 10) results.append(keywords)TextRank
TextRank 出自2004年的论文《TextRank: Bringing Order into Text》它是一种基于图的排序算法其思想借鉴了PageRank算法当然除了PageRank之外也可以用其他的图排序算法来计算节点的权重。
使用TextRank进行关键词提取的步骤如下 对文本进行分词并对单词进行词性标注只保留指定词性如名词和动词作为图的节点。 根据单词之间的共现关系进行构图使用一个大小为N的滑动窗口N一般取2到10如果两个节点同时出现在一个滑动窗口中则说明两个节点之间可以构成一条边。具体构图时按是否考虑单词之间的先后顺序来构建无向图或有向图按照是否考虑单词之间共现次数构建加权图或无权重图。 对已经构建好的图按照下式来迭代计算重要度直到收敛式中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 wji1。 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)wjkwjiWS(Vj) 按照计算好的重要度进行倒序排序挑选出重要度最大的T个词T可考虑根据根据文本长度来决定并将挑选出的词还原到原文本中将位置相邻的词合并成一个词。
TextRank相比于TF-IDF考虑了词汇之间的关系把文章中的词组成了一个图从全局角度来考虑不同词的重要性。
RAKE
RAKE(rapid automatic keyword extraction)出自2010年的论文《Automatic Keyword Extraction from Individual Documents》作者们基于关键词一般包括多个单词并且不包含停用词标点符号的观察提出了RAKE算法。
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对分割得到的候选词序列生成词共现图也就是如果两个词同时出现两者之间就构成一条边并计算每个词之间的共现次数。比如上面的例子得到的图对应的邻接矩阵示意如下对角线即每个单词本身出现的次数图片来自论文 计算每个关键词的分数设每个单词的词频为 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)而每个候选关键词的分数为其所有单词之和。上面例子中对应的计算结果如下图 考虑到有时候关键词可能会包括停用词比如“axis of evil”RAKE规定如果一对候选关键词出现在文章中相邻的位置至少2次以上就将他们合并成一个关键词其分数是其合并前的关键词分数之和。挑选出分数最大的T个词作为关键词。
YAKE
YAKE出自2018年的论文《A Text Feature Based Automatic Keyword Extraction Method for Single Documents》且有开源github。
YAKE是一种基于统计的关键词提取方法分成四个主要的部分(1) 文本预处理(2) 特征提取(3)单词权重计算(4)候选关键词生成。 文本预处理因为这篇论文提出背景主要使用于西方文字系统所以仅仅使用空格或其他字符如括号逗号句号等将文本切分成单个单词。 特征提取提出了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))} WCaselog2(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 WPosition0 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))) WPositionlog2(log2(2Median(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 } WFreqMeanTF1∗σ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) 单词权重计算 按照下式来计算每个单词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)WCaseWRelWFreqWRelWDifSentenceWRel∗WPosition 候选关键词生成: 因为关键词通常不仅仅由一个单词构成所以使用一个大小为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∑w∈kwS(w))∏w∈kwS(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(tokenizertokenize_zh)
kw_model KeyBERT(modelparaphrase-multilingual-MiniLM-L12-v2)
doc 强化学习是机器通过与环境交互来实现目标的一种计算方法。机器和环境的一轮交互是指机器在环境的一个状态下做一个动作决策把这个动作作用到环境当中这个环境发生相应的改变并且将相应的奖励反馈和下一轮状态传回机器。这种交互是迭代进行的机器的目标是最大化在多轮交互过程中获得的累积奖励的期望。
keywords kw_model.extract_keywords(doc, vectorizervectorizer)如果我们只选择那些与文档最相似的一些词来作为关键词很可能会使挑选出的关键词之间的相似度比较高所以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, Tupledef 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 keywordsWe 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 andextract the combination that are the least similar to each otherby cosine similarity.This is O(n^2) and therefore not advised if you use a large top_nArguments:doc_embedding: The document embeddingsword_embeddings: The embeddings of the selected candidate keywords/phraseswords: The selected candidate keywords/keyphrasestop_n: The number of keywords/keyhprases to returnnr_candidates: The number of candidates to considerReturns:List[Tuple[str, float]]: The selected keywords/keyphrases with their distancesif 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 keywordsdistances cosine_similarity(doc_embedding, word_embeddings)distances_words cosine_similarity(word_embeddings, word_embeddings)# Get 2*top_n words as candidates based on cosine similaritywords_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 othermin_sim 100_000candidate Nonefor 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 combinationmin_sim simreturn [(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 thedocument, along with the similarity of already selectedkeywords and keyphrases. This results in a selection of keywordsthat maximize their within diversity with respect to the document.Arguments:doc_embedding: The document embeddingsword_embeddings: The embeddings of the selected candidate keywords/phraseswords: The selected candidate keywords/keyphrasestop_n: The number of keywords/keyhprases to returndiversity: How diverse the select keywords/keyphrases are.Values between 0 and 1 with 0 being not diverse at alland 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 documentword_doc_similarity cosine_similarity(word_embeddings, doc_embedding)word_similarity cosine_similarity(word_embeddings)# Initialize candidates and already choose best keyword/keyphraskeywords_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/phrasescandidate_similarities word_doc_similarity[candidates_idx, :]target_similarities np.max(word_similarity[candidates_idx][:, keywords_idx], axis1)# Calculate MMRmmr (1 - diversity) * candidate_similarities - diversity * target_similarities.reshape(-1, 1)mmr_idx candidates_idx[np.argmax(mmr)]# Update keywords candidateskeywords_idx.append(mmr_idx)candidates_idx.remove(mmr_idx)# Extract and sort keywords in descending similaritykeywords [(words[idx], round(float(word_doc_similarity.reshape(1, -1)[0][idx]), 4))for idx in keywords_idx]keywords sorted(keywords, keyitemgetter(1), reverseTrue)return keywords理解了keyBERT的原理后就发现keyBERT提取关键词的效果十分依赖于向量编码模型的质量所以需要根据自己业务情况挑选适合的向量编码模型。
参考资料 scikit-learn CountVectorizer文档 scikit-learn TfiidfTransformer 文档tfidf提取关键字参考代码 textrank的论文TextRank: Bringing Order into Text textrank 的一些实现textrank jieba中实现了textrank关键词提取 RAKE python实现: RAKE multi_rake RAKE-turorial YAKE github keyBERT github 知乎上关于keyBERT在实际应用的分享