使用 LangChain 从文本数据构建知识图谱

在这篇文章中,我将带您了解知识图谱以及如何从您自己的文本数据构建知识图谱。

什么是知识图谱?

知识图谱也称为语义图,是一种以有效方式存储数据的智能结构。数据以节点和边的形式存储。如图所示,节点表示对象,边缘表示它们之间的关系。知识图谱所表示的数据模型有时被称为资源描述框架(RDF)。RDF 定义了万维网中站点互连的方式。

为什么选择知识图谱?

在整个数据集中,只有少数数据点是代表整个数据集的固有数据点。因此,知识图谱只存储重要的数据点。这大大降低了检索时间的复杂度,并降低了空间的复杂性。

实施

1. 安装和导入软件包

(注意:我们将使用 Open AI 的 GPT-3.5 来生成实体和关系,请确保您已准备好 Open AI Api 密钥)

使用您喜欢的包管理器安装包。在这里,我使用 PIP 来安装和管理依赖项。

ini 复制代码
pip install -q langchain openai pyvis gradio==3.39.0

导入已安装的软件包。

javascript 复制代码
from langchain.prompts import PromptTemplate
from langchain.llms.openai import OpenAI
from langchain.chains import LLMChain
from langchain.graphs.networkx_graph import KG_TRIPLE_DELIMITER
from pprint import pprint
from pyvis.network import Network
import networkx as nx
import gradio as gr

2. 设置 API 密钥

使用从 Open AI Platform Dashboard 复制的 API 密钥来设置 API 密钥环境变量。在这里,我通过 colab 秘密传递变量。因此,在运行之前,请确保已为 secret 变量分配了 api 密钥值。

csharp 复制代码
from google.colab import userdata
OPENAI_API_KEY = userdata.get('OPENAI_API_KEY')

3. 定义提示

更重要的是如何向 LLM 提出正确的问题,以便他们能够产生我们需要的东西。在这里,我们在说明中添加了一些示例,以便我们可以更容易的推理。这种提示方式称为 Few-Shot 提示。请随时阅读提示,以清楚地了解其工作原理。

swift 复制代码
# Prompt template for knowledge triple extraction
_DEFAULT_KNOWLEDGE_TRIPLE_EXTRACTION_TEMPLATE = (
"You are a networked intelligence helping a human track knowledge triples"
" about all relevant people, things, concepts, etc. and integrating"
" them with your knowledge stored within your weights"
" as well as that stored in a knowledge graph."
" Extract all of the knowledge triples from the text."
" A knowledge triple is a clause that contains a subject, a predicate,"
" and an object. The subject is the entity being described,"
" the predicate is the property of the subject that is being"
" described, and the object is the value of the property.\n\n"
"EXAMPLE\n"
"It's a state in the US. It's also the number 1 producer of gold in the US.\n\n"
f"Output: (Nevada, is a, state){KG_TRIPLE_DELIMITER}(Nevada, is in, US)"
f"{KG_TRIPLE_DELIMITER}(Nevada, is the number 1 producer of, gold)\n"
"END OF EXAMPLE\n\n"
"EXAMPLE\n"
"I'm going to the store.\n\n"
"Output: NONE\n"
"END OF EXAMPLE\n\n"
"EXAMPLE\n"
"Oh huh. I know Descartes likes to drive antique scooters and play the mandolin.\n"
f"Output: (Descartes, likes to drive, antique scooters){KG_TRIPLE_DELIMITER}(Descartes, plays, mandolin)\n"
"END OF EXAMPLE\n\n"
"EXAMPLE\n"
"{text}"
"Output:"
)

KNOWLEDGE_TRIPLE_EXTRACTION_PROMPT = PromptTemplate(
input_variables=["text"],
template=_DEFAULT_KNOWLEDGE_TRIPLE_EXTRACTION_TEMPLATE,
)

4. 初始化链

使用描述性提示,使用 LLMChain 类初始化链。

ini 复制代码
llm = OpenAI(
api_key=OPENAI_API_KEY,
temperature=0.9
)
# Create an LLMChain using the knowledge triple extraction prompt
chain = LLMChain(llm=llm, prompt=KNOWLEDGE_TRIPLE_EXTRACTION_PROMPT)

要构建知识图谱,您只需要一些相互关联的文本数据。在这里,我从字符串输入加载文本。但是,需要注意的是,您也可以使用 python 中的数据加载器,从其他的数据格式(例如 PDF、JSON、Markdown 等)加载。

