第七天学习进度--(KBQA)初接触知识图谱之最终改进(四)
通过这几天对于知识图谱的简单构建,简单地了解到了对应的知识图谱中相关的工作原理。
对于networkx构建知识图谱的学习本来打算是昨天就完结了,可是在昨天的最后测试中发现了对应添加动态知识的过程还存在bug,因此今天对其进行最终的改进。
昨天对之前编写的知识图谱添加了动态提取知识的功能,其中对应的动态知识提取的功能在句子的前面还添加了对应的node1节点,在平时时候的时候node1节点并不是一定要放在第一个位置的,因此今天打算通过对昨天提取动态知识的函数进行一个。
昨天编写的最终动态知识提取的时候
可以看到自定义句型中
这一句我们在自定义动态语句的时候,对应的主语前面并没有添加上node1节点,可是最终的结果中,依旧存在node1(揭阳)
因此我们需要对之前的原子处理的部分进行一个改进。让其在处理简单的知识的时候,自动对对应的句子添加上node1,在处理动态知识的时候,则只考虑自定义函数中的返回值。
首先对原子处理部分进行简单的更改(思路:返回时添加一个返回布尔值,当返回布尔值为True时,则添加node1节点)
# 原子信息处理 def nlp_atom_handle(digraph: nx.DiGraph, node1, node2, relation="relation"): ptype = get_nodes_relation(digraph, node1, node2, relation) n_2 = str(node2) n_1 = str(node1) try: n_relation = str(digraph[node1][node2][relation]) except: n_relation= str(digraph[node2][node1][relation]) global dictfunction try: if not dictfunction: dictfunction = {} except: dictfunction = {} if (dictfunction): if (node1 in dictfunction): return dictfunction[node1](digraph, node1, node2, n_relation, relation),False elif (relation in dictfunction): return dictfunction[n_relation](digraph, node1, node2, n_relation, relation),False elif (node2 in dictfunction): return dictfunction[node2](digraph, node1, node2, n_relation, relation),False if (ptype == 4): return "是" + n_2 + "的" + n_relation,True elif (ptype == 3): return n_relation + n_2 + ";" + n_2 + n_relation + n_1,True elif (ptype == 2): return n_2 + n_relation + n_1,True elif (ptype == 1): return n_relation + n_2,True else: return None,True
则对应的nlp中要加入判断来对根据返回布尔值进行相应的操作
# 处理长距离节点关系 def nlp_nodes(digraph: nx.DiGraph, node1, node2, relation="relation"): try: path = nx.dijkstra_path(digraph, node1, node2, weight='weight') # result = str(node1) result="" for i in range(len(path) - 1): if(i==0): _,g_judge=nlp_atom_handle(digraph, path[i], path[i + 1], relation) if not g_judge: result="" else: result+=str(node1) result += nlp_atom_handle(digraph, path[i], path[i + 1], relation)[0] if (i != len(path) - 2): result += "," else: result += "。" except Exception: result = str(node1) + "和" + str(node2) + "没有任何关系。" return result # 单节点释义(What) def nlp_node(digraph: nx.DiGraph, node1, relation="relation"): try: result = str(node1) + "(" + str(digraph.nodes[node1]['attribute']) + ")" path = [one for one in digraph.neighbors(node1)] for i in range(len(path)): if (i == 0): _, g_judge = nlp_atom_handle(digraph, node1, path[i], relation) if not g_judge: result = "" result += nlp_atom_handle(digraph, node1, path[i], relation)[0] if (i != len(path) - 1): result += "," result += "。" prepath = path path = [one for one in digraph.predecessors(node1) if one not in prepath] for i in range(len(path)): result += nlp_atom_handle(digraph, node1, path[i], relation)[0] if (i != len(path) - 1): result += "," else: result += "。" except Exception: result = "知识图谱中不存在" + str(node1) return result
在执行同样的代码之后
执行结果如下:
可以看到最终的结果已经没有了node1(揭阳)的主语。