在这篇文章中,我将带您了解知识图谱以及如何从您自己的文本数据构建知识图谱。
什么是知识图谱?
知识图谱也称为语义图,是一种以有效方式存储数据的智能结构。数据以节点和边的形式存储。如图所示,节点表示对象,边缘表示它们之间的关系。知识图谱所表示的数据模型有时被称为资源描述框架(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.nn"
"EXAMPLEn"
"It's a state in the US. It's also the number 1 producer of gold in the US.nn"
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 EXAMPLEnn"
"EXAMPLEn"
"I'm going to the store.nn"
"Output: NONEn"
"END OF EXAMPLEnn"
"EXAMPLEn"
"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 EXAMPLEnn"
"EXAMPLEn"
"{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)