You are on page 1of 43

Artificial Intelligence

CSE643
(Monsoon 2021)
Lecture #5
Tip: Take your own notes during lectures

C. Anantaram
c.anantaram@iiitd.ac.in
Google classroom code: dke4bgy
Note: This session is being recorded.
Disclaimer: I do not claim that all material in these slides are self-produced.
Some Material for the slides are taken from internet and other sources.
RECAP: Prolog concepts
• Prolog based on first-order logic.
-- Quantification over variables and function symbols
• Every program is a set of Horn clauses. Definite clauses.
-- At most one positive literal. (Horn clauses). Exactly one positive
literal (definite).
That is at most one head term in a clause.
• Inference is by resolution.
-- Positive and negative terms resolve
• Search is by backtracking with unification.
-- Go around and try your best to find a solution to a query
• Basic data structure is term.
• Variables are unknowns not locations.
• Prolog does not distinguish between inputs and outputs. It solves
relations/predicates.
2
Prolog Terms
• Terms are the items that can appear as the arguments of predicates
• They can be viewed as the basic data manipulated during execution
• They may exist statically in the given code of the program and initial
query, or they may come into existence dynamically by the process of
unification
• Terms containing no variables are said to be ground
• Prolog can process both ground and non-ground data
• A Prolog program can do useful things with a data structure even
when that structure is partially unknown

3
Prolog semantics
The clause
a :- b, c.
can be written in logic as a
a←b∧c
and then read declaratively as
a is true if b is true and c is true

4
Evaluation in Prolog
Prolog evaluates the terms in a query sequentially,
in the left-to-right order, as written
?- a, d, e. evaluate a, then d, then e

Convention: terms beginning with an upper-case letter or an underscore are


treated as variables
?- likes(rajiv, X). here, X is a variable

Queries and terms both belong to the class of logic sentences known as clauses

5
Evaluation
A computation is a chain of derived queries, starting with the
initial query
• Prolog selects the first predicate in the current query and seeks a
program clause whose head matches the predicate

• If there is such a clause, the predicate is replaced by the clause body,


giving the next derived query

• This is just applying the standard notion of procedure-calling in


any formalism

6
Example
EXAMPLE
?- a, d, e. initial query

a :- b, c. program clause with


head a and body b, c

take_umbrella(X) :- cloudy(X), humid(X), monsoon-time(X).

Starting with the initial query, the first predicate in it matches


the head of the clause shown, so the derived query is
?- b, c, d, e.
Execution then treats the derived query in the same way

7
Successful computation (satisfied)
A computation succeeds if it derives the empty query
EXAMPLE
?- likes(ravi, hari). query

likes(ravi, hari). program clause

The call matches the head and is replaced by the clause’s


(empty) body, and so the derived query is empty. (deriving the truth value –
TRUE or FALSE).

So the query has succeeded, i.e. has been solved


8
Finite failure
A computation fails finitely if the call selected from the
query does not match the head of any clause
EXAMPLE
?- likes(ravi, vinay). query

This fails finitely if there is no program clause whose head matches the sub-
goal likes(ravi, vinay).

Ex #2
?- faster(bus, scooter).
9
Infinite failure
A computation fails infinitely if every query in it is followed by a nonempty query

EXAMPLE
?- a. query

a :- a, b. clause

This gives the infinite computation


?- a.
?- a, b.
?- a, b, b.
…..
This may be useful for driving some perpetual process
10
Multiple answers
A query may produce many computations
Those, if any, that succeed may yield multiple answers to the query
(not necessarily distinct)
EXAMPLE
?- likes(rajiv, AIcourse, Z).

likes(rajiv, X, Z) :- has(X, Z).

has(AIcourse, reasoning).
has(AIcourse, learning).

11
Answers as consequences
A successful computation confirms that the conjunction in the initial
query is a logical consequence of the program.
EXAMPLE
?- a, d, e.
If this succeeds from a program P then the computed answer is
a∧d∧e
and we have
P⊨a∧d∧e /* means P logically entails a ∧ d ∧ e */
Conversely: if the program P does not offer any successful computation from
the query, then the query conjunction is not a consequence of P

12
Existential queries and universal clauses
Variables in queries are treated as existentially quantified
EXAMPLE
?- likes(X, prolog).
says “is (∃X) likes(X, prolog) true?”
or “find X for which likes(X, prolog) is true”
Variables in program clauses are treated as universally quantified
EXAMPLE
likes(ravi, X) :- likes(X, prolog).
expresses the sentence (∀X) ( likes(ravi, X) ← likes(X, prolog) )

13
List Operator in Prolog
[a,b,c] is a list in Prolog.
[H|T] bound with [a,b,c] results in
H binds to a i.e. the head of list
T binds to [b,c] i.e. the tail of the list.

