使用 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)

相关推荐
Raink老师5 分钟前
【AI面试临阵磨枪-79】实时数据 RAG:订单、商家、物流、天气、动态库存
人工智能·面试·职场和发展
脑极体11 分钟前
点亮星河AI+鸿蒙,一座艺术场馆的日神觉醒
人工智能·华为·harmonyos
Cosolar12 分钟前
Chroma向量库面试学习指南
数据库·人工智能·面试·职场和发展·数据库架构
BUG指挥官15 分钟前
Claude Code的自动化编程
人工智能
意图共鸣36 分钟前
意图共鸣科技《认知智能白皮书》——感知与执行分离:认知架构(CA)如何重塑大模型底层结构
人工智能·架构
等一个人的@38 分钟前
让数据自己开口:数睿通智库新增智能问数模块
人工智能·自然语言处理
ZGi.ai38 分钟前
人工审查节点:让自动化工作流多一步人工把关
运维·人工智能·自动化·人机协同·智能体工作流·人工审查
王莎莎-MinerU1 小时前
MinerU 深度技术解析:从架构原理到生产部署的全面指南
css·人工智能·自然语言处理·架构·ocr·个人开发
盘古信息IMS1 小时前
盘古信息IMS V6 8.0重磅发布:以薪火AI数智平台点燃离散制造数智化引擎
大数据·人工智能·制造
weilaieqi11 小时前
从音响制造到AI家庭娱乐生态:不见不散AI智能K歌音响亮相第二十届深圳国际金融博览会
人工智能·制造·娱乐