arduino 复制代码
# Run the chain with the specified text
text = "The city of Paris is the capital and most populous city of France. The Eiffel Tower is a famous landmark in Paris."
triples = chain.invoke(
{'text' : text}
).get('text')

并使用此用户定义的函数解析检索到的三元组

ini 复制代码
def parse_triples(response, delimiter=KG_TRIPLE_DELIMITER):
if not response:
return []
return response.split(delimiter)

triples_list = parse_triples(triples)
pprint(triples_list)

输出:

vbnet 复制代码
[' (Paris, is the capital of, France)',
'(Paris, is the most populous city in, France)',
'(Eiffel Tower, is a, famous landmark)',
'(Eiffel Tower, is in, Paris)']

5. 可视化构建的知识图谱

在这里,我们将使用 PyVis 为构建的知识图谱创建可视化,并使用 Gradio 框架以交互方式显示它。

以下是一些用户定义的函数,可以使我们的任务更轻松:

ini 复制代码
def create_graph_from_triplets(triplets):
G = nx.DiGraph()
for triplet in triplets:
subject, predicate, obj = triplet.strip().split(',')
G.add_edge(subject.strip(), obj.strip(), label=predicate.strip())
return G

def nx_to_pyvis(networkx_graph):
pyvis_graph = Network(notebook=True, cdn_resources='remote')
for node in networkx_graph.nodes():
pyvis_graph.add_node(node)
for edge in networkx_graph.edges(data=True):
pyvis_graph.add_edge(edge[0], edge[1], label=edge[2]["label"])
return pyvis_graph

def generateGraph():
triplets = [t.strip() for t in triples_list if t.strip()]
graph = create_graph_from_triplets(triplets)
pyvis_network = nx_to_pyvis(graph)

pyvis_network.toggle_hide_edges_on_drag(True)
pyvis_network.toggle_physics(False)
pyvis_network.set_edge_smooth('discrete')

html = pyvis_network.generate_html()
html = html.replace("'", """)

return f"""<iframe style="width: 100%; height: 600px;margin:0 auto" name="result" allow="midi; geolocation; microphone; camera;
display-capture; encrypted-media;" sandbox="allow-modals allow-forms
allow-scripts allow-same-origin allow-popups
allow-top-navigation-by-user-activation allow-downloads" allowfullscreen=""
allowpaymentrequest="" frameborder="0" srcdoc='{html}'></iframe>"""

使用 Gradio 显示 PyVis 生成的 html

ini 复制代码
demo = gr.Interface(
generateGraph,
inputs=None,
outputs=gr.outputs.HTML(),
title="Knowledge Graph",
allow_flagging='never',
live=True,
)

demo.launch(
height=800,
width="100%"
)

最终输出:

在这里,我们使用 gradio 框架展示了我们的知识图谱,以便可以通过生成的链接轻松地与任何人在线共享该页面。只需在方法中添加 ,即可使应用程序对任何人可见。share=True;demo.launch(share=True)

相关推荐
Akamai中国2 分钟前
AI需要防火墙,云计算需要重新构想
人工智能·云计算·云服务
liupengfei-iot12 分钟前
AutoGLM2.0背后的云手机和虚拟机分析(非使用案例)
人工智能·智能手机·ai编程
BB学长29 分钟前
流固耦合|01流固耦合分类
人工智能·算法
HeteroCat31 分钟前
提示工程你玩对了吗,这5个高阶玩法...
人工智能
广州智造1 小时前
EPLAN教程:流体工程
开发语言·人工智能·python·算法·软件工程·软件构建
CF14年老兵1 小时前
🤯 AI写代码比人类便宜99.9%!但这就是真相吗?
openai·全栈·trae
轻松Ai享生活1 小时前
Week 2 – CUDA Programming Model(超详细教程)
人工智能
wait a minutes1 小时前
【自动驾驶】8月 端到端自动驾驶算法论文(arxiv20250819)
人工智能·机器学习·自动驾驶
HuggingFace1 小时前
HF Papers 直播| 多模态专场
人工智能
聚客AI1 小时前
深度拆解AI大模型从训练框架、推理优化到市场趋势与基础设施挑战
图像处理·人工智能·pytorch·深度学习·机器学习·自然语言处理·transformer