Download - 1 Artificial Intelligence University Politehnica of Bucharest 2008-2009 Adina Magda Florea
1
Artificial IntelligenceArtificial Intelligence
University Politehnica of Bucharest2008-2009
Adina Magda Floreahttp://turing.cs.pub.ro/aifils_08
2
Lecture No. 6
Prolog Language
Rule-based Systems Knowledge representation using rules RBS structure Inference cycle of a RBS Control strategy
2
3
1. Prolog R. Kowalski, A. Colmerauer - '70
Prolog control structure A goal S is true in a Prolog program (can be
satisfied or is a logical consequence of the program) iff:
1. There is a clause C in the program;
2. There is an instance I of the clause C such that: 2.1. the head of I is the same with the head of S;
2.2 all the goals in I’s body has true (can be satisfied)
3
4
Prolog
Execuþie
sistem Prolog
conjuncþiide scopuri
program Prolog
indicator SUCCES/INSUCCES
instanþele variabilelor din scopuri
5
Prolog% parinte(IndividX, IndividY)% stramos(IndividX, IndividZ)parinte(vali, gelu).parinte(ada, gelu).parinte(ada, mia).parinte(gelu, lina).parinte(gelu, misu).parinte(misu, roco).
str1(X, Z) :- parinte(X, Z).str1(X, Z) :- parinte(X, Y), str1(Y, Z).
5
vali ada
gelu mia
lina mişu
roco
6
Prolog% Change the order of the rules:
str2(X, Z) :- parinte(X, Y), str2(Y, Z).
str2(X, Z) :- parinte(X, Z).
% Change the order of goals:
str3(X, Z) :- parinte(X, Z).
str3(X, Z) :- str3(X, Y), parinte(Y, Z).
% Change both the order of rules and the order of goals:
str4(X, Z) :- str4(X, Y), parinte(Y, Z).
str4(X, Z) :- parinte(X,Z).
6
7
Prolog
?- str1(ada, misu).
yes
?- str2(ada, misu).
yes
?- str3(ada, misu).
yes
7
str1(ada, misu)
parinte(ada, misu)
INSUCCES
parinte(ada, Y), str1(Y, misu)
parinte(ada, gelu)
Y=gelu
SUCCES
str1(gelu, misu)
parinte(gelu, misu)
SUCCES
str3(ada, misu)
parinte(ada, misu)
INSUCCES
str3(ada, Y), parinte(Y, misu)
parinte(ada, Y')
Y=Y'
SUCCES
parinte(gelu, misu)
SUCCES
parinte(ada, gelu)
Y'=gelu
8
Prolog?- str4(ada, misu).
?- str3(mia, roco).
8
str4(ada, misu)
str4(ada, Y), parinte(Y, misu)
str4(ada, Y'), parinte(Y', Y)
str4(ada, Y"), parinte(Y", Y)
arbore infinit...
str3(mia, roco)
parinte(mia, roco)
INSUCCES
str3(mia, Y), parinte(Y, roco)
parinte(mia, Y)
INSUCCES
str3(mia, Y'), parinte(Y', Y)
parinte(mia, Y')
INSUCCES
str3(mia, Y"), parinte(Y", Y')
parinte(mia, Y")
INSUCCES
...arbore infinit
9
2. Knowledge representation using rules Declarative representation / procedural representation
R1: if the patient has fever
and the type of the organism is gram-pozitiv
and the patient has a stiff neck
then the identity of the organism is streptococcus
R2: if the car does not start
and the lights do not turn on
then the battery is faulty
sau there is no contact of the battery
R3: if the temperature > 95o C
then open the protection valve
10
Knowledge representation using rules
( p)( o)(Temperatura (p,mare) Tip(o,gram - pozitiv) GitUscat(p))
Identitate (o,streptococ)
( m)( b)(NuPorneste(m) NuAprinde(m,far))
(Stare(b,consumata) Borne(b, fara_ contact))
3. Structure of an RBS
MEMORIEDE LUCRU
Fapte dinamice
BAZA DE CUNOSTINTE Reguli Fapte
Date de activare
MOTOR DEINFERENTA
Selectie reguliReguli selectate
Actiuni(Concluzii)
Date
Reprezentare
Control
Intrari
(date de caz)
Iesiri
(Raspunsuri)si fapte
12
4. Inference cycle of an RBS
Match Selection Execution
13
Inference cycle of an RBS - cont
Algorithm: Functioning of an RBS
1. WM Case data
2. repeat
2.1. Identify WM and KB and create the conflict set (CS)
2.2. Select a rule from the CS to apply
2.3. Apply selected rule
until there are no more applicable rules or
WM satisfies goal or
a predefined effort has been exhausted
end.
14
5. Control strategy
Selection criteria from the CS Direction of rule application
14
15
5.1 Selection criteria from the CS
Select the first applicable rule Select a rule from the CS
Preferences based on rule identitySpecificity
- the set of premises of R1 includes the set of premises of R2;
- the set of conditions of R1 are similar to that of R2, but the premises of R1 refer to constants while the premises of R2 refer to variables.
Time of last use Preferences based on matched objects
15
16
17
Selection criteria from the CS - cont
Use of meta-rules
if a rule has conditions A and B and
the rule refers {does not refer} X
{ not at all/
only in the LHS/
only in the RHS }
then the rule will be certainly useful
{ probably useful/
probably useless/
certainly useless }
Application of all rules in the CS 17
18
5.2 Direction of rule application
18
INLANTUIRE INAINTE
daca atuncidaca atunci
INLANTUIRE INAPOI
daca atuncidaca atunci
daca atunci
A B B C
A (data)
C (concluzie)
determina C B C A B
( A C, implicit)Este A adevarata? (data)
Forward chaining Backward chaining
Continut initial al memoriei de lucru: A,EStare scop: D
A,E A,E,B A,E,B,C A,E,B,C,D
(a)
R3 R1 R2
A,E
A,E,B
A,E,B,C
A,E,B,C,D
A,E,C
A,E,C,D
R4
R2
R3
R1
R2
(b)
(a) Forward chaining
19
R3
Continut initial al memoriei de lucru: A,EStare scop: D
D? C? A?, B? A?, E?
(a)
R3R1R2
D
C
A B E
R1 R4
R2
A? A? E?
E?
(b)
A
C
(b) Backward chaining
20
Algorithm: Find a value using forward chaining (a)FindValueD(A)1. if A has value
then return SUCCESS2. Build CS3. return Find(A, CS)end.Find(A, CS)1. if CS = {}
then return FAIL2. Choose a rule RCS according to a selection criterion (criteria) 3. for each premise Ij of R execute
3.1. Find the truth of Ij4. if all Ij , j=1,N are satisfied
then4.1. if A has value
then return SUCCESS4.2. Add the fact(s) refered in the RHS of R to WM
5. CS CS - R6. return Find(A, CS)end.
Algoritm: Find a value using backward chaining (b) Detvalue(A)1. Build the set if rules which refer A in RHS, CS2. if CS = {}
then2.1. Ask the user the value of A2.2. if the user answers A then stare this value in WM else return FAIL
3. else3.1. Choose a rule according to a selection criterion (criteria)3.2. for each premise Ij, j=1,N, in LHS of R execute3.2.1. Be Aj refered by the premise Ij3.2.2. if Aj has valuethen evaluate the truth of Ij3.2.3. elsei. if Detvalue(Aj) = SUCCESSthen evaluate the truth of Ijii. else consider Ij unsatisfied
3.3. if all premises Ij, j=1,N are satisfied
then store the value A obtained from the RHS of R in WM
4. if A has value (in WM)
then return SUCCESS
5. else
5.1 CS CS – R
5.2 repeat from 2
end.
1'. if A is primary data
then
1'.1. Ask the user the value of A
1'.2. if the user knows the value of A
then - store this value in WM
- return SUCCESS
1’.3. else return FAIL
Example of RBS with forward chaining (a)
R11: if Etapa is Verifica-Decor
and exists o statuie
and does not exist soclu
then Add soclu la Obiecte-Neimpachetate …..
R17: if Etapa is Verifica-Decor
then finish Etapa Verifica-Decor
and start Etapa Obiecte-Mari
Nume Greutate Dimensiune Fragil Impachetat
Etapa :Cutie 1 :Obiecte Neimpachetate :
Statuie mediu mare nu nuTablou usor medie nu nuVaza usor mica da nuSoclu greu mare nu nu
Verifica - Decor
Statuie,Tablou,Vaza ,Soclu{ }
Example of RBS with forward chaining - contR21: if Etapa is Obiecte-Mari
and exists un obiect mare de ambalatand exists un obiect greu de ambalatand exists o cutie cu mai putin de trei obiecte marithen pune obiectul greu in cutie
R22: if Etapa is Obiecte-Mariand exists un obiect mare de ambalatand exists o cutie cu mai putin de trei obiecte mari …..then pune obiectul mare in cutie
R28: if Etapa is Obiecte-Mariand exists un obiect mare de pusthen foloseste o cutie noua
R29: if Etapa is Obiecte-Marithen finish Etapa Obiecte-Mariand start Etapa Obiecte-Medii
25
Etapa :Cutie 1 :Obiecte Neimpachetate :
Obiecte - MediiSoclu,StatuieTablou,Vaza
Example OPS5WME
(literalize student name placed_in sex_stud)
(literalize room number capacity
free sex_room occupants)
(vector-attribute occupants)
room 111 4 2 F (Maria Elena) time tag
(make room ^number 112 ^capacity 4 ^free 4
^sex_cam nil ^occupants nil)
(make student ^name Mihai ^placed_in nil ^sex-stud M)
26
(p atrib_stud_free_room
(<Unplaced_student>
(student ^name < stud_name> ^plased_in nil ^sex_stud <gender>))
(<Free_room>
(room ^number <room_no>
^capacity <capacity_max>
^free <capacity_max>))
-->
(modify < Unplaced_student > ^ plased_in < room_no >)
(modify < Free_room > ^ occupants < stud_name >
^sex_room < gender >
^ free (compute < capacity_max >-1)).
27
28
Example Jess
(deftemplate person(slot firstname)(slot name)(slot age (type INTEGER))
)
(defrule adult(person (firstname ?p_first)
(age ?p_age))(test (>= ?p_age 18)))
=>(assert (adult (firstname ?p_first)))
)
Stud/room in Jess(deftemplate student
(slot name)(slot sex)(slot placed_in)(slot special_considerations (default no))
(deftemplate room(slot number)(slot capacity (type INTEGER)(default 4))(slot sexes_are)(slot vacancies (type INTEGER))(multislot occupants))
(defrule assign-student-empty-room?unplaced_student (student (name ?stud_name)
(placed_in nil) (sex ?gender))
?empty_room (room (number ?room_no) (capacity ?room_cap) (vacancies ?max_size))
(test (= ?room_cap ?max_size))=>
(modify ?unplaced_student (placed_in ?room_no))(modify ?empty_room (occupants ?stud_name) (sexes_are ?gender)
(vacancies (-- ?max_size)))
30
5. RBS strategies in OPS5 family
Recognize-act cycle: Match Select Act
WME = working memory element Identified by a "time tag"
Instantiation: set of WME which satisfy a rule Conflict set Conflict resolution
30
31
Recognize-act cycle
Match Application of rule – condition - WMEs of WM
satisfy LHS 2 aspects:
match intra-element match inter-element
(defrule teenager(person (firstName ?name) (age ?age))
=> (printout t ?name " is " ?age " years old." crlf))
Recognize-act cycle match inter-element(defrule assign-private-room
(student (name ?stud_name)
(placed_in nil)
(special_consideration yes))
(room (number ?room_no)
(capacity 1)
(vacancies 1)
=> …
WMEs41 (student name Mary sex F placed_in nil
special_consideration yes)52 (student name Peter sex M placed_in nil
special_consideration yes)9 (room number 221 capacity 1 vacancies 1)12 (room number 346 capacity 2 vacancies 1)17 (room number 761 capacity 1 vacancies 1)
Instantiations (WM)assign-private-room 41 9assign-private-room 41 17assign-private-room 52 9assign-private-room 52 17
33
Conflict resolution
Strategies Refraction = o aceeasi instantiere nu este
executata de mai multe ori (2 instantieri sunt la fel daca au acelasi nume de regula si aceleasi time tags, in aceeasi ordine)
Time of use = Se prefera instantierile care au identificat cu WMEs cu cele mai recente time tags (sau invers)
Specificity = Au prioritate instantierile cu LHS specifice = nr de valori testate in LHS
teste asupra: nume clasa, predicat cu 1 arg constanta, predicat cu un operator variabila legata
34
Conflict resolution
Strategia LEX Elimina din MC instantierile care au fost deja
executate Ordoneaza instantierile pe baza momentului
utilizarii Daca mai multe instantieri au aceleasi time
tags, utilizeaza specificitate Daca mai multe instantieri au aceeasi
specificitate alege arbitrar Strategia MEA – aceeasi dar utilizeaza primul
time tag
35
Efficiency
Match – cam 80% din timpul ciclului recunoastere-actiune Fiecare WME este comparat cu fiecare conditie din fiecare
regula O(R*FP), R – nr de reguli, F – nr WME, P nr mediu de
conditii in LHS regula RETE match algorithm (1982 Forgy)
Salveaza starea de match intre 2 cicluri recunoastere-actiune
La crearea unui WME, acesta este comparat cu toate elementele conditie din program si este memorat impreuna cu fiecare element conditie cu care a identificat =>
Numai schimbarile incrementale din WM sunt identificate in fiecare ciclu
O(R*F*P) aprox
Rule compilation Se compileaza conditiile regulilor intr-o retea de noduri de
test Un test este un predicat cu o constanta sau variabila legata
sau o disjunctie Procesul de match are loc numai la adaugarea sau la
eliminarea unui WME (modify este retract urmat de assert)(gate (type or) (value true))(gate (type or) (value false))
Node sharing1 = gate
type = or
value = true value = false
37
Rule compilation
Un pointer la noul WME este trecut prin retea, incepand de la nodul radacina
Fiecare nod actioneaza ca un switch Cand un nod primeste un pointer la un WME, testeaza
WME asociat. Daca testul reuseste, nodul se deschide si WME trece mai departe
Altfel nu se intampla nimic Daca un WME va trece prin retea, va fi combinat cu
alte WME care trec pentru a forma o instantiere in MC Pointerii la WME sunt trimisi prin reteaua RETE ca
tokens = pointer + stare (assert sau retract)
38
Types of node in RETE network
Nod cu 1 intrare = test intra-element realizat de noduri cu 1 intrare fiecare nod efectueaza un test corespunzator unei conditii testarea aceleiasi variabile – tot noduri cu 1 intrare
1 = gate
type = or
value = true value = false
39
RBS
Foarte multe Cele mai influente
OPS5 ART CLIPS Jess Familia Web Rule languages
In special RuleML si SWRL Interoperabilitatea regulilor
40
RuleML
RuleML Initiative - August 2000 Pacific Rim International Conference on Artificial Intelligence.
RuleML Initiative dezvolta limbaje bazate pe reguli deschise XML/RDF
Aceasta permite schimbul de reguli intre diferite sisteme, inclusiv componete software distribuite pe Web si sisteme client-server eterogene
Limbajul RuleML – sintaxa XML pentru reprezentarea cunostintelor sub forma de reguli
Integrarea cu ontologii: sistemul de reguli trebuie sa deriveze/utilizeze cunostinte din ontologie
41
RuleML
RuleML – se bazeaza pe Datalog Datalog = limbaj de interogare si reguli pentru baze de
date deductive Subset al Prolog cu restrictii:
argumente ne-functionale (constante sau variabile) limitari in nivelul de apeluri recursive variabilele din concluzie trebuie sa apara in predicate
ne-negate din ipoteza Hornlog – Datalog extins cu variabile functionale (termeni
generali)
42
RuleML
Reguli reactive = Observa/verifica anumite evenimente/conditii si executa o actiune – numai forward
Constrangeri de integritate = reguli speciale care semnaleaza inconistente cand se indeplinesc anumite conditii – numai forward
Reguli de inferenta (derivare) = reguli reactive speciale cu actiuni care adauga o concluzie daca conditiile (premisele sunt adevarate) - Se pot aplica atat forward cat si backward
Fapte = reguli de inferenta particulare
Regui reactive
Constangeri deintegritate
Reguli dederivare
Fapte
RuleML Reguli reactive<rule> <_body> <and> prem1 ... premN </and> </_body>
<_head> action </_head></rule>
Constrangeri de integritate<ic> <_head> inconsistency </_head>
<_body> <and> prem1 ... premN </and> </_body></ic>
implementate ca
<rule> <_body> <and> prem1 ... premN </and> </_body> <_head> <signal> inconsistency </signal> </_head>
</rule>
RuleML Reguli de inferenta/derivare
<imp> <_head> conc </_head> <_body> <and> prem1 ... premN </and> </_body>
</imp >
implementate prin<rule> <_body> <and> prem1 ... premN </and> </_body>
<_head> <assert> conc </assert> </_head></rule>
Fapte<atom> <_head> conc </_head> </atom> implementate prin<imp> <_head> conc </_head>
<_body> <and> </and> </_body> </imp>
RuleMLFapte
<atom> <rel>spending</rel> <ind>Peter Miller</ind> <ind>min 5000 euro</ind> <ind>previous year</ind>
</atom>
spending(petterMiller, min5000euro, previousYear).
Reguli de inferenta/derivare<imp> <head> <atom>
<rel>discount</rel> <var>customer</var>
<var>product</var> <ind>7.5 percent</ind> </atom>
</head> <body> <and> <atom>
<rel>premium</rel> <var>customer</var> </atom> <atom> <rel>luxury</rel> <var>product</var> </atom>
</and> </body></imp>
discount(Customer, Product, 7.5_percent):-premium(Customer), luxury(Product).
Example of RBS with backward chaining (b)R1: if X has par
then X is mamalR2: if X feeds puii with milk
then X is mamalR3: if X is mamal
and X has pointed teethand X has falcithen X is carnivor
R4: if X is carnivorand X is brownand X has petethen X is cheetah
R5: if X is carnivorand X is brownand X has stripsthen X is tiger
47
What is X?