Python 中(专家系统)的后向和前向链接算法

Backward and forward chaining algorithm for (expert system) in Python

我正在寻找后向和前向链接的算法来实现它 Python。我在网上看了看,但我没有找到太多。我也看了维基百科,但我只是找到了一些规则,但没有找到算法。

我知道你最初用 Python 标记了你之前的问题,所以我将其限制为 Python。

寻找代码示例时,一个不错的地方是 Github repositories. Querying for backward chaining and then limiting the results to Python will yield this query 您可以对 forward chaining 执行相同的操作。

请注意,您必须找到您喜欢的代码示例,然后在使用它之前对其进行全面测试。那里有很好的例子,但更有可能是不正确的尝试。计划与他们一起度过几天并创建大量测试用例。那里的所有代码都没有保证。

如果您只想要算法,请查找 Artificial Intelligence 的书籍,例如 Russell 和 Norvig 的 Artificial Intelligence ... by George F Luger or Artificial Intelligence ...

前向链接推理引擎可以在 Python 中相对容易地实现。这是推理规则列表:

mammal(A) ==> vertebrate(A).
vertebrate(A) ==> animal(A).
vertebrate(A),flying(A) ==> bird(A).
vertebrate("duck").
flying("duck").
mammal("cat").

这些规则可以翻译成Python:

global facts
global is_changed

is_changed = True
facts = [["vertebrate","duck"],["flying","duck"],["mammal","cat"]]

def assert_fact(fact):
    global facts
    global is_changed
    if not fact in facts:
        facts += [fact]
        is_changed = True

while is_changed:
    is_changed = False
    for A1 in facts:
        if A1[0] == "mammal":
            assert_fact(["vertebrate",A1[1]])
        if A1[0] == "vertebrate":
            assert_fact(["animal",A1[1]])
        if A1[0] == "vertebrate" and ["flying",A1[1]] in facts:
            assert_fact(["bird",A1[1]])

print(facts)

根据初始事实集,推理引擎生成此列表:

[['vertebrate', 'duck'], ['flying', 'duck'], ['mammal', 'cat'], ['animal', 'duck'], ['bird', 'duck'], ['vertebrate', 'cat'], ['animal', 'cat']]
global facts
global is_changed

is_changed = True
facts = [["plant","mango"],["eating","mango"],["seed","sprouts"]]

def assert_fact(fact):
    global facts
    global is_changed
    if not fact in facts:
        facts += [fact]
        is_changed = True

while is_changed:
    is_changed = False
    for A1 in facts:
        if A1[0] == "seed":
            assert_fact(["plant",A1[1]])
        if A1[0] == "plant":
            assert_fact(["fruit",A1[1]])
        if A1[0] == "plant" and ["eating",A1[1]] in facts:
            assert_fact(["human",A1[1]])

print(facts)