Implementation of an Animal Recognition Expert System with Python

  • Investigation production system
  • I know that in the vast sea of ​​search engines, you can see my article is not fate, but you have to hand in your homework
  • Before taking the code to "learn", at least like it
  • The code does not write a GUI, because I don't like this thing, and directly perform human-computer interaction in the terminal. Before using the code, please modify the character encoding and file path according to your own situation
  • The code is terrible. I will add the algorithm to optimize the code after I have the ability.

First question

First create a rule base based on the question map (using a text file)

if 有毛发 then 哺乳动物
if 有乳 then 哺乳动物
if 吃肉 then 食肉动物
if 有犬齿 and 有爪 and 眼向前方 then 食肉动物
if 哺乳动物 and 有蹄 then 有蹄类
if 哺乳动物 and 反刍动物 then 有蹄类
if 哺乳动物 and 食肉动物 and 黄褐色 and 暗斑点 then 豹子
if 哺乳动物 and 食肉动物 and 黄褐色 and 黑条纹 then 老虎
if 有蹄类 and 长脖子 and 长腿 and 暗斑点 then 长颈鹿 
if 有蹄类 and 黑条纹 then 斑马

Code:

rules = {} # 以字典形式存储规则


"""
读取规则库文件中规则,并存放在rules字典中
    - 字典的键:前提
    - 字典的值:结论 
"""
def readRules(filePath):
    global rules
    for line in open(filePath, mode = 'r', encoding = 'utf-8'):
        line = line.replace('if', '').strip()
        temp = line.split(' then ')
        premise = temp[0]
        conclusion = temp[1]
        rules[premise] = conclusion

"""
2. 推理机用这些事实(即:facts变量),依次与知识库中的规则的前提匹配
    - 注意:匹配成功的规则可能不止一条,进行冲突消解
3. 若某规则的前提全被事实满足,则规则可以得到运用
4. 规则的结论部分作为新的事实存储
5. 用更新过的事实再与其它规则的前提匹配,直到不再有可匹配的规则为止
"""
def matchRules(facts): 
    print()
    # 循环匹配
    isEnd = False
    def loop():
        global rules
        nonlocal facts, isEnd
        rules_copy = rules.copy()
        i = 0
        for premise in rules:
            flag = True
            # print(premise+ ':' + rules[premise])
            pre = premise.split(' and ')
            for p in pre:
                if p in facts:
                    pass
                else:
                    flag = False
            if(flag):
                print('该动物:' + premise + ' -> ' + rules[premise])
                for p in pre:
                    facts = facts.replace(p, ' ')
                facts = facts + rules[premise]
                rules_copy.pop(premise)
            else:
                i += 1
        if i == len(rules):
            isEnd = True
        rules = rules_copy

    # 是否推导出最终结论     
    while(not isEnd):
        loop()

    
"""
1. 用户通过人机界面输入一批事实
"""
def ui():
    print('----')
    print('--------动物识别系统--------')
    print('----')
    print('注意!请按照规则库中的前提来阐述事实', end='\n\n')
    facts = input('请输入事实:')
    matchRules(facts)


def main():
    filePath = r'动物识别系统/rules.txt'
    readRules(filePath)
    ui()
    


if __name__ == '__main__':
    main()

Examples of human-computer interaction:

----
--------动物识别系统--------
----
注意!请按照规则库中的前提来阐述事实

请输入事实:该动物有暗斑点、长脖子、长腿、有乳、有蹄。

该动物:有乳 -> 哺乳动物
该动物:哺乳动物 and 有蹄 -> 有蹄类
该动物:有蹄类 and 长脖子 and 长腿 and 暗斑点 -> 长颈鹿

Second question

Replace the rule base with the following rules, and look at the implementation of the system:

  1. Hairy animals are mammals;
  2. Animals with milk are mammals;
  3. Feathered animals are birds;
  4. If the animal can fly and lay eggs, it is a bird;
  5. Meat-eating mammals are called carnivores;
  6. Hounds-tooth claws, and the carnivorous eyes forward;
  7. Ruminant food mammals are ungulates;
  8. Hoofed mammals are hoofed;
  9. The tan with black stripes is a tiger;
  10. The yellowish brown carnivorous carnivorous species is the leopard;
  11. The long-legged long-necked ungulates with dark brown spots are giraffes;
  12. The ungulates with black and white stripes are zebras;
  13. The black-and-white bird with a long neck and no flying legs is an ostrich;
  14. Black and white birds that can't fly well are penguins;
  15. The flying bird is an albatross.

Just rewrite the rule base, or you can create a new text file

if 有毛发 then 哺乳类
if 有奶 then 哺乳类
if 有羽毛 then 鸟类
if 会飞 and 生蛋 then 鸟类
if 吃肉 and 哺乳类 then 食肉动物
if 犬牙 and 利爪 and 眼睛向前 then 食肉类
if 哺乳类 and 反刍食物 then 有蹄类
if 哺乳类 and 有蹄 then 有蹄类
if 食肉类 and 黄褐色 and 黑色条纹 then 老虎
if 食肉类 and 黄褐色 and 暗斑点 then 金钱豹
if 有蹄类 and 长脖 and 长腿 and 黄褐色 and 暗斑点 then 长颈鹿 
if 有蹄类 and 黑白条纹 then 斑马
if 鸟 and 不会飞 and 长脖子 and 长腿 and 黑白色 then 鸵鸟
if 鸟 and 不会飞 and 善游泳 and 黑白色 then 企鹅
if 鸟 and 善飞 then 信天翁
  • Finally, I say that the production system is really stupid. If I do n’t make fuzzy judgments on the input, I will do it.

  • So, my garbage code, you need to look at the premise of the rule base before entering a series of facts during execution; otherwise, you enter 'have milk' in the facts, and 'have milk' in the rule base. I don't recognize your 'milk'

Published 161 original articles · praised 467 · 240,000 views

Guess you like

Origin blog.csdn.net/Zhangguohao666/article/details/105423594