推理机制
-
forward chaining (正向推理)
-
backward chaining(逆向推理)
假设我们有下面四条规则:
1.如果X呱呱叫并且X吃苍蝇,那么X是只青蛙
2.如果X唧唧咋咋的叫并且X会唱歌,那么X是只金丝雀
3.如果X是青蛙,那么X是绿色的
4.如果X是金丝雀,那么X是黄色的
假设我们又得到两个事实:
- Fritz croaks (Fritz呱呱叫)
- Fritz eats flies(Fritz吃苍蝇)
一方面我们可以通过forward chaining 得出结论:
-
Fritz是只青蛙
-
Fritz是绿色的
另一方面如果我们的目标是证明Fritz是绿色的,那么通过 backward chaining 求解决会更有效率
1.在知识库里要证明Fritz是绿色的,Fritz就需要是一只青蛙
2.若要Fritz是一只青蛙,Fritz就必须呱呱叫而吃苍蝇,而这正好符合已知事实,所以Fritz是绿色的这个命题就被证明了。
看起来backward chaining 好像有点麻烦,不过当forward chaining有太多前进路径,采用backward chaining就会非常高效了,这有点像函数式编程里的惰性求值,只有在需要时计算才会发生。
forward chaining
people.eecs.berkeley.edu/~russell/cl…
Idea: fire any rule whose premises are satisfied in the KB (knowledge base), add its conclusion to the KB, until query is found
rete
A fast algorithm for the many pattern/many object pattern match problem
Key ideas:
- If-then forward chaining rules can be reorganized for efficient pattern matching.
- The RETE algorithm creates a decision tree that combines the patterns in all the rules of the knowledge base.
- Once it has been determined which patterns have been matched by facts, comparisons of variable bindings across patterns must be checked in a relational database table that ‘remembers’ what partial matches have already been tested.
- The key to its efficiency is AWP again: to do partial (incremental) matching - it remembers past test results across iterations of the rule matching loop. Only new facts are tested.
- Variable bindings are saved and reused, rather than recompjuted.
each node, except the root node, is a table representing one relation, and each row of the table records one assertions
To build a rete: • For each antecedent, create an ‘alpha’ node, aka a ‘match’ node (these are the root nodes) • Join a first antecedent and a second antecedent to create a ‘beta’ node, aka a ‘merge’ node • Join each subsequent antecedent with the previous merge node to create a new merge node • For each consequence, create a terminal node, aka execute node, via project, that carries the consequent
drool
DROOLS 是一个基于CHARLES FORGY'S的RETE算法的,易于访问企业策略、易于调整以及易于管理的开源业务规则引擎
zhuanlan.zhihu.com/p/482763434
Drools 被分为两个主要的部分:编译和运行时。编译是将规则描述文件按 ANTLR 3 语法进行解析,对语法进行正确性的检查,然后产生一种中间结构“descr”,descr 用 AST 来描述规则。目前,Drools 支持四种规则描述文件,分别是:drl 文件、 xls 文件、brl 文件和 dsl 文件,其中,常用的描述文件是 drl 文件和 xls 文件,而 xls 文件更易于维护,更直观,更为被业务人员所理解。运行时是将 AST传到 PackageBuilder,由 PackagBuilder来产生 RuleBase,它包含了一个或多个 Package 对象。