membership definition
member(H,[H|T]).
member(H,[_|T]):- member(H,T).

insert(X, L, [X|L]).
insert(X, [H|T], [H|T1]):- insert(X, T, T1).

14
Lists
[elephant, horse, donkey, dog]

[elephant, [], X, parent(X, raj), [a, b, c], f(22)]

?- [1, 2, 3, 4, 5] binds to [Head | Tail].


Head binds to 1
Tail binds to [2, 3, 4, 5]

?- [quod, licet, jovi, non, licet, bovi] = [_, X | _].


X = licet
Yes

15
Lists
concat_lists([], List, List).
concat_lists([Elem | List1], List2, [Elem | List3]) :- concat_lists(List1,
List2, List3).

Built-in predicates
append(List1, List2, List3).

length([elephant, [], [1, 2, 3, 4]], Length).

member(Elem, List) will succeed, if the term Elem can be matched


with one of the members of the list List

last(List, X).

reverse([1, 2, 3, 4, 5], X). Will give X = [5, 4, 3, 2, 1]


16
Backtracking
• Prolog keeps track of choicepoints, i.e., situations where there is more than
one possible match.
• Whenever the chosen path ultimately turns out to be a failure (or if the user
asks for alternative solutions), the system can jump back to the last choicepoint
and try the next alternative.
• This is process is known as backtracking.

Example
permutation([], []).
permutation(List, [Element | Permutation]) :- select(Element, List, Rest),
permutation(Rest, Permutation).

17
Backtracking
?- permutation([1, 2, 3], X).
X = [1, 2, 3] ;
X = [1, 3, 2] ;
X = [2, 1, 3] ;
X = [2, 3, 1] ;
X = [3, 1, 2] ;
X = [3, 2, 1] ;
No

18
Cut
remove_duplicates([], []).

remove_duplicates([Head | Tail], Result) :- member(Head, Tail), remove_duplicates(Tail,


Result).

remove_duplicates([Head | Tail], [Head | Result]) :- remove_duplicates(Tail, Result).

?- remove_duplicates([a, b, b, c, a], List).


List = [b, c, a] ;
List = [b, b, c, a] ;
List = [a, b, c, a] ;
List = [a, b, b, c, a] ;

19
Cut
remove_duplicates([], []).

remove_duplicates([Head | Tail], Result) :- member(Head, Tail), !,


remove_duplicates(Tail, Result).

remove_duplicates([Head | Tail], [Head | Result]) :- remove_duplicates(Tail,


Result).

?- remove_duplicates([a, b, b, c, a], List).


List = [b, c, a] ;
No

20
Dynamic facts
• assert
• To assert a new fact in the Prolog database

• Example: assert(predicate(value)).
assert(recommended(hampi)).

• retract
• To retract a fact from the Prolog database

• Example: retract(recommended(X)).
X = hampi.
• retractall(predicate(args)).
21
Basic Input and Output
• write(string).

• write(value).

• read(variable).

22
An example
• Let us design a system to advise an 8th standard student on selecting
his/her appropriate stream
• Physical Sciences stream
• Engineering stream
• Medical stream
• Humanities stream

• Based on aptitude for a stream


• Marks
• Interest

23
Suggestions?

24
Stream advisory system for 8th standard student
Fact-base based on marks, interest, etc.
What is your interest? If child has interest in a subject, then marks in that subject. And if
Threshold > 75% then go for it. Then go for it.
Good in science but not in maths then medical.
Good in science and in maths then engineering. Then check marks.
If the student has interest in reading and performing good in subjects like science then pursue medical.
I like to solve puzzles and mathematical reasoning then suggest subject then go for aptitude related
subjects like maths
Good at games then go for physical stream
Aptitude and reading ability then go for humanities
Interest in science but not in maths and good in drawing then medical
Aptitude test and then decide; Weightage kind of scheme – interest etc.
Quantize interest and aptitude – weighted sum and then create a sum of these and then tell

25
Stream advisory system for 8th standard student
If interested in natural-occurrences and interested in inanimate-objects and have good marks
in science and done experiments, aptitude for thinking then take physical sciences

If interested in man-made-things and done Meccano and done repairs and interested in
working-things and good-marks in maths and aptitude for design then you take engineering

If interested in living-things and interested in health and etc. then take medical

26
Stream advisory system for 8th standard student
physical-sciences(X) :- interested(X, natural-occurrences), interested(X, inanimate-objects),
good-marks(X, science), done(X, experiments), aptitude(X, thinking).

engineering(X) :- interested(X, man-made-things), done(X, meccano), done(X, repairs),


interested(X, working-things), good-marks(X, maths), aptitude(X, design).

medical(X) :- interested(X, natural-occurrences), interested(X, living-things), done(X, first-aid),


