小白学 NLP:KeyBERT提取中英文关键词

学术   2024-08-08 10:27   北京  

unsetunsetKeyBERT介绍unsetunset

pip install keybert

KeyBERT 是一种基于 BERT 嵌入的关键词提取技术,它通过计算文档与子短语之间的余弦相似度来识别文档中最重要的关键词和短语。该技术易于使用,并且不需要从头开始训练模型,非常适合初学者。用户可以通过简单的代码行使用预训练的 BERT 模型来提取关键词。

KeyBERT 的主要特点包括:

  • 利用 BERT 嵌入来创建与文档最相似的关键词和关键短语。
  • 通过 BERT 提取文档嵌入来获得文档级表示,然后提取 N-gram 词/短语的词嵌入。
  • 使用余弦相似度来找到与文档最相似的单词/短语,这些词可以被认为是最能描述整个文档的词。

unsetunsetKeyBERT使用方法unsetunset

基础使用案例

import os
os.environ['HF_ENDPOINT'] = 'https://hf-mirror.com'

from keybert import KeyBERT

doc = """
         Supervised learning is the machine learning task of learning a function that
         maps an input to an output based on example input-output pairs.[1] It infers a
         function from labeled training data consisting of a set of training examples.[2]
         In supervised learning, each example is a pair consisting of an input object
         (typically a vector) and a desired output value (also called the supervisory signal).
         A supervised learning algorithm analyzes the training data and produces an inferred function,
         which can be used for mapping new examples. An optimal scenario will allow for the
         algorithm to correctly determine the class labels for unseen instances. This requires
         the learning algorithm to generalize from the training data to unseen situations in a
         'reasonable' way (see inductive bias).
      "
""
kw_model = KeyBERT()
keywords = kw_model.extract_keywords(doc)

提取关键词组合

kw_model.extract_keywords(doc, keyphrase_ngram_range=(1, 2), stop_words=None)

Max Sum Distance

Max Sum Distance 方法首先选取与文档最相似的一定数量的词或短语作为候选,然后从这些候选中找出相互之间最不相似的组合作为关键词。这种方法通过最大化候选关键词之间的距离来增加结果的多样性

kw_model.extract_keywords(doc, keyphrase_ngram_range=(3, 3), stop_words='english', use_maxsum=True, nr_candidates=20, top_n=5)

Maximal Marginal Relevance (MMR)

另一种多样化关键词的方法,它在选取关键词时不仅考虑与文档的相似度,还考虑已选取关键词之间的差异性。通过引入一个参数来平衡关键词的相关性和多样性,从而生成具有高度多样性的关键词列表。

kw_model.extract_keywords(doc, keyphrase_ngram_range=(3, 3), stop_words='english', use_mmr=True, diversity=0.7)

unsetunsetKeyBERT中文使用unsetunset

KeyBERT是基于 BERT 模型来完成关键词提取,因此只需要替换中文分词方法和中文编码模型即可。

  • 加载中文分词方法
import jieba
import hanlp
tok = hanlp.load(hanlp.pretrained.tok.COARSE_ELECTRA_SMALL_ZH)
pos = hanlp.load(hanlp.pretrained.pos.CTB9_POS_ELECTRA_SMALL)
  • 加载中文编码模型
import os
os.environ['HF_ENDPOINT'] = 'https://hf-mirror.com'

from keybert import KeyBERT
from sklearn.feature_extraction.text import CountVectorizer

doc = """
林黛玉,中国古典名著《红楼梦》中的人物,金陵十二钗正册之首,西方灵河岸绛珠仙草转世,荣府幺女贾敏与扬州巡盐御史林如海之独生女,母亲贾敏是贾代善和贾母四个女儿里最小的女儿,贾母的外孙女,贾宝玉的姑表妹、恋人、知己,贾府通称林姑娘。
"
""

kw_model = KeyBERT(model='BAAI/bge-small-zh-v1.5')
vectorizer = CountVectorizer(tokenizer=tok)
# vectorizer = CountVectorizer(tokenizer=jieba.lcut)

kw_model.extract_keywords(doc, vectorizer=vectorizer, top_n=20)

 学习大模型 & 讨论Kaggle  #


△长按添加竞赛小助手

每天大模型、算法竞赛、干货资讯

与 36000+来自竞赛爱好者一起交流~

Coggle数据科学
Coggle全称Communication For Kaggle,专注数据科学领域竞赛相关资讯分享。
 最新文章