1概览
使用 Semantica 推理模块构建知识图谱、定义规则、执行正向/反向链式推理,并为 AI 推理生成解释。
文档:API 参考
2安装
从 PyPI 安装 Semantica:
pip install semantica
# 或安装所有可选依赖:
pip install semantica[all]
3工作流:构建 KG → 定义规则 → 正向/反向链式推理 → 生成解释
# 安装并升级 Semantica
!pip install -qU semantica
# 导入图构建与推理相关组件
from semantica.kg import GraphBuilder
from semantica.reasoning import Reasoner, ExplanationGenerator
4步骤 1:构建知识图谱
# 步骤 1:构建知识图谱
builder = GraphBuilder()
# 定义实体(人员与地点)
entities = [
{"id": "alice", "type": "Person", "name": "Alice"},
{"id": "bob", "type": "Person", "name": "Bob"},
{"id": "charlie", "type": "Person", "name": "Charlie"},
{"id": "sf", "type": "Location", "name": "San Francisco"},
{"id": "california", "type": "Location", "name": "California"},
]
# 定义关系(亲缘与地理位置)
relationships = [
{"source": "alice", "target": "bob", "type": "parent_of"},
{"source": "bob", "target": "charlie", "type": "parent_of"},
{"source": "sf", "target": "california", "type": "located_in"},
{"source": "alice", "target": "sf", "type": "lives_in"},
]
# 构建知识图谱对象
knowledge_graph = builder.build([{"entities": entities, "relationships": relationships}])
5步骤 2:定义规则
# 初始化推理器
reasoner = Reasoner()
# 使用逻辑语法定义规则
rules = [
"IF parent_of(?a, ?b) AND parent_of(?b, ?c) THEN grandparent_of(?a, ?c)",
"IF lives_in(?x, ?y) AND located_in(?y, ?z) THEN lives_in(?x, ?z)"
]
for rule in rules:
reasoner.add_rule(rule)
6步骤 3:正向链式推理
# 执行正向链式推理以推导新事实
# 推理器可以直接从知识图谱或事实列表推断事实
inferred_facts = reasoner.infer_facts(knowledge_graph)
print(f"Inferred {len(inferred_facts)} new facts:")
for fact in inferred_facts:
print(f" - {fact}")
7步骤 4:反向链式推理
# 定义一个要证明的目标
goal = "grandparent_of(alice, charlie)"
# 执行反向链式推理
proof = reasoner.backward_chain(goal)
if proof:
print(f"Goal '{goal}' proven successfully!")
else:
print(f"Could not prove goal '{goal}'.")
8步骤 5:生成解释
generator = ExplanationGenerator()
# 如果我们有来自反向链式推理的证明,则解释它
if proof:
proof_explanation = generator.generate_explanation(proof)
print("Explanation for backward chaining proof:")
print(proof_explanation.natural_language)
9小结
推理与推断工作流: - 知识图谱已构建 - 推断规则已定义 - 事实已加载到引擎 - 已执行正向链式推理 - 已执行反向链式推理 - 已生成解释
深入探讨:推理模块
本节深入介绍 Semantica 的推理能力。通过稳健、可复现的示例学习规则语法、事实格式、链式推理策略和解释生成。
你将练习的内容 - 使用变量和谓词定义规则 - 以谓词形式加载事实 - 运行正向和反向链式推理 - 生成人类可读的解释
# 初始化推理所需的组件
from semantica.kg import GraphBuilder
from semantica.reasoning import Reasoner, ExplanationGenerator
builder = GraphBuilder()
reasoner = Reasoner()
explainer = ExplanationGenerator()
规则语法
规则使用谓词逻辑,变量以 ? 为前缀。
- 示例:
IF parent_of(?a, ?b) AND parent_of(?b, ?c) THEN grandparent_of(?a, ?c) - 变量在同一规则中的谓词之间统一
- 当条件匹配时,结论会作为新事实添加
# 定义实体与关系,构建知识图谱
entities = [
{"id": "alice", "type": "Person", "name": "Alice"},
{"id": "bob", "type": "Person", "name": "Bob"},
{"id": "charlie", "type": "Person", "name": "Charlie"},
{"id": "sf", "type": "Location", "name": "San Francisco"},
{"id": "california", "type": "Location", "name": "California"}
]
relationships = [
{"source": "alice", "target": "bob", "type": "parent_of"},
{"source": "bob", "target": "charlie", "type": "parent_of"},
{"source": "sf", "target": "california", "type": "located_in"},
{"source": "alice", "target": "sf", "type": "lives_in"}
]
# 构建知识图谱并输出规模
knowledge_graph = builder.build([{"entities": entities, "relationships": relationships}])
print(len(knowledge_graph.get("entities", [])))
print(len(knowledge_graph.get("relationships", [])))
# 定义推理规则并添加到推理器
rules = [
"IF parent_of(?a, ?b) AND parent_of(?b, ?c) THEN grandparent_of(?a, ?c)",
"IF lives_in(?x, ?y) AND located_in(?y, ?z) THEN lives_in(?x, ?z)"
]
for r in rules:
reasoner.add_rule(r)
# 将关系转换为谓词事实并加载到推理器
for rel in relationships:
fact = f"{rel['type']}({rel['source']}, {rel['target']})"
reasoner.add_fact(fact)
# 执行正向链式推理,推导新事实
derived = reasoner.forward_chain()
print(len(derived))
for d in derived:
print(d.conclusion)
# 对多个目标执行反向链式推理并检查是否可证
goals = [
"grandparent_of(alice, charlie)",
"lives_in(alice, california)"
]
for g in goals:
proof = reasoner.backward_chain(g)
print(g)
print(bool(proof))
# 为推导结果与证明生成自然语言解释
if derived:
exp = explainer.generate_explanation(derived[0])
print(exp.natural_language)
goal = "grandparent_of(alice, charlie)"
proof = reasoner.backward_chain(goal)
if proof:
pexp = explainer.generate_explanation(proof)
print(pexp.natural_language)