3.4. Backward Reasoning Topic 3.4 General schema for Backward reasoning: 1. Define S as the list of top level goals to test (e.g., ((is fruit apple), (is fruit pear), …) Backward Reasoning 2. For each goal G in S: • Try to establish G Contents 3.4.1 Open and Closed Worlds • 3.4.2 General Schema for Backward Reasoning Stop condition: depends: • 3.4.2.1 Assuming Closed World 3.4.2.2 Assuming Open World 3.4.2.3 Backward Reasoning with Variables • 3.4.3 Code for Backward Reasoning Where either only one of the goals can be correct (as with the fruit example), or only one of several possible alternatives solutions is desired, stop on first. Where more than one goal on this list can be correct, and all are desired, stop when all goals attempted. 1 3 3.4. Backward Reasoning 3.4. Backward Reasoning Open and Closed-World Semantics: To establish a goal, G (closed world assumption): • 1. If the goal matches a known fact, it is established. Return TRUE. Closed world assumption: what is not currently known to be true is false. 2. Find list of rules, RL, which have the goal as a consequence. – Something is true if and only if it is in our fact base, or it can be established via the rules in the system. 3. For each applicable rule R in RL: • Open world assumption: the system’s knowledge is incomplete. a) For each premise, P, of R: • If cannot establish P (recursive call), proceed with next rule b) All premises are established, rule establishes G • Add G to factlist, • Return TRUE – Thus a fact can be true even if not present in the fact base, nor derivable via rules. – In a KBS, systems making this assumption can ask the user to provide details not found in the database. 4. The goal could not be established, return FALSE 2 4 1 3.4. Backward Reasoning Example: funct establish(G) 1. 2. 3. If G in FACTS, return TRUE RL= rules with G in THENs For R in RL: a) For P in R.premises: • If not establish(P): next rule b) Add G to FACTS c) Return TRUE 4. Return False 3.4. Backward Reasoning Goal: G=(is Fruit apple) 1. G in FACTS– no 2. RL=(R11a, R11b) 3. • • Given R11a: establish (is fruitclass tree)->TRUE establish (is color red) -> FALSE 3. Given R11b: • • • • To establish a goal, G (open-world assumption): 1. If the goal matches a known fact, it is established. Return TRUE. 2. Find list of rules, RL, which have the goal as a consequence. 3. For each applicable rule R in RL: a) For each premise, P, of R: • If cannot establish P (recursive call), proceed with next rule b) All premises are established, rule establishes G • Add G to factlist, • Return TRUE establish (is fruitclass tree)->TRUE establish (is color green) -> TRUE THUS add G to FACTS RETURN TRUE Rules (R11a IF ((is fruitclass tree) (is color red)) THEN (is fruit apple)) (R11b IF ((is fruitclass tree) (is color green)) THEN (is fruit apple)) 4. If there were rules, and none succeeded, return FALSE Facts 5. If there are no rules to establish G: (is color green) (< diameter 10cm) (is shape round) 1. ask user if G is TRUE or FALSE 2. If true, G is established, Add G to factlist, and return TRUE 3. If false: G is rejected, return FALSE 5 7 3.4. Backward Reasoning 3.4. Backward Reasoning Notes on Example Notes on General Schema • • • • On the first call to establish (is fruitclass tree), the goal does not match a known fact, so the algorithm uses a rule to establish this fact. The application places the goal on the fact list. Consequently, on the second call to establish (is fruitclass tree), it is found on the fact list. The rule does not need to be applied again. • 6 This schema assumes that if a rule is available to derive a fact, the user should not be asked. The system thus distinguishes between: – derivable facts (facts which can be derived using a rule) and – basic facts (facts for which no rules are available, which are user supplied, either in the original fact list, or via asking the user. 8 2 3.4. Backward Reasoning 3.4. Backward Reasoning Backward Chaining with Variables in goals: To establish a goal, G (open-world and variables): function establish(G, bindings) • In some systems, goals can contain variables: ? (is fruit ?x) • In these systems, the resolution of a goal, instead of returning TRUE or FALSE, should return a list of the variables and their bindings for which the goal is true, e.g., 1. If G unifies with a known fact, return bindings. 2. Find list of rules, RL, where the goal unifies with THEN. 3. For each rule R in RL: Solutions: Query: (is fruit ?x) • a) Set B to the bindings produced by unifying goal with THEN b) For each premise, P, of R: • set B to return value of establish(P, B) • if B is FALSE, goto next rule. c) All premises are established, • For each soln in B, Add G with bindings B to factlist, • Return B ((?x . apple)) This is equivalent to a goal list (disjunctive): ? (or (is fruit apple) (is fruit pear) (is fruit cherry) …) 4. … 9 11 3.4. Backward Reasoning 3.4. Backward Reasoning Backward Chaining with Variables in rules: 3.4.3 Code for Backward Reasoning • In some systems, rules can contain variables: (R1 IF ((parent ?x ?y) (parent ?y ?z)) THEN (grandparent ?x ?z)) • We here describe code for representing backward reasoning from a single goal • In these systems also, the resolution of a goal, instead of returning TRUE or FALSE, should return a list of the variables and their bindings for which the goal is true, e.g., • Goals are started in the form: – ((is type ?)) • Facts (parent (parent (parent (parent john maria) john paul) luisa john) edgar john) Query: (grandparent ?a ?b) Solutions: (((?a.luisa)(?b.maria)) ((?a.luisa)(?b.paul)) ((?a.edgar)(?b.maria)) ((?a.edgar)(?b.paul))) 10 The first possible instantiation of the goal is returned: The value of TYPE is BANANA ((IS TYPE BANANA)) 12 3 3.4. Backward Reasoning VALUE-FROM-FACTS Busca el valor de la incógnita en la lista de hechos. Sólo aceptamos un valor por incógnita, es decir, que podemos buscar por el nombre de la incógnita. Facts • Facts are all of the form: (prop param val) ASK-USER Pregunta al usuario el valor de la incógnita, para construir y devolver un hecho con la entrada del usuario y el nombre de la incógnita. – e.g. (is type apple) – e.g. (> size 10) FIND-RULES Devuelve la lista de reglas aplicables para resolver la incógnita. • Facts are accessed as follows: (defun fact-prop (fact) (first fact)) (defun fact-param (fact) (second fact)) (defun fact-val (fact) (third fact)) GOOD-RULE? Una regla es aplicable para resolver una incógnita si alguno de sus consecuentes / conclusiones sirve para dar un valor a la incógnita. 13 15 IN-THEN? Mira uno a uno todos los consecuentes/conclusiones de la regla, a ver si alguno de ellos puede dar valor a la incógnita. 3.5. Razonamiento Hacia Atrás: implementación (estudiar código) BACKWARD Utiliza tres variables globales: *fact-list*, *rule-list*, *hypothesis*. Esta última es una lista de nombres de características de las cuales se quiere saber su valor. Representan las aspectos sobre los cuales se quiere que el sistema obtenga sus conclusiones. Las mal llamadas hipótesis, son en realidad incógnitas del sistema. VALUE-FROM-RULES Recorre secuencialmente la lista de reglas aplicando aquellas que cuyas premisas se cumplan, y parando con la primera cuya aplicación permita conocer el valor de la incógnita actual. Se devuelve el hecho correspondiente a la incógnita, si es que se llego a encontrar su valor, o NIL en caso contrario. FIND-HYPOTHESIS-VALUE Busca el valor de una incógnita/hipótesis del sistema. Si se le puede dar un valor a partir de los hechos, eso es todo; si no, hay que intentarlo con todas la reglas que puedan dar un valor a esta incógnita, y si esto también falla, sólo queda la alternativa de preguntarle al usuario. EVAL-RULE Para ver si la regla se puede aplicar se recorre la lista de premisas (ifs) de la regla llamando a find-hypothesis-value con cada premisa, y si todas ellas se cumplen, entonces se añaden todas la conclusiones de esta regla a la base de datos. y al final se devuelve el valor de la incógnita actual usando value-from-facts. Si alguna premisa no se cumple, se devuelve NIL. 14 16 4 (defun find-hypothesis-value (hypothesis) ;; toma (? param ??) y devuelve (prop param value) (let (rules) (cond ;; hypothesis está en *fact-list* ((value-from-facts hypothesis *fact-list*)) The main function is as follows: (defun backward () (mapc #'display-results (mapcar #'find-hypothesis-value *hypothesis-list*))) ;; hypothesis es la consecuencia de una regla ((setq rules (find-rules hypothesis *rule-list*)) (value-from-rules hypothesis rules)) (t (ask-user hypothesis))))) ;; se pregunta al usuario • For each goal in *hypothesis-list*, find its solution. (defun value-from-facts (hypothesis facts) ;; return first fact (prop param value) that has the same parameter as the hypothesis: (? param ??) • Call display-results to display each solution. (let ((param (fact-param hypothesis))) (find-if #'(lambda(x) (eq param (fact-param x))) facts))) 17 (defun ask-user (hypothesis) (let ((answer)) (format t "˜%Introduzca el valor de ˜S: " hypothesis) (let ((in (read))) (if (atom in) (setq answer (list ’is hypothesis in)) (setq answer (list (car in) hypothesis (cadr in))) ) ) (format t "˜%Gracias") (setq fact-list (cons answer fact-list)) answer ) ) 19 (defun ask-user (hypothesis) ;; hypothesis es del tipo (? param ??) (let ((prop) (answer)) (format t "~%Introduccion de un hecho nuevo (<prop> ~S <val>)" (fact-param hypothesis)) (format t "~%Introduzca <prop>: ") (setq prop (read)) (format t "~%Introduzca <val>: ") (setq answer (list prop (fact-param hypothesis) (read))) (format t "~%Gracias") (add-fact answer) answer)) 18 20 5 (defun true-fact? (fact) ;; devuelve T si el hecho recibido es cierto (equal fact (find-hypothesis-value (list '? (fact-param fact) '?)))) (defun find-rules (hypothesis rule-list) ;; devuelve lista de reglas de las que se puede ;; deducir el valor de la hipótesis (? param ??) (mapcan #'(lambda(x) (if (good-rule? hypothesis x) (list x))) rule-list)) (defun eval-rule (hypothesis rule) ;; si todas las premisas de la regla son ciertas, la dispara ;; (añade los hechos nuevos a *fact-list*), coge la hypothesis ;; (? param ??), y deduce ?, ?? de ellos devolviendo la ;; hypothesis deducida. ;; En caso de que alguna premisa no fuera cierta, devuelve NIL (defun good-rule? (hypothesis rule) (in-then? hypothesis (rule-thens rule))) (when (every #'true-fact? (rule-ifs rule)) (mapc #'add-fact (rule-thens rule)) (value-from-facts hypothesis (rule-thens rule)))) 21 23 (defun in-then? (hypothesis thens) ;;devuelve T si de algún then se puede derivar el valor de la ;;hipótesis (? params ??) (defun add-fact (fact) (push fact *fact-list*)) (let ((param (fact-param hypothesis))) (if (some #'(lambda(x) (eq param (fact-param x))) thens) T))) (defun display-results (derived-fact) (format t "~%~S ~S ~S" (fact-param derived-fact) (fact-prop derived-fact) (fact-val derived-fact))) (defun value-from-rules (hypothesis rules) ;; rules son reglas que contienen en sus consecuentes a hypothesis. ;; Si hay alguna regla en rules que es satisfacible, expande ;; *rule-list* con sus conclusiones, y devuelve el valor deducido ;; de hypothesis. ;; En caso de que ninguna sea satisfacible devuelve NIL (some #'(lambda(x) (eval-rule hypothesis x)) rules)) 22 24 6 Utilización (erase-facts) > NIL (set-hypothesis-list ’(fruta forma)) > ((? FRUTA ??) (? FORMA ??)) (backward) > > > > > > > > > > > > > > > Introduccion de un hecho nuevo (<prop> FORMA <val>) Introduzca <prop>: is Introduzca <val>: redonda Gracias Introduccion de un hecho nuevo (<prop> DIAMETRO <val>) Introduzca <prop>: > Introduzca <val>: 10 Gracias Introduccion de un hecho nuevo (<prop> COLOR <val>) Introduzca <prop>: is Introduzca <val>: verde Gracias FRUTA is SANDIA FRUTA is REDONDA ((IS FRUTA SANDIA) (IS FRUTA REDONDA)) 25 Esquema de llamadas entre las funciones de backward.lisp BACKWARD FIND-HYPOTHESIS-VALUE VALUE-FROM-RULES DISPLAY-RESULTS FIND-RULES EVAL-RULE TRUE-FACT? VALUE-FROM-FACTS ASK-USER GOOD RULE? IN-THEN? RULE-IFS RULE-THENS ADD-FACT FACT-PROP FACT-PARAM FACT-VAL 26 7