使用LLM根据句子创建示例知识图谱

2024年07月04日 由 alex 发表 161 0

2


知识图谱是一种以结构化形式表示信息的强大方法,它使实体之间的关系更容易检索、分析和可视化。随着大型语言模型(LLM)(如 Hugging Face 提供的模型)的出现,从自然语言文本中构建知识图谱变得更加容易。在本文中,我们将介绍如何使用 Hugging Face 模型从一个句子中创建知识图谱示例。


什么是知识图谱?

知识图谱是存储在图谱数据库中的现实世界实体(如人、地点和事物)及其相互关系的网络。每个节点代表一个实体,每条边代表两个实体之间的关系。


前提条件

系统中已安装 Python。


Hugging Face 转换器库。


用于创建和可视化图形的 networkx 库。


你可以使用 pip 安装必要的库:


pip install transformers networkx


分步指南


步骤 1:导入库

首先,让我们导入所需的库。


import networkx as nx
import matplotlib.pyplot as plt
from transformers import pipeline


步骤 2:加载预训练模型

我们将使用 Hugging Face 预先训练好的命名实体识别(NER)模型来识别句子中的实体。


ner_pipeline = pipeline("ner", model="dbmdz/bert-large-cased-finetuned-conll03-english")"ner", model="dbmdz/bert-large-cased-finetuned-conll03-english")


步骤 3:定义句子

定义一个句子,从中提取实体和关系。


sentence = "Barack Obama was born in Hawaii. He was elected president in 2008.""Barack Obama was born in Hawaii. He was elected president in 2008."


步骤 4:提取实体

使用 NER 管道从句子中提取实体。


entities = ner_pipeline(sentence)
print(entities)


输出结果将是一个实体列表,其中包含实体标签和实体在句子中的位置。


步骤 5:创建知识图谱

现在,我们将使用 networkx 库创建知识图谱。为简单起见,我们将根据文本中的邻近度创建关系。


G = nx.DiGraph()
# Add nodes
for entity in entities:
    G.add_node(entity['word'], label=entity['entity'])
# Add edges
for i in range(len(entities) - 1):
    G.add_edge(entities[i]['word'], entities[i+1]['word'])
# Draw the graph
pos = nx.spring_layout(G)
nx.draw(G, pos, with_labels=True, node_size=3000, node_color='skyblue', font_size=10, font_color='black')
labels = nx.get_edge_attributes(G, 'label')
nx.draw_networkx_edge_labels(G, pos, edge_labels=labels)
plt.show()


这将创建一个简单的知识图谱,根据实体在句子中的邻近程度将其连接起来。


步骤 6:增强知识图谱

如果想采用更复杂的方法,可以使用依赖关系解析来更准确地识别关系。在这里,我们演示了使用 Hugging Face 中预先训练好的依赖关系解析模型。


from transformers import AutoTokenizer, AutoModelForTokenClassification
from transformers import pipeline
tokenizer = AutoTokenizer.from_pretrained("Davlan/bert-base-multilingual-cased-ner-hrl")
model = AutoModelForTokenClassification.from_pretrained("Davlan/bert-base-multilingual-cased-ner-hrl")
nlp = pipeline("ner", model=model, tokenizer=tokenizer)
result = nlp(sentence)
entities = []
for res in result:
    entities.append((res['word'], res['entity']))
# Create a new graph
G = nx.DiGraph()
# Add nodes and edges
for i, entity in enumerate(entities):
    G.add_node(entity[0], label=entity[1])
    if i > 0:
        G.add_edge(entities[i-1][0], entity[0])
# Draw the graph
pos = nx.spring_layout(G)
nx.draw(G, pos, with_labels=True, node_size=3000, node_color='skyblue', font_size=10, font_color='black')
plt.show()


结论

在本文中,我们演示了如何使用拥抱脸模型从一个句子中创建一个简单的知识图谱。通过利用 LLM 的强大功能和 networkx 库的灵活性,你可以根据自己的具体需求构建更复杂、更丰富的知识图谱。这仅仅是个开始;整合更先进的 NLP 技术和更丰富的数据集,可以生成更强大的知识图谱。

文章来源:https://medium.com/@visheshtaposthali/creating-a-sample-knowledge-graph-from-a-sentence-using-llms-e8bcdbc07881
欢迎关注ATYUN官方公众号
商务合作及内容投稿请联系邮箱:bd@atyun.com
评论 登录
热门职位
Maluuba
20000~40000/月
Cisco
25000~30000/月 深圳市
PilotAILabs
30000~60000/年 深圳市
写评论取消
回复取消