Hello everyone! Today I want to share a very interesting topic – how to build an expert system using Python. An expert system is a program that simulates the decision-making process of human experts, solving problems in specific domains through predefined rules and a knowledge base. Sounds impressive, right? Don’t worry, just follow me step by step, and soon you’ll be able to develop your own expert system!
What is an Expert System?
An expert system mainly consists of three parts:
-
Knowledge Base: Stores rules and facts of the professional field
-
Inference Engine: Makes reasoning judgments based on the rules
-
User Interface: Interacts with the user
Building a Simple Medical Diagnosis Expert System
Let’s learn by creating a simple medical diagnosis system. This system will provide possible disease diagnoses based on symptoms described by the user.
class MedicalExpert:
def __init__(self):
# Initialize knowledge base
self.knowledge_base = {
'Cold': ['Fever', 'Headache', 'Runny Nose'],
'Food Poisoning': ['Abdominal Pain', 'Vomiting', 'Diarrhea'],
'Heat Stroke': ['Dizziness', 'Sweating', 'Thirst']
}
def diagnose(self, symptoms):
possible_diseases = []
for disease, disease_symptoms in self.knowledge_base.items():
# Calculate symptom match
matches = len(set(symptoms) & set(disease_symptoms))
if matches >= 2: # If 2 or more symptoms match
possible_diseases.append(disease)
return possible_diseases
def get_user_input(self):
print("Please describe your symptoms (separate multiple symptoms with commas):")
symptoms = input().split(',')
return symptoms
# Create an expert system instance
doctor = MedicalExpert()
Tip: In practical applications, the knowledge base is usually more complex and may require using a database for storage. Here, we use a dictionary to simplify the implementation.
Adding User Interaction Interface
Let’s add a simple interactive interface for the expert system:
def run_expert_system():
doctor = MedicalExpert()
print("Welcome to the Medical Diagnosis Expert System!")
while True:
symptoms = doctor.get_user_input()
if not symptoms or symptoms[0].lower() == 'quit':
break
diagnosis = doctor.diagnose(symptoms)
if diagnosis:
print("\nBased on your symptoms, the possible diseases are:")
for disease in diagnosis:
print(f"- {disease}")
else:
print("\nSorry, unable to make an accurate diagnosis based on the current symptoms. It is recommended that you go to the hospital.")
print("\nTo continue diagnosing, please enter symptoms; to exit, please enter 'quit'")
# Run the expert system
run_expert_system()
Improvements and Extensions
This simple expert system can undergo many improvements:
-
Add symptom weights:
def add_symptom_weights(self):
self.symptom_weights = {
'Fever': 0.8,
'Headache': 0.5,
'Runny Nose': 0.6
# More symptom weights...
}
-
Increase confidence calculation:
def calculate_confidence(self, matched_symptoms, disease_symptoms):
confidence = sum(self.symptom_weights[s] for s in matched_symptoms) / \
sum(self.symptom_weights[s] for s in disease_symptoms)
return confidence
Tip: In practical applications, the rule base of an expert system needs to be validated by many experts to ensure the accuracy of diagnoses. The examples here are for learning reference only.
Practical Exercises
-
Try to expand the knowledge base by adding more diseases and symptoms
-
Implement a confidence threshold to only display diagnostic results that exceed a certain confidence level
-
Add a recommendation system to provide corresponding suggestions for different diagnostic results
Friends, today’s Python learning journey ends here! We learned how to build a basic expert system. Although this example is simple, it contains the core concepts of expert systems. Remember to practice; you can start with simple rules and gradually improve your expert system. Feel free to ask me any questions in the comments. Wishing everyone a pleasant learning experience and continuous progress in Python!