good-marks(X, science), done(X, helping-people), aptitude(X, memory).

humanities(X):- interested(X, social), interested(X, human-values), done(X, creative-work),


done(X, reading-books), good-marks(X, social-studies), aptitude(X, talk).

27
References
• Prolog manual that I have posted

• Download swi-prolog from


https://www.swi-prolog.org/download/stable

28
Areas of AI and their inter-dependencies
Agent
Logic and Knowledge
Search Reasoning Representation
Sensors
Actuators
Machine
Planning
Learning

IoT
NLP Vision Robotics Systems
29
Adapted from Prof. Pushpak Bhattacharyya’s slides on NLP (2008), IITB
What is Logic?

30
Source: PropositionalPredicates.pdf by Unknown Author available on Internet
Propositional Logic
• A Proposition is a statement that is either True or False.
• Every proposition is either True or False, but its truth value may
need to be determined.

Consists of a set of declarative sentences

• Primitive P India is a country (TRUE)


Q Pune is the capital of India (FALSE)
R Moon is made of green cheese (TRUE)
31
Propositional Logic
• Logical constants: TRUE, FALSE
• Propositional symbols: P, Q, S, ... (atomic sentences)
• Wrapping parentheses: ( … )
• Sentences are combined by connectives:
 ...and [conjunction]
 ...or [disjunction]
...implies [implication / conditional]
..is equivalent [biconditional]
 ...not [negation]
• Literal: atomic sentence or negated atomic sentence
32
Propositional Logic

33
Source: PropositionalPredicates.pdf by Unknown Author available on Internet
Examples of Propositional logic sentences
• P means “It is hot.”
• Q means “It is humid.”
• R means “It is raining.”
• (P  Q) → R
“If it is hot and it is humid, then it is raining”
•Q→P
“If it is humid, then it is hot”

34
Compound Propositional statements
• Compound using connectives  (and)  (or)  (not) → (implies)
 (biconditional)

• A: It is raining
• A: (not) It is raining same as It is not raining

• B: Newton knew Einstein


• B: (not) Newton knew Einstein same as Newton did not know Einstein

35
Source: PropositionalPredicates.pdf by Unknown Author available on Internet
Truth Table and Truth Values
• The truth value of a compound propositional statement is determined
by its truth table

• Truth tables define the truth value of a connective for every possible
truth value of its terms

36
Source: PropositionalPredicates.pdf by Unknown Author available on Internet
Source: PropositionalPredicates.pdf by Unknown Author available on Internet

Truth Table of Propositions


A: It is raining
A: It is not raining

Truth Table for Proposition and its Negation


A: Newton was a physicist
B: Einstein was a physicist

A  B: Newton was a physicist and Einstein was a physicist

C: Ramanujam was a physicist


 C: (not) Ramanujam was a physicist
Truth Table for Conjunction of Propositions

A   C : Newton was a physicist and (not) Ramanujam was a physicist 37


Well formed formula (wff)
• An atomic proposition is a wff

• Any wff can be prefixed with  . The result will be a wff too.

• Any two wffs can be put together with  (and)  (or) → (implies)
and  (biconditional) between them, enclosing the result in
parentheses. This will be a wff too.

38
References
• Russell and Norvig: Section 7.4

• Deepak Khemani: Section 12.3, 12.5

• https://www.cs.colostate.edu/~cs122/Fall16/slides/PropositionsPredi
cates.pdf

• https://faculty.psau.edu.sa/filedownload/doc-7-pdf-
a154ffbcec538a4161a406abf62f5b76-original.pdf
39
References
• http://www1.spms.ntu.edu.sg/~frederique/dm2.pdf

• http://www1.spms.ntu.edu.sg/~frederique/dm3.pdf

• https://www.cin.ufpe.br/~tfl2/artificial-intelligence-modern-
approach.9780131038059.25368.pdf

40
• https://www.cs.swarthmore.edu/~eeaton/teaching/cs63/slides/Logic
.ppt

41
Binding and Unification
• Binding between known and unknown variable

• Unification between unknowns

• Two terms unify if substitutions can be made for any variables in the terms so
that the terms are made identical.

• If no such substitution exists, the terms do not unify.

• The Unification Algorithm proceeds by recursive descent of the two terms.


• Constants unify if they are identical
• Variables unify with any term, including other variables
• Compound terms unify if their functors and components unify.

42
Binding and Unification
• Binding and Unification
• ?- p(X, 2, 2) = p(1, Y, X).
• No

• ?- p(_, 2, 2) = p(1, Y, _).


• Y=2
• Yes

• ?- f(a, g(X, Y)) = f(X, Z), Z = g(W, h(X)).


• X=a
• Y = h(a)
• Z = g(a, h(a))
• W=a
• Yes

43

You might also like