SlideShare a Scribd company logo
1 of 34
Download to read offline
Expert System With Python
Ahmad Hussein
ahmadhussein.ah7@gmail.com
Lecture 2: The Basics
CONTENT OVERVIEW
• What is CLIPS?
• CLIPS Characteristics.
• What is PyKnow?
• Facts
• DefFacts
• Rules
• Knowledge Engine
• Conditional Elements: Composing Patterns Together.
• Field Constraints: FC for sort.
• Composing FCs: &, | and ~.
• Variable Binding: The << Operator.
What is CLIPS?
• CLIPS is a multiparadigm programming language that provides
support for:
• Rule-based
• Object-oriented
• Procedural programming
CLIPS Characteristics
• CLIPS is an acronym for
• C Language Integrated Production System.
• CLIPS was designed using the C language at the NASA/Johnson Space
Center.
What is PyKnow?
• PyKnow is a Python library alternative to CLIPS.
• Difference between CLIPS and PyKnow:
• CLIPS is a programming language, PyKnow is a Python library. This imposes
some limitations on the constructions we can do (specially on the LHS of a
rule).
• CLIPS is written in C, PyKnow in Python. A noticeable impact in performance is
to be expected.
• In CLIPS you add facts using assert, in Python assert is a keyword, so we use
declare instead.
The Basics
• Facts
• DefFacts
• Rules
• Knowledge Engine
Facts
• Facts are the basic unit of information of PyKnow. They are used by
the system to reason about the problem.
Let’s enumerate some facts about Facts:
1. The class Fact is a subclass of dict.
f = Fact(a=1, b=2)
print(f['a’])
# 1
Facts
2. Therefore a Fact does not maintain an internal order of items.
f = Fact(a=1, b=2) # Order is arbitrary
# f = Fact(a=1, b=2)
Facts
3. In contrast to dict, you can create a Fact without keys (only values),
and Fact will create a numeric index for your values.
f = Fact('x', 'y', 'z')
print(f[0])
# x
Facts
4. You can mix autonumeric values with key-values, but autonumeric
must be declared first.
f = Fact('x', 'y', 'z', a=1, b=2)
print(f[0])
# x
print(f['a’])
# 1
Facts
5. You can subclass Fact to express different kinds of data or extend it
with your custom functionality.
class Alert(Fact):
pass
class Status(Fact):
pass
f1 = Alert(color = 'red')
f2 = Status(state = 'critical')
print(f1['color’]) # red
print(f2['state’]) # 'critical
Facts vs Patterns
• The difference between Facts and Patterns is small. In fact, Patterns
are just Facts containing Pattern Conditional Elements instead of
regular data. They are used only in the LHS of a rule.
• If you don’t provide the content of a pattern as a PCE, PyKnow will
enclose the value in a LiteralPCE automatically
• for you.
• Also, you can’t declare any Fact containing a PCE, if you do, you will
receive a nice exception back.
DefFacts
• Most of the time expert systems needs a set of facts to be present for the
system to work. This is the purpose of the DefFacts decorator.
• All DefFacts inside a KnowledgeEngine will be called every time the reset
method is called.
@DefFacts()
def needed_data():
yield Fact(best_color="red")
yield Fact(best_body="medium")
yield Fact(best_sweetness="dry")
Rules
• In PyKnow a rule is a callable, decorated with Rule.
• Rules have two components, LHS (left-hand-side) and RHS (right-
hand-side).
• The LHS describes (using patterns) the conditions on which the rule * should
be executed (or fired).
• The RHS is the set of actions to perform when the rule is fired.
• For a Fact to match a Pattern, all pattern restrictions must be True
when the Fact is evaluated against it.
Rules
Example:
• This rule will match with every instance of ‘MyFact’.
class MyFact (Fact):
pass
@Rule(MyFact()) # This is the LHS
def matchWithEveryMyfact():
# This is the RHS
pass
Rules
Example:
• Match with every Fact which:
• f[0] == 'animal'
• f['family'] == 'felinae'
class MyFact (Fact):
pass
@Rule(Fact('animal', family='felinae’))
def match_with_cats ():
print("Meow!")
Rules
Example:
• The user is a privileged one and we are not dropping privileges.
@Rule((User('admin') | User('root’))
& ~Fact('drop-privileges'))
def the_user_has_power():
enable_superpowers()
KnowledgeEngine
• This is the place where all the magic happens.
• The first step is to make a subclass of it and use Rule to decorate its
methods.
• After that, you can instantiate it, populate it with facts, and finally run
it.
KnowledgeEngine
Example:
from pyknow import *
class Greetings(KnowledgeEngine):
@DefFacts()
def _initial_action(self):
yield Fact(action="greet")
@Rule(Fact(action='greet'),NOT(Fact(name=W())))
def ask_name(self):
self.declare(Fact(name=input("What's your name? ")))
continue
KnowledgeEngine
Example:
@Rule(Fact(action='greet’),NOT(Fact(location=W())))
def ask_location(self):
self.declare(Fact(location=input("Where are you? ")))
@Rule(Fact(action='greet'),Fact(name="name" << W()),
Fact(location="location" << W()))
def greet(self, name, location):
print("Hi %s! How is the weather in %s?" % (name, location))
continue
KnowledgeEngine
Example:
engine = Greetings()
engine.reset() # Prepare the engine for the execution.
engine.run() # Run it!
Output:
What's your name? Roberto
Where are you? Madrid
Hi Roberto! How is the weather in Madrid?
Conditional Elements: Composing Patterns Together
AND:
• AND creates a composed pattern containing all Facts passed as
arguments. All of the passed patterns must match for the composed
pattern to match.
• Match if two facts are declared, one matching Fact(1) and other
matching Fact(2).
@Rule(AND(Fact(1),Fact(2)))
def _():
pass
Conditional Elements: Composing Patterns Together
OR:
• OR creates a composed pattern in which any of the given pattern will
make the rule match.
• Match if a fact matching Fact(1) exists and/or a fact matching Fact(2)
exists.
@Rule(OR(Fact(1),Fact(2)))
def _():
pass
Conditional Elements: Composing Patterns Together
NOT:
• This element matches if the given pattern does not match with any
fact or combination of facts. Therefore this element matches the
absence of the given pattern.
• Match if no fact match with Fact(1).
@Rule(NOT(Fact(1))
def _():
pass
Conditional Elements: Composing Patterns Together
EXISTS:
• This CE receives a pattern and matches if one or more facts matches
this pattern. This will match only once while one or more matching
facts exists and will stop matching when there is no matching facts.
• Match once when one or more Color exists.
@Rule(EXISTS(Color()))
def _():
pass
Conditional Elements: Composing Patterns Together
FORALL:
• The FORALL conditional element provides a mechanism for
determining if a group of specified CEs is satisfied for every
occurrence of another specified CE.
• Match once when one or more Color exists.
@Rule(FORALL(Student(W('name')),
Reading(W('name')),
Writing(W('name')),
Arithmetic(W('name')))
def all_students_passed():
pass
Field Constraints: FC for sort
L (Literal Field Constraint):
• This element performs an exact match with the given value. The
matching is done using the equality operator ==.
• Match if the first element is exactly 3.
@Rule(Fact(L(3)))
def _():
pass
Field Constraints: FC for sort
W (Wildcard Field Constraint):
• This element matches with any value.
• Match if some fact is declared with the key mykey.
@Rule(Fact(mykey=W()))
def _():
pass
Field Constraints: FC for sort
P (Predicate Field Constraint):
• The match of this element is the result of applying the given callable
to the fact-extracted value. If the callable returns True the FC will
match, in other case the FC will not match.
• Match if some fact is declared whose first parameter is an instance of
int.
@Rule(Fact(P(lambda x: isinstance(x, int))))
def _():
pass
Composing FCs: &, | and ~
ANDFC() - &:
• The composed FC matches if all the given FC match.
• Match if key x of Point is a value between 0 and 255.
@Rule(x=P(lambda x: x >= 0) & P(lambda x: x <= 255)))
def _():
pass
Composing FCs: &, | and ~
ORFC() - |:
• The composed FC matches if any of the given FC matches.
• Match if name is either Alice or Bob.
@Rule(Fact(name=L('Alice') | L('Bob’)))
def _():
pass
Composing FCs: &, | and ~
NOTFC() - ~:
• This composed FC negates the given FC, reversing the logic. If the
given FC matches this will not and vice versa.
• Match if name is not Charlie.
@Rule(Fact(name=~L('Charlie')))
def _():
pass
Variable Binding: The << Operator
• Any patterns and some FCs can be binded to a name using the <<
operator.
• Example 1:
• The first value of the matching fact will be binded to the name value
and passed to the function when fired.
@Rule(Fact('value' << W()))
def _(value):
pass
Variable Binding: The << Operator
• Any patterns and some FCs can be binded to a name using the <<
operator.
• Example 2:
• The whole matching fact will be binded to f1 and passed to the
function when fired.
@Rule(Fact(‘f1' << Fact())
def _(f1):
pass

More Related Content

What's hot

Unsupervised learning (clustering)
Unsupervised learning (clustering)Unsupervised learning (clustering)
Unsupervised learning (clustering)Pravinkumar Landge
 
Machine Learning - Accuracy and Confusion Matrix
Machine Learning - Accuracy and Confusion MatrixMachine Learning - Accuracy and Confusion Matrix
Machine Learning - Accuracy and Confusion MatrixAndrew Ferlitsch
 
Artificial intelligence and knowledge representation
Artificial intelligence and knowledge representationArtificial intelligence and knowledge representation
Artificial intelligence and knowledge representationLikan Patra
 
BDI - Aula 09 - SQL e Algebra Relacional
BDI - Aula 09 - SQL e Algebra RelacionalBDI - Aula 09 - SQL e Algebra Relacional
BDI - Aula 09 - SQL e Algebra RelacionalRodrigo Kiyoshi Saito
 
Introduction to CLIPS Expert System
Introduction to CLIPS Expert SystemIntroduction to CLIPS Expert System
Introduction to CLIPS Expert SystemMotaz Saad
 
rule-based classifier
rule-based classifierrule-based classifier
rule-based classifierSean Chiu
 
Underfitting and Overfitting in Machine Learning
Underfitting and Overfitting in Machine LearningUnderfitting and Overfitting in Machine Learning
Underfitting and Overfitting in Machine LearningAbdullah al Mamun
 
What is Apriori Algorithm | Edureka
What is Apriori Algorithm | EdurekaWhat is Apriori Algorithm | Edureka
What is Apriori Algorithm | EdurekaEdureka!
 
Oracle python pandas merge DataFrames
Oracle python pandas merge DataFramesOracle python pandas merge DataFrames
Oracle python pandas merge DataFramesJohan Louwers
 
Understanding Association Rule Mining
Understanding Association Rule MiningUnderstanding Association Rule Mining
Understanding Association Rule MiningMohit Rajput
 
Binary Search Tree in Data Structure
Binary Search Tree in Data StructureBinary Search Tree in Data Structure
Binary Search Tree in Data StructureDharita Chokshi
 
Machine Learning - Splitting Datasets
Machine Learning - Splitting DatasetsMachine Learning - Splitting Datasets
Machine Learning - Splitting DatasetsAndrew Ferlitsch
 
Machine learning with ADA Boost
Machine learning with ADA BoostMachine learning with ADA Boost
Machine learning with ADA BoostAman Patel
 
Unit3:Informed and Uninformed search
Unit3:Informed and Uninformed searchUnit3:Informed and Uninformed search
Unit3:Informed and Uninformed searchTekendra Nath Yogi
 
Estrutura de Dados II - Apresentação da Disciplina
Estrutura de Dados II - Apresentação da DisciplinaEstrutura de Dados II - Apresentação da Disciplina
Estrutura de Dados II - Apresentação da DisciplinaDaniel Arndt Alves
 
2.4 rule based classification
2.4 rule based classification2.4 rule based classification
2.4 rule based classificationKrish_ver2
 

What's hot (20)

Random Forest Algoritması
Random Forest AlgoritmasıRandom Forest Algoritması
Random Forest Algoritması
 
Unsupervised learning (clustering)
Unsupervised learning (clustering)Unsupervised learning (clustering)
Unsupervised learning (clustering)
 
Machine Learning - Accuracy and Confusion Matrix
Machine Learning - Accuracy and Confusion MatrixMachine Learning - Accuracy and Confusion Matrix
Machine Learning - Accuracy and Confusion Matrix
 
Artificial intelligence and knowledge representation
Artificial intelligence and knowledge representationArtificial intelligence and knowledge representation
Artificial intelligence and knowledge representation
 
BDI - Aula 09 - SQL e Algebra Relacional
BDI - Aula 09 - SQL e Algebra RelacionalBDI - Aula 09 - SQL e Algebra Relacional
BDI - Aula 09 - SQL e Algebra Relacional
 
Introduction to CLIPS Expert System
Introduction to CLIPS Expert SystemIntroduction to CLIPS Expert System
Introduction to CLIPS Expert System
 
rule-based classifier
rule-based classifierrule-based classifier
rule-based classifier
 
Underfitting and Overfitting in Machine Learning
Underfitting and Overfitting in Machine LearningUnderfitting and Overfitting in Machine Learning
Underfitting and Overfitting in Machine Learning
 
What is Apriori Algorithm | Edureka
What is Apriori Algorithm | EdurekaWhat is Apriori Algorithm | Edureka
What is Apriori Algorithm | Edureka
 
Oracle python pandas merge DataFrames
Oracle python pandas merge DataFramesOracle python pandas merge DataFrames
Oracle python pandas merge DataFrames
 
Confusion Matrix Explained
Confusion Matrix ExplainedConfusion Matrix Explained
Confusion Matrix Explained
 
Understanding Association Rule Mining
Understanding Association Rule MiningUnderstanding Association Rule Mining
Understanding Association Rule Mining
 
Aula7 diagrama classes
Aula7 diagrama classesAula7 diagrama classes
Aula7 diagrama classes
 
Binary Search Tree in Data Structure
Binary Search Tree in Data StructureBinary Search Tree in Data Structure
Binary Search Tree in Data Structure
 
Machine Learning - Splitting Datasets
Machine Learning - Splitting DatasetsMachine Learning - Splitting Datasets
Machine Learning - Splitting Datasets
 
Machine learning with ADA Boost
Machine learning with ADA BoostMachine learning with ADA Boost
Machine learning with ADA Boost
 
Unit3:Informed and Uninformed search
Unit3:Informed and Uninformed searchUnit3:Informed and Uninformed search
Unit3:Informed and Uninformed search
 
Estrutura de Dados II - Apresentação da Disciplina
Estrutura de Dados II - Apresentação da DisciplinaEstrutura de Dados II - Apresentação da Disciplina
Estrutura de Dados II - Apresentação da Disciplina
 
Random forest
Random forestRandom forest
Random forest
 
2.4 rule based classification
2.4 rule based classification2.4 rule based classification
2.4 rule based classification
 

Similar to Expert system with python -2

Introduction to Boost regex
Introduction to Boost regexIntroduction to Boost regex
Introduction to Boost regexYongqiang Li
 
An Introduction To Python - Final Exam Review
An Introduction To Python - Final Exam ReviewAn Introduction To Python - Final Exam Review
An Introduction To Python - Final Exam ReviewBlue Elephant Consulting
 
An Introduction : Python
An Introduction : PythonAn Introduction : Python
An Introduction : PythonRaghu Kumar
 
LecccccccccccccProgrammingLecture-09.pdf
LecccccccccccccProgrammingLecture-09.pdfLecccccccccccccProgrammingLecture-09.pdf
LecccccccccccccProgrammingLecture-09.pdfAmirMohamedNabilSale
 
PYTHON -Chapter 2 - Functions, Exception, Modules and Files -MAULIK BOR...
PYTHON -Chapter 2 - Functions,   Exception, Modules  and    Files -MAULIK BOR...PYTHON -Chapter 2 - Functions,   Exception, Modules  and    Files -MAULIK BOR...
PYTHON -Chapter 2 - Functions, Exception, Modules and Files -MAULIK BOR...Maulik Borsaniya
 
Basics of Functional Programming
Basics of Functional ProgrammingBasics of Functional Programming
Basics of Functional ProgrammingSartaj Singh
 
Introduction to Python for Plone developers
Introduction to Python for Plone developersIntroduction to Python for Plone developers
Introduction to Python for Plone developersJim Roepcke
 
Python For Data Science.pptx
Python For Data Science.pptxPython For Data Science.pptx
Python For Data Science.pptxrohithprabhas1
 
Designing A Syntax Based Retrieval System03
Designing A Syntax Based Retrieval System03Designing A Syntax Based Retrieval System03
Designing A Syntax Based Retrieval System03Avelin Huo
 
Basic concept of Python.pptx includes design tool, identifier, variables.
Basic concept of Python.pptx includes design tool, identifier, variables.Basic concept of Python.pptx includes design tool, identifier, variables.
Basic concept of Python.pptx includes design tool, identifier, variables.supriyasarkar38
 
Ti1220 Lecture 7: Polymorphism
Ti1220 Lecture 7: PolymorphismTi1220 Lecture 7: Polymorphism
Ti1220 Lecture 7: PolymorphismEelco Visser
 
Python_Unit-1_PPT_Data Types.pptx
Python_Unit-1_PPT_Data Types.pptxPython_Unit-1_PPT_Data Types.pptx
Python_Unit-1_PPT_Data Types.pptxSahajShrimal1
 
Programming with Python - Week 3
Programming with Python - Week 3Programming with Python - Week 3
Programming with Python - Week 3Ahmet Bulut
 
Introduction To Programming with Python-1
Introduction To Programming with Python-1Introduction To Programming with Python-1
Introduction To Programming with Python-1Syed Farjad Zia Zaidi
 
Intro To C++ - Class #17: Pointers!, Objects Talking To Each Other
Intro To C++ - Class #17: Pointers!, Objects Talking To Each OtherIntro To C++ - Class #17: Pointers!, Objects Talking To Each Other
Intro To C++ - Class #17: Pointers!, Objects Talking To Each OtherBlue Elephant Consulting
 
Object Oriented PHP - PART-2
Object Oriented PHP - PART-2Object Oriented PHP - PART-2
Object Oriented PHP - PART-2Jalpesh Vasa
 
Python operators (1).pptx
Python operators (1).pptxPython operators (1).pptx
Python operators (1).pptxVaniHarave
 

Similar to Expert system with python -2 (20)

Apriori.pptx
Apriori.pptxApriori.pptx
Apriori.pptx
 
Introduction to Boost regex
Introduction to Boost regexIntroduction to Boost regex
Introduction to Boost regex
 
Lecture 08.pptx
Lecture 08.pptxLecture 08.pptx
Lecture 08.pptx
 
An Introduction To Python - Final Exam Review
An Introduction To Python - Final Exam ReviewAn Introduction To Python - Final Exam Review
An Introduction To Python - Final Exam Review
 
Python Week 1.pptx
Python Week 1.pptxPython Week 1.pptx
Python Week 1.pptx
 
An Introduction : Python
An Introduction : PythonAn Introduction : Python
An Introduction : Python
 
LecccccccccccccProgrammingLecture-09.pdf
LecccccccccccccProgrammingLecture-09.pdfLecccccccccccccProgrammingLecture-09.pdf
LecccccccccccccProgrammingLecture-09.pdf
 
PYTHON -Chapter 2 - Functions, Exception, Modules and Files -MAULIK BOR...
PYTHON -Chapter 2 - Functions,   Exception, Modules  and    Files -MAULIK BOR...PYTHON -Chapter 2 - Functions,   Exception, Modules  and    Files -MAULIK BOR...
PYTHON -Chapter 2 - Functions, Exception, Modules and Files -MAULIK BOR...
 
Basics of Functional Programming
Basics of Functional ProgrammingBasics of Functional Programming
Basics of Functional Programming
 
Introduction to Python for Plone developers
Introduction to Python for Plone developersIntroduction to Python for Plone developers
Introduction to Python for Plone developers
 
Python For Data Science.pptx
Python For Data Science.pptxPython For Data Science.pptx
Python For Data Science.pptx
 
Designing A Syntax Based Retrieval System03
Designing A Syntax Based Retrieval System03Designing A Syntax Based Retrieval System03
Designing A Syntax Based Retrieval System03
 
Basic concept of Python.pptx includes design tool, identifier, variables.
Basic concept of Python.pptx includes design tool, identifier, variables.Basic concept of Python.pptx includes design tool, identifier, variables.
Basic concept of Python.pptx includes design tool, identifier, variables.
 
Ti1220 Lecture 7: Polymorphism
Ti1220 Lecture 7: PolymorphismTi1220 Lecture 7: Polymorphism
Ti1220 Lecture 7: Polymorphism
 
Python_Unit-1_PPT_Data Types.pptx
Python_Unit-1_PPT_Data Types.pptxPython_Unit-1_PPT_Data Types.pptx
Python_Unit-1_PPT_Data Types.pptx
 
Programming with Python - Week 3
Programming with Python - Week 3Programming with Python - Week 3
Programming with Python - Week 3
 
Introduction To Programming with Python-1
Introduction To Programming with Python-1Introduction To Programming with Python-1
Introduction To Programming with Python-1
 
Intro To C++ - Class #17: Pointers!, Objects Talking To Each Other
Intro To C++ - Class #17: Pointers!, Objects Talking To Each OtherIntro To C++ - Class #17: Pointers!, Objects Talking To Each Other
Intro To C++ - Class #17: Pointers!, Objects Talking To Each Other
 
Object Oriented PHP - PART-2
Object Oriented PHP - PART-2Object Oriented PHP - PART-2
Object Oriented PHP - PART-2
 
Python operators (1).pptx
Python operators (1).pptxPython operators (1).pptx
Python operators (1).pptx
 

More from Ahmad Hussein

Knowledge Representation Methods
Knowledge Representation MethodsKnowledge Representation Methods
Knowledge Representation MethodsAhmad Hussein
 
Knowledge-Base Systems Homework - 2019
Knowledge-Base Systems Homework - 2019Knowledge-Base Systems Homework - 2019
Knowledge-Base Systems Homework - 2019Ahmad Hussein
 
Knowledge based systems homework
Knowledge based systems homeworkKnowledge based systems homework
Knowledge based systems homeworkAhmad Hussein
 
Python introduction 2
Python introduction 2Python introduction 2
Python introduction 2Ahmad Hussein
 
Python introduction 1
Python introduction 1  Python introduction 1
Python introduction 1 Ahmad Hussein
 

More from Ahmad Hussein (6)

Knowledge Representation Methods
Knowledge Representation MethodsKnowledge Representation Methods
Knowledge Representation Methods
 
Knowledge-Base Systems Homework - 2019
Knowledge-Base Systems Homework - 2019Knowledge-Base Systems Homework - 2019
Knowledge-Base Systems Homework - 2019
 
Design Patterns
Design PatternsDesign Patterns
Design Patterns
 
Knowledge based systems homework
Knowledge based systems homeworkKnowledge based systems homework
Knowledge based systems homework
 
Python introduction 2
Python introduction 2Python introduction 2
Python introduction 2
 
Python introduction 1
Python introduction 1  Python introduction 1
Python introduction 1
 

Recently uploaded

Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...aditisharan08
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...OnePlan Solutions
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...MyIntelliSource, Inc.
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)OPEN KNOWLEDGE GmbH
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantAxelRicardoTrocheRiq
 
Project Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationProject Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationkaushalgiri8080
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...ICS
 
The Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfThe Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfPower Karaoke
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfkalichargn70th171
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...gurkirankumar98700
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEOrtus Solutions, Corp
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comFatema Valibhai
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfjoe51371421
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxTier1 app
 
DNT_Corporate presentation know about us
DNT_Corporate presentation know about usDNT_Corporate presentation know about us
DNT_Corporate presentation know about usDynamic Netsoft
 
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...Christina Lin
 
cybersecurity notes for mca students for learning
cybersecurity notes for mca students for learningcybersecurity notes for mca students for learning
cybersecurity notes for mca students for learningVitsRangannavar
 
chapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptchapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptkotipi9215
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsAlberto González Trastoy
 

Recently uploaded (20)

Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...
 
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service Consultant
 
Project Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationProject Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanation
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
The Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfThe Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdf
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdf
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
 
DNT_Corporate presentation know about us
DNT_Corporate presentation know about usDNT_Corporate presentation know about us
DNT_Corporate presentation know about us
 
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
 
cybersecurity notes for mca students for learning
cybersecurity notes for mca students for learningcybersecurity notes for mca students for learning
cybersecurity notes for mca students for learning
 
chapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptchapter--4-software-project-planning.ppt
chapter--4-software-project-planning.ppt
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 

Expert system with python -2

  • 1. Expert System With Python Ahmad Hussein ahmadhussein.ah7@gmail.com Lecture 2: The Basics
  • 2. CONTENT OVERVIEW • What is CLIPS? • CLIPS Characteristics. • What is PyKnow? • Facts • DefFacts • Rules • Knowledge Engine • Conditional Elements: Composing Patterns Together. • Field Constraints: FC for sort. • Composing FCs: &, | and ~. • Variable Binding: The << Operator.
  • 3. What is CLIPS? • CLIPS is a multiparadigm programming language that provides support for: • Rule-based • Object-oriented • Procedural programming
  • 4. CLIPS Characteristics • CLIPS is an acronym for • C Language Integrated Production System. • CLIPS was designed using the C language at the NASA/Johnson Space Center.
  • 5. What is PyKnow? • PyKnow is a Python library alternative to CLIPS. • Difference between CLIPS and PyKnow: • CLIPS is a programming language, PyKnow is a Python library. This imposes some limitations on the constructions we can do (specially on the LHS of a rule). • CLIPS is written in C, PyKnow in Python. A noticeable impact in performance is to be expected. • In CLIPS you add facts using assert, in Python assert is a keyword, so we use declare instead.
  • 6. The Basics • Facts • DefFacts • Rules • Knowledge Engine
  • 7. Facts • Facts are the basic unit of information of PyKnow. They are used by the system to reason about the problem. Let’s enumerate some facts about Facts: 1. The class Fact is a subclass of dict. f = Fact(a=1, b=2) print(f['a’]) # 1
  • 8. Facts 2. Therefore a Fact does not maintain an internal order of items. f = Fact(a=1, b=2) # Order is arbitrary # f = Fact(a=1, b=2)
  • 9. Facts 3. In contrast to dict, you can create a Fact without keys (only values), and Fact will create a numeric index for your values. f = Fact('x', 'y', 'z') print(f[0]) # x
  • 10. Facts 4. You can mix autonumeric values with key-values, but autonumeric must be declared first. f = Fact('x', 'y', 'z', a=1, b=2) print(f[0]) # x print(f['a’]) # 1
  • 11. Facts 5. You can subclass Fact to express different kinds of data or extend it with your custom functionality. class Alert(Fact): pass class Status(Fact): pass f1 = Alert(color = 'red') f2 = Status(state = 'critical') print(f1['color’]) # red print(f2['state’]) # 'critical
  • 12. Facts vs Patterns • The difference between Facts and Patterns is small. In fact, Patterns are just Facts containing Pattern Conditional Elements instead of regular data. They are used only in the LHS of a rule. • If you don’t provide the content of a pattern as a PCE, PyKnow will enclose the value in a LiteralPCE automatically • for you. • Also, you can’t declare any Fact containing a PCE, if you do, you will receive a nice exception back.
  • 13. DefFacts • Most of the time expert systems needs a set of facts to be present for the system to work. This is the purpose of the DefFacts decorator. • All DefFacts inside a KnowledgeEngine will be called every time the reset method is called. @DefFacts() def needed_data(): yield Fact(best_color="red") yield Fact(best_body="medium") yield Fact(best_sweetness="dry")
  • 14. Rules • In PyKnow a rule is a callable, decorated with Rule. • Rules have two components, LHS (left-hand-side) and RHS (right- hand-side). • The LHS describes (using patterns) the conditions on which the rule * should be executed (or fired). • The RHS is the set of actions to perform when the rule is fired. • For a Fact to match a Pattern, all pattern restrictions must be True when the Fact is evaluated against it.
  • 15. Rules Example: • This rule will match with every instance of ‘MyFact’. class MyFact (Fact): pass @Rule(MyFact()) # This is the LHS def matchWithEveryMyfact(): # This is the RHS pass
  • 16. Rules Example: • Match with every Fact which: • f[0] == 'animal' • f['family'] == 'felinae' class MyFact (Fact): pass @Rule(Fact('animal', family='felinae’)) def match_with_cats (): print("Meow!")
  • 17. Rules Example: • The user is a privileged one and we are not dropping privileges. @Rule((User('admin') | User('root’)) & ~Fact('drop-privileges')) def the_user_has_power(): enable_superpowers()
  • 18. KnowledgeEngine • This is the place where all the magic happens. • The first step is to make a subclass of it and use Rule to decorate its methods. • After that, you can instantiate it, populate it with facts, and finally run it.
  • 19. KnowledgeEngine Example: from pyknow import * class Greetings(KnowledgeEngine): @DefFacts() def _initial_action(self): yield Fact(action="greet") @Rule(Fact(action='greet'),NOT(Fact(name=W()))) def ask_name(self): self.declare(Fact(name=input("What's your name? "))) continue
  • 20. KnowledgeEngine Example: @Rule(Fact(action='greet’),NOT(Fact(location=W()))) def ask_location(self): self.declare(Fact(location=input("Where are you? "))) @Rule(Fact(action='greet'),Fact(name="name" << W()), Fact(location="location" << W())) def greet(self, name, location): print("Hi %s! How is the weather in %s?" % (name, location)) continue
  • 21. KnowledgeEngine Example: engine = Greetings() engine.reset() # Prepare the engine for the execution. engine.run() # Run it! Output: What's your name? Roberto Where are you? Madrid Hi Roberto! How is the weather in Madrid?
  • 22. Conditional Elements: Composing Patterns Together AND: • AND creates a composed pattern containing all Facts passed as arguments. All of the passed patterns must match for the composed pattern to match. • Match if two facts are declared, one matching Fact(1) and other matching Fact(2). @Rule(AND(Fact(1),Fact(2))) def _(): pass
  • 23. Conditional Elements: Composing Patterns Together OR: • OR creates a composed pattern in which any of the given pattern will make the rule match. • Match if a fact matching Fact(1) exists and/or a fact matching Fact(2) exists. @Rule(OR(Fact(1),Fact(2))) def _(): pass
  • 24. Conditional Elements: Composing Patterns Together NOT: • This element matches if the given pattern does not match with any fact or combination of facts. Therefore this element matches the absence of the given pattern. • Match if no fact match with Fact(1). @Rule(NOT(Fact(1)) def _(): pass
  • 25. Conditional Elements: Composing Patterns Together EXISTS: • This CE receives a pattern and matches if one or more facts matches this pattern. This will match only once while one or more matching facts exists and will stop matching when there is no matching facts. • Match once when one or more Color exists. @Rule(EXISTS(Color())) def _(): pass
  • 26. Conditional Elements: Composing Patterns Together FORALL: • The FORALL conditional element provides a mechanism for determining if a group of specified CEs is satisfied for every occurrence of another specified CE. • Match once when one or more Color exists. @Rule(FORALL(Student(W('name')), Reading(W('name')), Writing(W('name')), Arithmetic(W('name'))) def all_students_passed(): pass
  • 27. Field Constraints: FC for sort L (Literal Field Constraint): • This element performs an exact match with the given value. The matching is done using the equality operator ==. • Match if the first element is exactly 3. @Rule(Fact(L(3))) def _(): pass
  • 28. Field Constraints: FC for sort W (Wildcard Field Constraint): • This element matches with any value. • Match if some fact is declared with the key mykey. @Rule(Fact(mykey=W())) def _(): pass
  • 29. Field Constraints: FC for sort P (Predicate Field Constraint): • The match of this element is the result of applying the given callable to the fact-extracted value. If the callable returns True the FC will match, in other case the FC will not match. • Match if some fact is declared whose first parameter is an instance of int. @Rule(Fact(P(lambda x: isinstance(x, int)))) def _(): pass
  • 30. Composing FCs: &, | and ~ ANDFC() - &: • The composed FC matches if all the given FC match. • Match if key x of Point is a value between 0 and 255. @Rule(x=P(lambda x: x >= 0) & P(lambda x: x <= 255))) def _(): pass
  • 31. Composing FCs: &, | and ~ ORFC() - |: • The composed FC matches if any of the given FC matches. • Match if name is either Alice or Bob. @Rule(Fact(name=L('Alice') | L('Bob’))) def _(): pass
  • 32. Composing FCs: &, | and ~ NOTFC() - ~: • This composed FC negates the given FC, reversing the logic. If the given FC matches this will not and vice versa. • Match if name is not Charlie. @Rule(Fact(name=~L('Charlie'))) def _(): pass
  • 33. Variable Binding: The << Operator • Any patterns and some FCs can be binded to a name using the << operator. • Example 1: • The first value of the matching fact will be binded to the name value and passed to the function when fired. @Rule(Fact('value' << W())) def _(value): pass
  • 34. Variable Binding: The << Operator • Any patterns and some FCs can be binded to a name using the << operator. • Example 2: • The whole matching fact will be binded to f1 and passed to the function when fired. @Rule(Fact(‘f1' << Fact()) def _(f1): pass