KG+多模态通常应用于医疗病例推理。
多模态大模型较大的一个问题是“语义鸿沟”,如AI能识别一团阴影,但是因为缺乏医学常识,所以不知道这团阴影意味着什么病理改变; 用知识图谱去弥补“感知数据(像素/波形)”与“医学概念”之间的语义鸿沟;
以下是知识图谱的一个应用:
# encoding=utf-8
import sys
from SPARQLWrapper import SPARQLWrapper, JSON, POST
# 配置连接
BLAZEGRAPH_URL = "http://192.168.1.101:9999/blazegraph/namespace/kb/sparql"
print(f"BlazeGraph has been connected: {BLAZEGRAPH_URL}")
sparql = SPARQLWrapper(BLAZEGRAPH_URL)
# 定义数据
ttl_data = """
PREFIX : <http://example.org/medical/>
PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
# 定义实体:肺炎、药物
:Pneumonia rdf:type :Disease ; rdfs:label "肺炎" .
:Amoxicillin rdf:type :Drug ; rdfs:label "阿莫西林" .
:Levofloxacin rdf:type :Drug ; rdfs:label "左氧氟沙星" .
:Azithromycin rdf:type :Drug ; rdfs:label "阿奇霉素" .
# 定义实体:药物类别
:PenicillinClass rdf:type :DrugClass ; rdfs:label "青霉素类" .
:QuinoloneClass rdf:type :DrugClass ; rdfs:label "喹诺酮类" .
:MacrolideClass rdf:type :DrugClass ; rdfs:label "大环内酯类" .
# 定义实体:过敏源
:PenicillinAllergy rdf:type :Allergy ; rdfs:label "青霉素严重过敏" .
# 建立关系:药物 -> 治病
:Amoxicillin :treats :Pneumonia .
:Levofloxacin :treats :Pneumonia .
:Azithromycin :treats :Pneumonia .
# 建立关系:药物 -> 归属类别
:Amoxicillin :belongsTo :PenicillinClass .
:Levofloxacin :belongsTo :QuinoloneClass .
:Azithromycin :belongsTo :MacrolideClass .
# 建立关系:类别 -> 禁忌 (核心逻辑)
:PenicillinClass :hasContraindication :PenicillinAllergy .
"""
# 写入数据
def init_kg():
# 先清除旧数据 (可选,为了纯净)
sparql.setQuery("CLEAR ALL")
sparql.setMethod(POST)
try:
sparql.query()
except:
pass # 第一次运行可能报错,忽略
# 插入新数据
insert_query = f"""
PREFIX : <http://example.org/medical/>
INSERT DATA {{
{ttl_data}
}}
"""
sparql.setQuery(insert_query)
sparql.setMethod(POST)
try:
sparql.query()
print("数据写入成功")
except Exception as e:
print(f"数据写入失败: {e}")
sys.exit(1)
# 逻辑推理演示
def ai_doctor_check(disease_label, allergy_iri):
print(f"诊断疾病: {disease_label}")
print(f"患者禁忌: {allergy_iri.split('/')[-1]}")
# 查找所有能治这个病的药
find_drugs_query = f"""
PREFIX : <http://example.org/medical/>
PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
SELECT ?drug ?drugLabel ?drugClass
WHERE {{
?drug :treats ?disease .
?disease rdfs:label "{disease_label}" .
?drug rdfs:label ?drugLabel .
?drug :belongsTo ?drugClass .
}}
"""
sparql.setQuery(find_drugs_query)
sparql.setReturnFormat(JSON)
results = sparql.query().convert()
candidates = results["results"]["bindings"]
print(f"发现 {len(candidates)} 种候选药...")
recommended = []
# 对每个药进行安全性逻辑推理
for item in candidates:
drug_name = item["drugLabel"]["value"]
class_uri = item["drugClass"]["value"]
# 查询该药物的类别,是否连接到了患者的过敏源
ask_danger = f"""
PREFIX : <http://example.org/medical/>
ASK {{
<{class_uri}> :hasContraindication <{allergy_iri}> .
}}
"""
sparql.setQuery(ask_danger)
is_dangerous = sparql.query().convert()["boolean"]
if is_dangerous:
print(f"剔除 '{drug_name}' -> 因为它属于过敏类别 (禁忌命中!)")
else:
print(f"保留 '{drug_name}' -> 安全")
recommended.append(drug_name)
return recommended
if __name__ == "__main__":
# 初始化数据库
init_kg()
# 模拟场景:患者得了肺炎且对青霉素过敏(这里的URL需要和ttl_data里定义的一致)
patient_allergy = "http://example.org/medical/PenicillinAllergy"
final_list = ai_doctor_check("肺炎", patient_allergy)
print(f"最终推荐处方: {final_list}")