AI Course Notes for Summer 2025
AI Course Notes for Summer 2025
2025-05-14
0.1. PREFACE i
0.1 Preface
0.1.1 Course Concept
Objective: The course aims at giving students a solid (and often somewhat theoretically
oriented) foundation of the basic concepts and practices of artificial intelligence. The course will
predominantly cover symbolic AI – also sometimes called “good old-fashioned AI (GofAI)” – in
the first semester and offers the very foundations of statistical approaches in the second. Indeed, a
full account sub symbolic, machine learning based AI deserves its own specialization courses and
needs much more mathematical prerequisites than we can assume in this course.
Context: The course “Artificial Intelligence” (AI 1 & 2) at FAU Erlangen is a two-semester
course in the “Wahlpflichtbereich” (specialization phase) in semester 5/6 of the bachelor program
“Computer Science” at FAU Erlangen. It is also available as a (somewhat remedial) course in the
“Vertiefungsmodul Künstliche Intelligenz” in the Computer Science Master’s program.
Prerequisites: AI-1 & 2 builds on the mandatory courses in the FAU bachelor’s program, in
particular the course “Grundlagen der Logik in der Informatik” [gloin:URL], which already covers
a lot of the materials usually presented in the “knowledge and reasoning” part of an introductory
AI course. The AI 1& 2 course also minimizes overlap with the course.
The course is relatively elementary, we expect that any student who attended the mandatory
CS course at FAU Erlangen can follow it.
Open to external students: Other bachelor programs are increasingly co-opting the course
as specialization option. There is no inherent restriction to CS students in this course. Students
with other study biographies – e.g. students from other bachelor programs our external Master’s
students should be able to pick up the prerequisites when needed.
0.1.4 Acknowledgments
Materials: Most of the materials in this course is based on Russel/Norvik’s book “Artificial
Intelligence — A Modern Approach” (AIMA [RussellNorvig:aiama95]). Even the slides are
based on a LATEX-based slide set, but heavily edited. The section on search algorithms is originallly
based on materials obtained from Bernhard Beckert (then Uni Koblenz), which is in turn based
on AIMA. Some extensions have been inspired by an AI course by Jörg Hoffmann and Wolfgang
Wahlster at Saarland University in 2016. Finally Dennis Müller suggested and supplied some
extensions on AGI.
In Summer 2024 Dennis Müller gave the AI-2 lecture and improved the presentation consider-
ably.
Last but not least, Florian Rabe, Max Rapp and Katja Berčič have carefully re-read the text
and pointed out problems.
All course materials have been restructured and semantically annotated in the STEX format,
so that we can base additional semantic services on them.
AI Students: The following students have submitted corrections and suggestions to this and
earlier versions of the notes: Rares Ambrus, Ioan Sucan, Yashodan Nevatia, Dennis Müller, Si-
mon Rainer, Demian Vöhringer, Lorenz Gorse, Philipp Reger, Benedikt Lorch, Maximilian Lösch,
Luca Reeb, Marius Frinken, Peter Eichinger, Oskar Herrmann, Daniel Höfer, Stephan Mattejat,
Matthias Sonntag, Jan Urfei, Tanja Würsching, Adrian Kretschmer, Tobias Schmidt, Maxim On-
ciul, Armin Roth, Liam Corona, Tobias Völk, Lena Voigt, Yinan Shao, Michael Girstl, Matthias
Vietz, Anatoliy Cherepantsev, Stefan Musevski, Matthias Lobenhofer, Philipp Kaludercic, Di-
warkara Reddy, Martin Helmke, Stefan Müller, Dominik Mehlich, Paul Martini, Vishwang Dave,
Arthur Miehlich, Christian Schabesberger, Vishaal Saravanan, Simon Heilig, Michelle Fribrance,
Wenwen Wang, Xinyuan Tu, Lobna Eldeeb.
0.1 Preface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . i
0.1.1 Course Concept . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . i
0.1.2 Course Contents . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . i
0.1.3 This Document . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . i
0.1.4 Acknowledgments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ii
0.1.5 Recorded Syllabus . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ii
1 Preliminaries 1
1.1 TL;DR: Goals and Links . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
1.2 Administrative Ground Rules . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
1.3 Getting Most out of AI-2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
1.4 Learning Resources for AI-2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
1.5 ALeA – AI-Supported Learning . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
1.6 AI-Supported Learning – How does it work? . . . . . . . . . . . . . . . . . . . . . . 18
iii
iv CONTENTS
Preliminaries
In this chapter, we want to get all the organizational matters out of the way, so that we can
get course contents unencumbered. We will talk about the necessary administrative details, go
into how students can get most out of the course, talk about where the various resources provided
with the course can be found, and finally introduce the ALeA system, an experimental – using
AI methods – learning support system for the AI-2 course.
In the broadest sense: A bunch of tools for your toolchest (i.e. various
(quasi-mathematical) models, first and foremost)
the underlying principles of these models (assumptions, limitations, the math behind
them ...)
the ability to describe real-world problems in terms of these models, where adequate
(...and knowing when they are adequate!), and
the ideas behind effective algorithms that solve these problems (and to understand them
well enough to implement them)
Note: You will likely never get payed to implement an algorithm that e.g. solves Bayesian
networks. (They already exist)
But you might get payed to recognize that some given problem can be represented as a
Bayesian network!
Or: you can recognize that it is similar to a Bayesian network, and reuse the underlying
principles to develop new specialized tools.
: 1 2025-05-14
In other words: Many things you learn here are means to an end (e.g. understanding the under-
lying ideas behind algorithms), not the end itself. But the best way to understand these means is
to first treat them as an end in themselves.
1
2 CHAPTER 1. PRELIMINARIES
Employee 2 – AI-2 Alumna: “...while you were talking, I quickly built a custom UI for an
off-the-shelve <problem> solver that runs on a medium-sized potato and returns a provably
correct result in a few milliseconds. For inputs longer than 1000unit, you might need a
slightly bigger potato though...”
Moral of the story: Know your tools well enough to select the right one for the job.
: 2 2025-05-14
Obviously, that is not to say that machine learning is not a useful tool! (It is!)
If your job is to e.g. filter customer support requests, or to recognize cats in pictures, trying to
write a prolog program from scratch is probably the wrong approach: Just use a language model
/ image model and finetune it on a classification head.
But it is also not the only tool, and it is not always the right tool for the job – despite what
some people might tell you. And even in scenarios where machine learning can yield decent results,
it is not always the best tool. (Some people care about efficiency, explainability, etc ;))
In an ideal world . . . We would spend weeks on each topic, give you lots of interesting
problems to solve, give you individual feedback and tutoring.
As an exam, you would have to solve a few real-world problems by choosing the right tools,
model the problem accordingly, customize the algorithms to the specifics, implement them.
; You would each write a 10 page essay in 4 hours, we would spend the next 6 months grading
them, and then 95% of you would probably fail: Really understanding this stuff takes time and
lots of practice!
Instead: we will teach you all the important stuff, give you practice problems to do on your
own, and then test you on the basics in a manner that is actually gradable in a reasonable time
frame, and doable
Hopefully, in five years, when you encounter a problem, you will remember enough of the broad
strokes to recognize the “kind of problem” you have, and are able to look up the rest easily.
: 3 2025-05-14
: 4 2025-05-14
Note: I do not literally presuppose the courses on the slide above – most of you do not have
a bachelor’s degree from FAU, so you cannot have taken them. And indeed some of the content
of these courses is irrelevant for AI-2. Stating these courses is just the easiest way to specifying
what content I will be building on – and any graduate courses has to build on something.
Many of you will have taken the moral equivalent of these courses in your undergraduate studies
at your home university. If you did not, you will have to somehow catch up on the content as we
go along in AI-2. This should be possible with enough motivation.
There are essentially three skillsets that are essential for AI-2:
4 CHAPTER 1. PRELIMINARIES
3. A solid understanding of formal languages and grammars, as well as applied complexity theory
(basics of theoretical computer science).
Without (catching up on) these the AI-2 course will be quite frustrating and hard.
We will briefly go over the most important topics in chapter 4 to synchronize concepts and
notation. Note that if you do not have a formal education in courses like the ones mentioned
above you will very probably have to do significant remedial work.
Now we come to a topic that is always interesting to the students: the grading scheme.
Assessment, Grades
Overall (Module) Grade:
Grade via the exam (Klausur) ; 100% of the grade.
Up to 10% bonus on-top for an exam with ≥ 50% points. (< 50% ; no bonus)
Bonus points =
b percentage sum of the best 10 prepquizzes divided by 100.
Exam: exam conducted in presence on paper! (∼ Oct. 10. 2025)
Retake Exam: 90 minutes exam six months later. (∼ April 10. 2026)
You have to register for exams in [Link] in the first month of classes.
Note: You can de-register from an exam on [Link] up to three working
days before exam. (do not miss that if you are not prepared)
: 5 2025-05-14
Preparedness Quizzes
PrepQuizzes: Before every lecture we offer a 10 min online quiz – the PrepQuiz – about
the material from the previous week. (16:15-16:25; starts in week 2)
Motivations: We do this to
keep you prepared and working continuously. (primary)
bonus points if the exam has ≥ 50% points (potential part of your grade)
update the ALeA learner model. (fringe benefit)
[Link]
You have to be logged into ALeA! (via FAU IDM)
: 6 2025-05-14
The pretest covers the prerequisites of AI-2 and some of the material that may have been
covered in other courses.
The test will be also used to refine the ALeA learner model, which may make learning
experience in ALeA better. (see below)
: 7 2025-05-14
Due to the current AI hype, the course Artificial Intelligence is very popular and thus many
degree programs at FAU have adopted it for their curricula. Sometimes the course setup that fits
6 CHAPTER 1. PRELIMINARIES
for the CS program does not fit the other’s very well, therefore there are some special conditions.
I want to state here.
: 8 2025-05-14
I can only warn of what I am aware, so if your degree program lets you jump through extra hoops,
please tell me and then I can mention them here.
Homeworks give no points, but without trying you are unlikely to pass the exam.
Our Experience: Doing your homework is probably even more important (and predictive
of exam success) than attending the lecture in person!
Homeworks will be mainly peer-graded in the ALeA system.
Didactic Motivation: Through peer grading students are able to see mistakes in their think-
ing and can correct any problems in future assignments. By grading assignments, students
may learn how to complete assignments more accurately and how to improve their future
results. (not just us being lazy)
: 9 2025-05-14
1.3. GETTING MOST OUT OF 7
It is very well-established experience that without doing the homework assignments (or something
similar) on your own, you will not master the concepts, you will not even be able to ask sensible
questions, and take very little home from the course. Just sitting in the course and nodding is not
enough!
Homework/Tutorial Discipline:
Start early! (many assignments need more than one evening’s work)
Don’t start by sitting at a blank screen (talking & study groups help)
Humans will be trying to understand the text/code/math when grading it.
Go to the tutorials, discuss with your TA! (they are there for you!)
: 10 2025-05-14
If you have questions please make sure you discuss them with the instructor, the teaching
assistants, or your fellow students. There are three sensible venues for such discussions: online in
the lectures, in the tutorials, which we discuss now, or in the course forum – see below. Finally,
it is always a very good idea to form study groups with your friends.
Approach: Weekly tutorials and homework assignments (first one in week two)
Goal 1: Reinforce what was taught in the lectures. (you need practice)
Goal 2: Allow you to ask any question you have in a protected environment.
Details (rooms, times, etc) will be announced in time (i.e. not now) on the forum and
matrix channel.
Life-saving Advice: Go to your tutorial, and prepare for it by having looked at the slides
and the homework assignments!
: 11 2025-05-14
Collaboration
Definition 1.3.1. Collaboration (or cooperation) is the process of groups of agents acting
together for common, mutual benefit, as opposed to acting in competition for selfish bene-
fit. In a collaboration, every agent contributes to the common goal and benefits from the
contributions of others.
In learning situations, the benefit is “better learning”.
Observation: In collaborative learning, the overall result can be significantly better than in
competitive learning.
Choose your study group well! (ALeA helps via the study buddy feature)
: 12 2025-05-14
As we said above, almost all of the components of the AI-2 course are optional. That even applies
to attendance. But make no mistake, attendance is important to most of you. Let me explain, . . .
: 13 2025-05-14
Do use the opportunity to discuss the AI-2 topics with others. After all, one of the non-trivial
skills you want to learn in the course is how to talk about artificial intelligence topics. And that
takes practice, practice, and practice.
1.4. LEARNING RESOURCES FOR 9
: 14 2025-05-14
: 15 2025-05-14
FAU has issued a very insightful guide on using lecture videos. It is a good idea to heed these
recommendations, even if they seem annoying at first.
Catch up.
: 16 2025-05-14
You will only pass the exam, if you can do AI-1 yourself!
Intuition: AI tools like GhatGPT, CoPilot, etc. (see also [Shein:iacse24])
can help you solve problems, (valuable tools in production situations)
hinders learning if used for homeworks/quizzes, etc. (like driving instead of jogging)
What (not) to do: (to get most of the brave new AI-supported world)
try out these tools to get a first-hand intuition what they can/cannot do
challenge yourself while learning so that you can also do it (mind over matter!)
: 17 2025-05-14
Goal: Make ALeA more like a instructor + study group than like a book!
Example 1.5.2 (Course Notes). =
b Slides + Comments
: 18 2025-05-14
The central idea in the AI4AI approach – using AI to support learning AI – and thus the ALeA
system is that we want to make course materials – i.e. what we give to students for preparing and
12 CHAPTER 1. PRELIMINARIES
postparing lectures – more like teachers and study groups (only available 24/7) than like static
books.
(some) students use the system actively (our logs tell us)
reviews are mostly positive/enthusiastic (error reports pour in)
: 19 2025-05-14
The ALeA AI-2 page is the central entry point for working with the ALeA system. You can get
to all the components of the system, including two presentations of the course contents (notes-
and slides-centric ones), the flashcards, the localized forum, and the quiz dashboard.
We now come to the heart of the ALeA system: its learning support services, which we will now
briefly introduce. Note that this presentation is not really sufficient to undertstand what you may
be getting out of them, you will have to try them, and interact with them sufficiently that the
learner model can get a good estimate of your competencies to adapt the results to you.
Example 1.5.4 (More Definitions on Click). Clicking on a (cyan) term reference shows
us more definitions from other contexts.
14 CHAPTER 1. PRELIMINARIES
Example 1.5.5 (Guided Tour). A guided tour for a concept c assembles definitions/etc.
into a self-contained mini-course culminating at c.
c = count-
able ;
: 20 2025-05-14
Note that this is only an initial collection of learning support services, we are constantly working
on additional ones. Look out for feature notifications ( ) on the upper right hand of
the ALeA screen.
: 21 2025-05-14
While the learning support services up to now have been adressed to individual learners, we
now turn to services addressed to communities of learners, ranging from study groups with three
learners, to whole courses, and even – eventually – all the alumni of a course, if they have not
de-registered from ALeA.
Currently, the community aspect of ALeA only consists in localized interactions with the course
materials.
The ALeA system uses the semantic structure of the course materials to localize some interactions
that are otherwise often from separate applications. Here we see two:
1. one for reporting content errors – and thus making the material better for all learners – and‘’
2. a localized course forum, where forum threads can be attached to learning objects.
Localized comments induce a thread in the ALeA forum (like the StudOn Forum, but
targeted towards specific learning objects.)
16 CHAPTER 1. PRELIMINARIES
: 22 2025-05-14
We can use the same four models discussed in the space of guided tours to deploy additional
learning support services, which we now discuss.
Idea: Challenge yourself to a card stack, keep drilling/assessing flashcards until the learner
model eliminates all.
Bonus: Flashcards can be generated from existing semantic markup (educational
equivalent to free beer)
: 23 2025-05-14
We have already seen above how the learner model can drive the drilling with flashcards. It can
also be used for the configuration of card stacks by configuring a domain e.g. a section in the
course materials and a competency threshold. We now come to a very important issue
that we always face when we do AI systems that interface with humans. Most web technology
1.5. ALEA – AI-SUPPORTED LEARNING 17
companies that take one the approach “the user pays for the services with their personal data,
which is sold on” or integrate advertising for renumeration. Both are not acceptable in university
setting.
But abstaining from monetizing personal data still leaves the problem how to protect it from
intentional or accidental misuse. Even though the GDPR has quite extensive exceptions for
research, the ALeA system – a research prototype – adheres to the principles and mandates of
the GDPR. In particular it makes sure that personal data of the learners is only used in learning
support services directly or indirectly initiated by the learners themselves.
: 24 2025-05-14
So, now that you have an overview over what the ALeA system can do for you, let us see what
you have to concretely do to be able to use it.
: 25 2025-05-14
Even if you did not understand some of the AI jargon or the underlying methods (yet), you
should be good to go for using the ALeA system in your day-to-day work.
ALeA=
b Data-Driven & AI-enabled Learning Assistance
Learner Rhetoric/Didactic
Model Model
understand the objects and their properties they are talking about
have readimade formulations how to convey them best
: 26 2025-05-14
20 CHAPTER 1. PRELIMINARIES
Chapter 2
We start the course by giving an overview of (the problems, methods, and issues of) artificial
intelligence, and what has been achieved so far.
Naturally, this will dwell mostly on philosophical aspects – we will try to understand what
the important issues might be and what questions we should even be asking. What the most
important avenues of attacks may be and where AI research is being carried out.
In particular the discussion will be very non-technical – we have very little basis to discuss
technicalities yet. But stay with me, this will drastically change very soon. the introduction of
this chapter ]21467
: 27 2025-05-14
21
22 CHAPTER 2. AI – WHO?, WHAT?, WHEN?, WHERE?, AND WHY?
Maybe we can get around the problems of defining “what artificial intelligence is”, by just describ-
ing the necessary components of AI (and how they interact). Let’s have a try to see whether that
is more informative.
Inference
Perception
2.2. ARTIFICIAL INTELLIGENCE IS HERE TODAY! 23
Language understanding
Emotion
: 29 2025-05-14
Note that list of components is controversial as well. Some say that it lumps together cognitive
capacities that should be distinguished or forgets others, . . . . We state it here much more to get
AI-2 students to think about the issues than to make it normative.
in outer space
in outer space systems
need autonomous con-
trol:
remote control impos-
sible due to time lag
in artificial limbs
the user controls the
prosthesis via existing
nerves, can e.g. grip
a sheet of paper.
in household appliances
The iRobot Roomba
vacuums, mops, and
sweeps in corners, . . . ,
parks, charges, and
discharges.
general robotic house-
hold help is on the
horizon.
in hospitals
in the USA 90% of the
prostate operations are
carried out by Ro-
boDoc
Paro is a cuddly robot
that eases solitude in
nursing homes.
26 CHAPTER 2. AI – WHO?, WHAT?, WHEN?, WHERE?, AND WHY?
: 30 2025-05-14
The AI Conundrum
Observation: Reserving the term “artificial intelligence” has been quite a land grab!
But: researchers at the Dartmouth Conference (1956) really thought they would solve/reach
AI in two/three decades.
Consequence: AI still asks the big questions. (and still promises answers soon)
Another Consequence: AI as a field is an incubator for many innovative technologies.
Still Consequence: AI research was alternatingly flooded with money and cut off brutally.
: 31 2025-05-14
All of these phenomena can be seen in the growth of AI as an academic discipline over the course
of its now over 70 year long history.
Funding levels are tied to public perception of success (especially for AI)
Definition 2.2.2. An AI winter is a time period of low public perception and funding for AI,
mostly because AI has failed to deliver on its – sometimes overblown – promises
An AI summer is a time period of high public perception and funding for AI
AI becomes
scarily effective,
ubiquitous
Excitement fades;
some applications
AI-conse- profit a lot
quences,
Biases, AI-bubble bursts,
Regulation the next AI winter
Lighthill report WWW ; comes
Dartmouth Conference Data/-
Turing Test Computing
AI Winter 2
AI Winter 1 Explosion
1987-1994
1974-1980
: 32 2025-05-14
Of course, the future of AI is still unclear, we are currently in a massive hype caused by the advent
of deep neural networks being trained on all the data of the Internet, using the computational
power of huge compute farms owned by an oligopoly of massive technology companies – we are
definitely in an AI summer.
But AI as a academic community and the tech industry also make outrageous promises, and
the media pick it up and distort it out of proportion, . . . So public opinion could flip again, sending
AI into the next winter.
: 33 2025-05-14
As a consequence, the field of artificial intelligence (AI) is an engineering field at the intersection of
CS (logic, programming, applied statistics), Cognitive Science (psychology, neuroscience), philos-
ophy (can machines think, what does that mean?), linguistics (natural language understanding),
and mechatronics (robot hardware, sensors).
Subsymbolic AI and in particular machine learning is currently hyped to such an extent, that
many people take it to be synonymous with “Artificial Intelligence”. It is one of the goals of this
course to show students that this is a very impoverished view.
28 CHAPTER 2. AI – WHO?, WHAT?, WHEN?, WHERE?, AND WHY?
We can classify the AI approaches by their coverage and the analysis depth (they are
complementary)
: 34 2025-05-14
We combine the topics in this way in this course, not only because this reproduces the histor-
ical development but also as the methods of statistical and subsymbolic AI share a common
basis.
It is important to notice that all approaches to AI have their application domains and strong points.
We will now see that exactly the two areas, where symbolic AI and statistical/subsymbolic AI
have their respective fortes correspond to natural application areas.
Precision
100% Producer Tasks
General Rule: Subsymbolic AI is well suited for consumer tasks, while symbolic AI is better
suited for producer tasks.
2.4. STRONG VS. WEAK AI 29
: 35 2025-05-14
An example of a producer task – indeed this is where the name comes from – is the case of a
machine tool manufacturer T , which produces digitally programmed machine tools worth multiple
million Euro and sells them into dozens of countries. Thus T must also provide comprehensive
machine operation manuals, a non-trivial undertaking, since no two machines are identical and
they must be translated into many languages, leading to hundreds of documents. As those manual
share a lot of semantic content, their management should be supported by AI techniques. It is
critical that these methods maintain a high precision, operation errors can easily lead to very
costly machine damage and loss of production. On the other hand, the domain of these manuals is
quite restricted. A machine tool has a couple of hundred components only that can be described
by a couple of thousand attributes only.
Indeed companies like T employ high-precision AI techniques like the ones we will cover in this
course successfully; they are just not so much in the public eye as the consumer tasks.
Definition 2.4.2. With the term strong AI (also full AI, AGI) we denote the quest for
software performing at the full range of human cognitive abilities.
Definition 2.4.3. Problems requiring strong AI to solve are called AI hard, and AI complete,
iff AGI should be able to solve them all.
: 36 2025-05-14
One can usually defuse public worries about “is AI going to take control over the world” by just
explaining the difference between strong AI and weak AI clearly.
I would like to add a few words on AGI, that – if you adopt them; they are not universally accepted
– will strengthen the arguments differentiating between strong and weak AI.
AGI research focuses mostly on abstract aspects of machine learning (reinforcement learning,
neural nets) and decision/game theory (“which goals should an AGI pursue?”).
Academic respectability of AGI fluctuates massively, recently increased (again). (correlates
somewhat with AI winters and golden years)
Public attention increasing due to talk of “existential risks of AI” (e.g. Hawking, Musk,
Bostrom, Yudkowsky, Obama, . . . )
Kohlhase’s View: Weak AI is here, strong AI is very far off. (not in my lifetime)
: But even if that is true, weak AI will affect all of us deeply in everyday life.
: 37 2025-05-14
I want to conclude this section with an overview over the recent protagonists – both personal and
institutional – of AGI.
Be highly skeptical about any claims with respect to AGI! (Kohlhase’s View)
: 38 2025-05-14
Problem Solving and search (Black Box World States and Actions)
Adversarial search (Game playing) (A nice application of search)
constraint satisfaction problems (Factored World States)
: 39 2025-05-14
: 40 2025-05-14
Partial Solution: Getting your hands dirty in the homeworks and the Kalah Challenge
Full Solution: AI1SysProj: AI-1 Systems Project (10 ECTS, 30-50places)
For each Topic of AI-1, where will be a mini-project in AI1SysProj
e.g. for game-play there will be Chinese Checkers (more difficult than Kalah)
e.g. for CSP we will schedule TechFak courses or exams (from real data)
solve challenges by implementing the AI-1 algorithms or use SoA systems
Question: Should I take AI1SysProj in my first semester? (i.e. now)
: 41 2025-05-14
Thus: reasoning components of some form are at the heart of many AI systems.
KWARC Angle: Scaling up (web-coverage) without dumbing down (too much)
Content markup instead of full formalization (too tedious)
User support and quality control instead of “The Truth” (elusive anyway)
use Mathematics as a test tube ( Mathematics =
b Anything Formal )
care more about applications than about philosophy (we cannot help getting this right
anyway as logicians)
The KWARC group was established at Jacobs Univ. in 2004, moved to FAU Erlangen in
2016
See [Link] for projects, publications, and links
: 42 2025-05-14
Research in the KWARC group ranges over a variety of topics, which range from foundations of
mathematics to relatively applied web information systems. I will try to organize them into three
2.6. AI IN THE KWARC GROUP 33
pillars here.
: 43 2025-05-14
For all of these areas, we are looking for bright and motivated students to work with us. This
can take various forms, theses, internships, and paid students assistantships.
: 44 2025-05-14
Sciences like physics or geology, and engineering need high-powered equipment to perform
measurements or experiments. CS and in particular the KWARC group needs high powered human
brains to build systems and conduct thought experiments.
The KWARC group may not always have as much funding as other AI research groups, but
we are very dedicated to give the best possible research guidance to the students we supervise.
So if this appeals to you, please come by and talk to us.
34 CHAPTER 2. AI – WHO?, WHAT?, WHEN?, WHERE?, AND WHY?
Part I
35
37
This part of the lecture notes sets the stage for the technical parts of the course by establishing
a common framework (Rational Agents) that gives context and ties together the various methods
discussed in the course. After having seen what AI can do and where artificial
intelligence is being employed today (see chapter 2), we will now
ad 1. Prolog: For the programming language we choose Prolog, historically one of the most
influential “AI programming languages”. While the other AI programming language: Lisp which
gave rise to the functional programming programming paradigm has been superseded by typed
languages like SM L, Haskell, Scala, and F#, Prolog is still the prime example of the declarative
programming paradigm. So using Prolog in this course gives students the opportunity to explore
this paradigm. At the same time, Prolog is well-suited for trying out algorithms in symbolic AI the
topic of this semester since it internalizes the more complex primitives of the algorithms presented
here.
ad 2. Rational Agents: The conceptual framework centers around rational agents which
combine aspects of purely cognitive architectures (an original concern for the field of AI) with the
more recent realization that intelligence must interact with the world (embodied AI) to grow and
learn. The cognitive architectures aspect allows us to place and relate the various algorithms and
methods we will see in this course. Unfortunately, the “situated AI” aspect will not be covered in
this course due to the lack of time and hardware.
ad 3. Topics of Theoretical Computer Science: When we evaluate the methods and
algorithms introduced in AI-2, we will need to judge their suitability as agent functions. The main
theoretical tool for that is complexity theory; we will give a short motivation and overview of the
main methods and results as far as they are relevant for AI-2 in section 4.1.
In the second half of the semester we will transition from search-based methods for problem
solving to inference-based ones, i.e. where the problem formulation is described as expressions of a
formal language which are transformed until an expression is reached from which the solution can
be read off. Phrase structure grammars are the method of choice for describing such languages;
we will introduce/recap them in section 4.2.
: 45 2025-05-14
38
Chapter 3
Logic Programming
We will now learn a new programming paradigm: logic programming, which is one of the most
influential paradigms in AI. We are going to study Prolog (the oldest and most widely used) as a
concrete example of ideas behind logic programming and use it for our homeworks in this course.
As Prolog is a representative of a programming paradigm that is new to most students, pro-
gramming will feel weird and tedious at first. But subtracting the unusual syntax and program
organization logic programming really only amounts to recursive programming just as in func-
tional programming (the other declarative programming paradigm). So the usual advice applies,
keep staring at it and practice on easy examples until the pain goes away.
Logic Programming
Idea: Use logic as a programming language!
We state what we know about a problem (the program) and then ask for results (what the
program would compute).
Example 3.1.1.
How to achieve this? Restrict a logic calculus sufficiently that it can be used as computa-
tional procedure.
39
40 CHAPTER 3. LOGIC PROGRAMMING
Remark: This idea leads a totally new programming paradigm: logic programming.
Slogan: Computation = Logic + Control (Robert Kowalski 1973; [Kowalski:alc79])
We will use the programming language Prolog as an example.
: 46 2025-05-14
We now formally define the language of Prolog, starting off the atomic building blocks.
: 47 2025-05-14
The first three lines are Prolog facts and the last a rule.
: 48 2025-05-14
The whole point of writing down a knowledge base (a Prolog program with knowledge about the
situation), if we do not have to write down all the knowledge, but a (small) subset, from which
the rest follows. We have already seen how this can be done: with logic. For logic programming
we will use a logic called “first-order logic” which we will not formally introduce here.
Definition 3.1.8. The knowledge base given by Prolog program is that set of facts that can
be derived from it by Modus Ponens (MP), ∧I and instantiation.
A A⇒B A B A
MP ∧I Subst
B A∧B [B/X](A)
: 49 2025-05-14
??? introduces a very important distinction: that between a Prolog program and the knowledge
base it induces. Whereas the former is a finite, syntactic object (essentially a string), the latter
may be an infinite set of facts, which represents the totality of knowledge about the world or the
aspects described by the program.
As knowledge bases can be infinite, we cannot pre-compute them. Instead, logic programming
languages compute fragments of the knowledge base by need; i.e. whenever a user wants to check
membership; we call this approach querying: the user enters a query expression and the system
answers yes or no. This answer is computed in a depth first search process.
: 50 2025-05-14
: 51 2025-05-14
Note that backchaining replaces the current query with the body of the rule suitably instantiated.
For rules with a long body this extends the list of current goals, but for facts (rules without a
body), backchaining shortens the list of current goals. Once there are no goals left, the Prolog
interpreter finishes and signals success by issuing the string true.
If no rules match the current subgoal, then the interpreter terminates and signals failure with the
string false,
: 52 2025-05-14
We can extend querying from simple yes/no answers to programs that return values by simply
using variables in queries. In this case, the Prolog interpreter returns a substitution.
repeated backchaining.
Example 3.1.16. We talk about (Bavarian) cars for a change, and use a query with a
variables
has_wheels(mybmw,4).
has_motor(mybmw).
car(X):−has_wheels(X,4),has_motor(X).
?− car(Y) % query
?− has_wheels(Y,4),has_motor(Y). % substitution X = Y
?− has_motor(mybmw). % substitution Y = mybmw
Y = mybmw % answer substitution
true
: 53 2025-05-14
In ??? the first backchaining step binds the variable X to the query variable Y, which gives us the
two subgoals has_wheels(Y,4),has_motor(Y). which again have the query variable Y. The next
backchaining step binds this to mybmw, and the third backchaining step exhausts the subgoals.
So the query succeeds with the (overall) answer substitution Y = mybmw. With this setup, we
can already do the “fallible Greeks” example from the introduction.
: 54 2025-05-14
which asserts that the predicate unat2 is true on the term zero. Generally, we can add a fact to
the knowledge base either by writing it into a file (e.g. [Link]) and then “consulting it” by
writing one of the following three commands into the interpreter:
[example]
consult(’[Link]’).
consult(’example’).
or by directly typing
assert(unat(zero)).
into the Prolog interpreter. Next tell Prolog about the following rule
assert(unat(suc(X)) :− unat(X)).
which gives the Prolog runtime an initial (infinite) knowledge base, which can be queried by
?− unat(suc(suc(zero))).
Even though we can use any text editor to program Prolog, but running Prolog in a modern
editor with language support is incredibly nicer than at the command line, because you can see
the whole history of what you have done. Its better for debugging too.
So far, all the examples led to direct success or to failure. (simple KB)
Definition 3.2.1 (Prolog Search Procedure). The Prolog interpreter employs top-down,
left-right depth first search, concretely, Prolog search:
We say that a goal G matches a head H, iff we can make them equal by replacing variables
in H with terms.
We can force backtracking to compute more answers by typing ;.
: 55 2025-05-14
Note: With the Prolog search procedure detailed above, computation can easily go into infinite
loops, even though the knowledge base could provide the correct answer. Consider for instance
the simple program
p(X):− p(X).
p(X):− q(X).
q(X).
If we query this with ?− p(john), then DFS will go into an infinite loop because Prolog expands
by default the first predicate. However, we can conclude that p(john) is true if we start expanding
the second predicate.
2 for “unary natural numbers”.
3.2. PROGRAMMING AS SEARCH 45
In fact this is a necessary feature and not a bug for a programming language: we need to
be able to write non-terminating programs, since the language would not be Turing complete
otherwise. The argument can be sketched as follows: we have seen that for Turing machines the
halting problem is undecidable. So if all Prolog programs were terminating, then Prolog would be
weaker than Turing machines and thus not Turing complete.
We will now fortify our intuition about the Prolog search procedure by an example that extends
the setup from ??? by a new choice of a vehicle that could be a car (if it had a motor).
Backtracking by Example
Example 3.2.2. We extend ???:
has_wheels(mytricycle,3).
has_wheels(myrollerblade,3).
has_wheels(mybmw,4).
has_motor(mybmw).
car(X):-has_wheels(X,3),has_motor(X). % cars sometimes have three wheels
car(X):-has_wheels(X,4),has_motor(X). % and sometimes four.
?- car(Y).
?- has_wheels(Y,3),has_motor(Y). % backtrack point 1
Y = mytricycle % backtrack point 2
?- has_motor(mytricycle).
FAIL % fails, backtrack to 2
Y = myrollerblade % backtrack point 2
?- has_motor(myrollerblade).
FAIL % fails, backtrack to 1
?- has_wheels(Y,4),has_motor(Y).
Y = mybmw
?- has_motor(mybmw).
Y=mybmw
true
: 56 2025-05-14
In general, a Prolog rule of the form A:−B,C reads as “A, if B and C”. If we want to express
“A if B or C”, we have to express this two separate rules A:−B and A:−C and leave the choice
which one to use to the search procedure.
In Example 3.2.2 we indeed have two clauses for the predicate car/1; one each for the cases of cars
with three and four wheels. As the three-wheel case comes first in the program, it is explored first
in the search process.
Recall that at every point, where the Prolog interpreter has the choice between two clauses for
a predicate, chooses the first and leaves a backtrack point. In Example 3.2.2 this happens first
for the predicate car/1, where we explore the case of three-wheeled cars. The Prolog interpreter
immediately has to choose again – between the tricycle and the rollerblade, which both have three
wheels. Again, it chooses the first and leaves a backtrack point. But as tricycles do not have mo-
tors, the subgoal has_motor(mytricycle) fails and the interpreter backtracks to the chronologically
nearest backtrack point (the second one) and tries to fulfill has_motor(myrollerblade). This fails
again, and the next backtrack point is point 1 – note the stack-like organization of backtrack points
which is in keeping with the depth-first search strategy – which chooses the case of four-wheeled
cars. This ultimately succeeds as before with y=mybmw.
We now turn to a more classical programming task: computing with numbers. Here we turn
to our initial example: adding unary natural numbers. If we can do that, then we have to consider
Prolog a programming language.
46 CHAPTER 3. LOGIC PROGRAMMING
expt(X,zero,s(zero)).
expt(X,s(Y),Z) :− expt(X,Y,W), mult(X,W,Z).
: 57 2025-05-14
Note: Viewed through the right glasses logic programming is very similar to functional program-
ming; the only difference is that we are using n + 1 ary relations rather than n ary function. To see
how this works let us consider the addition function/relation example above: instead of a binary
function + we program a ternary relation add, where relation add(X,Y ,Z) means X + Y = Z. We
start with the same defining equations for addition, rewriting them to relational style.
The first equation is straight-forward via our correspondence and we get the Prolog fact
add(X,zero,X). For the equation X + s(Y ) = s(X + Y ) we have to work harder, the straight-
forward relational translation add(X,s(Y),s(X+Y)) is impossible, since we have only partially
replaced the function + with the relation add. Here we take refuge in a very simple trick that we
can always do in logic (and mathematics of course): we introduce a new name Z for the offending
expression X + Y (using a variable) so that we get the fact add(X,s(Y ),s(Z)). Of course this is
not universally true (remember that this fact would say that “X + s(Y ) = s(Z) for all X, Y , and
Z”), so we have to extend it to a Prolog rule add(X,s(Y),s(Z)):−add(X,Y,Z). which relativizes to
mean “X + s(Y ) = s(Z) for all X, Y , and Z with X + Y = Z”.
Indeed the rule implements addition as a recursive predicate, we can see that the recursion
relation is terminating, since the left hand sides have one more constructor for the successor
function. The examples for multiplication and exponentiation can be developed analogously, but
we have to use the naming trick twice.
We now apply the same principle of recursive programming with predicates to other examples
to reinforce our intuitions about the principles.
X = s(s(zero))
true
Example 3.2.5. Computing the nth Fibonacci number (0, 1, 1, 2, 3, 5, 8, 13,. . . ; add the
last two to get the next), using the addition predicate above.
fib(zero,zero).
fib(s(zero),s(zero)).
fib(s(s(X)),Y):−fib(s(X),Z),fib(X,W),add(Z,W,Y).
Example 3.2.6. Using Prolog’s internal floating-point arithmetic: a goal of the form
?− D is e. — where e is a ground arithmetic expression binds D to the result of evaluat-
ing e.
fib(0,0).
fib(1,1).
fib(X,Y):− D is X − 1, E is X − 2,fib(D,Z),fib(E,W), Y is Z + W.
: 58 2025-05-14
Note: Note that the is relation does not allow “generate and test” inversion as it insists on the
right hand being ground. In our example above, this is not a problem, if we call the fib with
the first (“input”) argument a ground term. Indeed, it matches the last rule with a goal ?− g,Y.,
where g is a ground term, then g−1 and g−2 are ground and thus D and E are bound to the
(ground) result terms. This makes the input arguments in the two recursive calls ground, and we
get ground results for Z and W, which allows the last goal to succeed with a ground result for
Y. Note as well that re-ordering the bodys literal of the rule so that the recursive calls are called
before the computation literals will lead to failure.
We will now add the primitive data structure of lists to Prolog; they are constructed by prepending
an element (the head) to an existing list (which becomes the rest list or “tail” of the constructed
one).
append([],L,L).
append([X|R],L,[X|S]):−append(R,L,S).
reverse([],[]).
reverse([X|R],L):−reverse(R,S),append(S,[X],L).
48 CHAPTER 3. LOGIC PROGRAMMING
: 59 2025-05-14
Logic programming is the third large programming paradigm (together with functional program-
ming and imperative programming).
: 60 2025-05-14
From a programming practice point of view it is probably best understood as “relational program-
ming” in analogy to functional programming, with which it shares a focus on recursion.
The major difference to functional programming is that “relational programming” does not have
a fixed input/output distinction, which makes the control flow in functional programs very direct
and predictable. Thanks to the underlying search procedure, we can sometime make use of the
flexibility afforded by logic programming.
If the problem solution involves search (and depth first search is sufficient), we can just get by
with specifying the problem and letting the Prolog interpreter do the rest. In Example 3.2.11 we
just specify that list Xs can be sorted into Ys, iff Ys is a permutation of Xs and Ys is ordered.
Given a concrete (input) list Xs, the Prolog interpreter will generate all permutations of Ys of Xs
via the predicate perm/2 and then test them whether they are ordered.
This is a paradigmatic example of logic programming. We can (sometimes) directly use the
specification of a problem as a program. This makes the argument for the correctness of the
program immediate, but may make the program execution non optimal.
: 61 2025-05-14
We “define” the computational behavior of the predicate rev, but the list constructors [. . .]
are just used to construct lists from arguments.
Example 3.2.16 (Trees and Leaf Counting). We represent (unlabelled) trees via the
function t from tree lists to trees. For instance, a balanced binary tree of depth 2 is
t([t([t([]),t([])]),t([t([]),t([])])]). We count leaves by
leafcount(t([]),1).
leafcount(t([V]),W) :− leafcount(V,W).
leafcount(t([X|R]),Y) :− leafcount(X,Z), leafcount(t(R),W), Y is Z + W.
: 62 2025-05-14
RTFM (b
= “read the fine manuals”)
RTFM Resources: There are also lots of good tutorials on the web,
I personally like [Fisher:pt:on; LPN:on],
[Flach:SL94] has a very thorough logic-based introduction,
consult also the SWI Prolog Manual [SWIPL-manual:on],
: 63 2025-05-14
50 CHAPTER 3. LOGIC PROGRAMMING
Chapter 4
In this chapter we will briefly recap some of the prerequisites from theoretical CS that are needed
for understanding Artificial Intelligence 1.
51
52CHAPTER 4. RECAP OF PREREQUISITES FROM MATH & THEORETICAL COMPUTER SCIENCE
performance
size linear quadratic exponential
n 100nµs 7n2 µs 2n µs
1 100µs 7µs 2µs
5 .5ms 175µs 32µs
10 1ms .7ms 1ms
45 4.5ms 14ms 1.1Y
100 ... ... ...
1 000 ... ... ...
10 000 ... ... ...
1 000 000 ... ... ...
: 64 2025-05-14
The last number in the rightmost column may surprise you. Does the run time really grow that
fast? Yes, as a quick calculation shows; and it becomes much worse, as we will see.
Example 4.1.2. We denote all times that are longer than the age of the universe with −
performance
size linear quadratic exponential
n 100nµs 7n2 µs 2n µs
1 100µs 7µs 2µs
5 .5ms 175µs 32µs
10 1ms .7ms 1ms
45 4.5ms 14ms 1.1Y
< 100 100ms 7s 1016 Y
1 000 1s 12min −
10 000 10s 20h −
1 000 000 1.6min 2.5mon −
: 65 2025-05-14
So it does make a difference for larger computational problems what algorithm we choose. Consid-
erations like the one we have shown above are very important when judging an algorithm. These
evaluations go by the name of “complexity theory”.
Let us now recapitulate some notions of elementary complexity theory: we are interested in the
worst-case growth of the resources (time and space) required by an algorithm in terms of the sizes
of its arguments. Mathematically we look at the functions from input size to resource size and
classify them into “big-O” classes, abstracting from constant factors (which depend on the machine
thealgorithm runs on and which we cannot control) and initial (algorithm startup) factors.
Definition 4.1.4. The following sets are often used for S in T (α):
Landau set class name rank Landau set class name rank
O(1) constant 1 O(n2 ) quadratic 4
O(log2 (n)) logarithmic 2 O(nk ) polynomial 5
O(n) linear 3 O(kn ) exponential 6
where O(g) = {f | ∃k > 0.f ≤a k · g} and f ≤a g (f is asymptotically bounded by g), iff there
is an n0 ∈ N, such that f (n) ≤ g(n) for all n > n0 .
For AI-2: I expect that given an algorithm, you can determine its complexity class. (next)
: 66 2025-05-14
Practical Advantage: Computing with Landau sets is quite simple. (good simplification)
Theorem 4.1.6 (Computing with Landau Sets).
: 67 2025-05-14
OK, that was the theory, . . . but how do we use that in practice?
What I mean by this is that given an algorithm, we have to determine the time complexity.
This is by no means a trivial enterprise, but we can do it by analyzing the algorithm instruction
by instruction as shown below.
: 68 2025-05-14
As instructions in imperative programs can introduce new variables, which have their own time
complexity, we have to carry them around via the introduced context, which has to be defined
co-recursively with the time complexity. This makes Definition 4.1.7 rather complex. The main
two cases to note here are
• the variable case, which “uses” the context Γ and
• the assignment case, which extends the introduced context by the time complexity of the value.
The other cases just pass around the given context and the introduced context systematically.
Let us now put one motivation for knowing about complexity theory into the perspective of the
job market; here the job as a scientist.
Please excuse the chemistry pictures, public imagery for CS is really just quite boring, this is
what people think of when they say “scientist”. So, imagine that instead of a chemist in a lab, it’s
me sitting in front of a computer.
But my 2nd attempt didn’t work either, which got me a bit agitated.
Ta-da . . . when, for once, I turned around and looked in the other direction– CAN one
actually solve this efficiently? – NP-hard was there to rescue me.
: 69 2025-05-14
The meat of the story is that there is no profit in trying to invent an algorithm, which we could
have known that cannot exist. Here is another image that may be familiar to you.
Example 4.1.9. Trying to find a sea route east to India (from Spain) (does not exist)
Observation: Complexity theory saves you from spending lots of time trying to invent
algorithms that do not exist.
4.2. RECAP: FORMAL LANGUAGES AND GRAMMARS 57
: 70 2025-05-14
It’s like, you’re trying to find a route to India (from Spain), and you presume it’s somewhere to
the east, and then you hit a coast, but no; try again, but no; try again, but no; ... if you don’t
have a map, that’s the best you can do. But the concept “NP-hard” gives you the map: you can
check that there actually is no way through here. But what is this notion “NP-hard”
alluded to above? We observe that we can analyze the complexity of problems by the complexity
of the algorithms that solve them. This gives us a notion of what to expect from solutions to
a given problem class, and thus whether efficient (i.e. polynomial time) algorithms can exist at
all.
: 71 2025-05-14
: 72 2025-05-14
: 73 2025-05-14
We have multiple notations for concatenation, since it is such a basic operation, which is used
so often that we will need very short notations for it, trusting that the reader can disambiguate
based on the context.
Now that we have defined the concept of a string as a sequence of characters, we can go on to
give ourselves a way to distinguish between good strings (e.g. programs in a given programming
language) and bad strings (e.g. such with syntax errors). The way to do this by the concept of a
formal language, which we are about to define.
Formal Languages
S
Definition 4.2.7. Let A be an alphabet, then we define the sets A+ := i∈N+ Ai of nonempty
string and A∗ :=A+ ∪ {ϵ} of strings.
Example 4.2.8. If A = {a, b, c}, then A∗ = {ϵ, a, b, c, aa, ab, ac, ba, . . . , aaa, . . . }.
Example 4.2.12. The set M := {ba[n] | n ∈ N} of strings that start with character b
followed by an arbitrary numbers of a’s is a formal language over A = {a, b}.
Definition 4.2.13. Let L1 , L2 , L ⊆ Σ∗ be formal languages over Σ.
Intersection and union: L1 ∩ L2 , L1 ∪ L2 .
4.2. RECAP: FORMAL LANGUAGES AND GRAMMARS 59
: 74 2025-05-14
There is a common misconception that a formal language is something that is difficult to under-
stand as a concept. This is not true, the only thing a formal language does is separate the “good”
from the bad strings. Thus we simply model a formal language as a set of stings: the “good”
strings are members, and the “bad” ones are not.
Of course this definition only shifts complexity to the way we construct specific formal languages
(where it actually belongs), and we have learned two (simple) ways of constructing them: by
repetition of characters, and by concatenation of existing languages. As mentioned above,
the purpose of a formal language is to distinguish “good” from “bad” strings. It is maximally
general, but not helpful, since it does not support computation and inference. In practice we
will be interested in formal languages that have some structure, so that we can represent formal
languages in a finite manner (recall that a formal language is a subset of A∗ , which may be infinite
and even undecidable – even though the alphabet A is finite).
To remedy this, we will now introduce phrase structure grammars (or just grammars), the
standard tool for describing structured formal languages.
The sets N and Σ are assumed to be disjoint. Any word w ∈ Σ∗ is called a terminal word.
Intuition: Production rules map strings with at least one nonterminal to arbitrary other
strings.
Notation: If we have n rules h → bi sharing a head, we often write h → b1 | . . . | bn instead.
: 75 2025-05-14
We fortify our intuition about these – admittedly very abstract – constructions by an example
60CHAPTER 4. RECAP OF PREREQUISITES FROM MATH & THEORETICAL COMPUTER SCIENCE
S → NP Vi
NP → Article N
Article → the | a | an
N → dog | teacher | . . .
Vi → sleeps | smells | . . .
: 76 2025-05-14
Now we look at just how a grammar helps in analyzing formal languages. The basic idea is that
a grammar accepts a word, iff the start symbol can be rewritten into it using only the rules of the
grammar.
Definition 4.2.21. The language L(G) of G is the set of its sentences. We say that L(G)
is generated by G.
Definition 4.2.22. We call two grammars equivalent, iff they have the same languages.
Definition 4.2.23. A grammar G is said to be universal if L(G) = Σ∗ .
Definition 4.2.24. Parsing, syntax analysis, or syntactic analysis is the process of analyzing
a string of symbols, either in a formal or a natural language by means of a grammar.
4.2. RECAP: FORMAL LANGUAGES AND GRAMMARS 61
: 77 2025-05-14
S →G NP Vi
→G Article N Vi
→G Article teacher Vi S → NP Vi
NP → Article N
Article → the | a | an | . . .
2. “The teacher sleeps” is a sentence. N → dog | teacher | . . .
S →∗G Article teacher Vi Vi → sleeps | smells | . . .
→G the teacher Vi
→G the teacher sleeps
: 78 2025-05-14
Note that this process indeed defines a formal language given a grammar, but does not provide
an efficient algorithm for parsing, even for the simpler kinds of grammars we introduce below.
1. context-sensitive (or type 1), if the bodies of production rules have no less symbols than
the heads,
2. context-free (or type 2), if the heads have exactly one symbol,
3. regular (or type 3), if additionally the bodies are empty or consist of a nonterminal, option-
ally followed by a terminal symbol.
S → abc|A
A → aAB c|abc
cB → Bc
bB → bb
62CHAPTER 4. RECAP OF PREREQUISITES FROM MATH & THEORETICAL COMPUTER SCIENCE
: 79 2025-05-14
While the presentation of grammars from above is sufficient in theory, in practice the various
grammar rules are difficult and inconvenient to write down. Therefore CS – where grammars
are important to e.g. specify parts of compilers – has developed extensions – notations that can
be expressed in terms of the original grammar rules – that make grammars more readable (and
writable) for humans. We introduce an important set now.
: 80 2025-05-14
We will now build on the notion of BNF grammar notations and introduce a way of writing
down the (short) grammars we need in AI-2 that gives us even more of an overview over what is
happening.
in AI-2: I will try to give “grammar overviews” that combine those, e.g. the grammar of
first-order logic.
4.3. MATHEMATICAL LANGUAGE RECAP 63
variables X ∈ V1
function constants f k ∈ Σfk
predicate constants pk ∈ Σp k
terms t ::= X variable
| f0 constant
| f k (t1 , . . ., tk ) application
formulae A ::= pk (t1 , . . ., tk ) atomic
| ¬A negation
| A1 ∧ A2 conjunction
| ∀X.A quantifier
: 81 2025-05-14
We will generally get by with context-free grammars, which have highly efficient into parsing
algorithms, for the formal language we use in this course, but we will not cover the algorithms in
AI-2.
Mathematical Structures
Observation: Mathematicians often cast classes of complex objects as mathematical struc-
tures.
We have just seen an example of a mathematical structure: (repeated here for convenience)
Definition 4.3.1. A phrase structure grammar (also called type 0 grammar, unrestricted
grammar, or just grammar) is a tuple ⟨N , Σ, P , S ⟩ where
Observation: Even though we call production rules “pairs” above, they are also mathematical
structures ⟨h, b⟩ with a funny notation h → b.
: 82 2025-05-14
Note that the idea of mathematical structures has been picked up by most programming
languages in various ways and you should therefore be quite familiar with it once you realize the
64CHAPTER 4. RECAP OF PREREQUISITES FROM MATH & THEORETICAL COMPUTER SCIENCE
parallelism.
: 83 2025-05-14
Even if the idea of mathematical structures may be familiar from programming, it may be quite
intimidating to some students in the mathematical notation we will use in this course. Therefore
will – when we get around to it – use a special overview notation in AI-2. We introduce it below.
Read the first line “N Set nonterminal symbols” in the structure above as “N is in an
(unspecified) set and is a nonterminal symbol”.
Here – and in the future – we will use Set for the class of sets ; “N is a set”.
I will try to give structure signatures where necessary.
4.3. MATHEMATICAL LANGUAGE RECAP 65
: 84 2025-05-14
66CHAPTER 4. RECAP OF PREREQUISITES FROM MATH & THEORETICAL COMPUTER SCIENCE
Chapter 5
In this chapter, we introduce a framework that gives a comprehensive conceptual model for the
multitude of methods and algorithms we cover in this course. The framework of rational agents
accommodates two traditions of AI.
Initially, the focus of AI research was on symbolic methods concentrating on the mental processes
of problem solving, starting from Newell/Simon’s “physical symbol hypothesis”:
A physical symbol system has the necessary and sufficient means for general intelligent action.
[NewSim:cseiss76]
Here a symbol is a representation an idea, object, or relationship that is physically manifested in
(the brain of) an intelligent agent (human or artificial).
Later – in the 1980s – the proponents of embodied AI posited that most features of cognition,
whether human or otherwise, are shaped – or at least critically influenced – by aspects of the
entire body of the organism. The aspects of the body include the motor system, the perceptual
system, bodily interactions with the environment (situatedness) and the assumptions about the
world that are built into the structure of the organism. They argue that symbols are not always
necessary since
The world is its own best model. It is always exactly up to date. It always has every detail
there is to be known. The trick is to sense it appropriately and often enough.[Brooks:edpc90]
The framework of rational agents initially introduced by Russell and Wefald in [Russell:dtrt91]
– accommodates both, it situates agents with percepts and actions in an environment, but does
not preclude physical symbol systems – i.e. systems that manipulate symbols as agent functions.
Russell and Norvig make it the central metaphor of their book “Artificial Intelligence – A modern
approach” [RusNor:AIMA03], which we follow in this course.
67
68 CHAPTER 5. RATIONAL AGENTS: AN AI FRAMEWORK
Humanly Rational
Thinking “The exciting new effort “The formalization of men-
to make computers think tal faculties in terms of
. . . machines with human-like computational models”
minds” [Haugeland:aitvi85] [ChaMcD:itai85]
Acting “The art of creating machines “The branch of CS concerned
that perform actions requiring with the automation of appro-
intelligence when performed by priate behavior in complex situ-
people” [Kurzweil:taoim90] ations” [LugStu:aisscps93]
: 85 2025-05-14
: 86 2025-05-14
We now discuss all of the four facets in a bit more detail, as they all either contribute directly
to our discussion of AI methods or characterize neighboring disciplines.
Definition 5.1.1. The Turing test is an operational test for intelligent behavior based on an
imitation game over teletext (arbitrary topic)
It was predicted that by 2000, a machine might have a 30% chance of fooling a lay person
for 5 minutes.
Note: In [Turing:cmi50], Alan Turing
anticipated all major arguments against AI in following 50 years and
suggested major components of AI: knowledge, reasoning, language understanding, learn-
ing
Problem: Turing test is not reproducible, constructive, or amenable to mathematical anal-
ysis!
: 87 2025-05-14
Definition 5.1.2. Cognitive science is the interdisciplinary, scientific study of the mind and
its processes. It examines the nature, the tasks, and the functions of cognition.
Definition 5.1.3. Cognitive neuroscience studies the biological processes and aspects that
underlie cognition, with a specific focus on the neural connections in the brain which are
involved in mental processes.
: 88 2025-05-14
70 CHAPTER 5. RATIONAL AGENTS: AN AI FRAMEWORK
: 89 2025-05-14
Acting Rationally
Idea: Rational behavior =
b doing the right thing!
Definition 5.1.4. Rational behavior consists of always doing what is expected to maximize
goal achievement given the available information.
Rational behavior does not necessarily involve thinking e.g., blinking reflex — but thinking
should be in the service of rational action.
Aristotle: Every art and every inquiry, and similarly every action and pursuit, is thought to
aim at some good. (Nicomachean Ethics)
: 90 2025-05-14
: 91 2025-05-14
: 92 2025-05-14
One possible objection to this is that the agent and the environment are conceptualized as separate
entities; in particular, that the image suggests that the agent itself is not part of the environment.
Indeed that is intended, since it makes thinking about agents and environments easier and is of
little consequence in practice. In particular, the offending separation is relatively easily fixed if
needed.
Let us now try to express the agent/environment ideas introduced above in mathematical language
to add the precision we need to start the process towards the implementation of rational agents.
We assume that agents can always perceive their own actions. (but not necessarily their
consequences)
72 CHAPTER 5. RATIONAL AGENTS: AN AI FRAMEWORK
Problem: Agent functions can become very big and may be uncomputable. (theoretical
tool only)
Definition 5.2.6. An agent function can be implemented by an agent program that runns
on a (physical or hypothetical) agent architecture.
: 93 2025-05-14
Here we already see a problem that will recur often in this course: The mathematical formulation
gives us an abstract specification of what we want (here the agent function), but not directly a
way of how to obtain it. Here, the solution is to choose a computational model for agents (an
agent architecture) and see how the agent function can be implemented in a agent program.
Agent Sensors
Percepts
? Environment
Actions
Actuators
Figure 2.1 Agents interact with environments through sensors and actuators.
Different agents differ on the contents of the white box in the center.
there is to say about the agent. Mathematically speaking, we say that an agent’s behavior is
described
AGENT FUNCTION
:
by the agent function that maps 94
any given percept sequence to an action. 2025-05-14
We can imagine tabulating the agent function that describes any given agent; for most
agents,
Let us fortify our this would
intuition be a all
about veryoflarge
thistable—infinite,
with an example, in fact, unless
whichwewe place
willa use
bound on the
often in the course
length of percept sequences we want to consider. Given an agent to experiment with, we can,
of the AI-2 course.
in principle, construct this table by trying out all possible percept sequences and recording
which actions the agent does in response.1 The table is, of course, an external characterization
Example: Vacuum-Cleaner World and Agent
of the agent. Internally, the agent function for an artificial agent will be implemented by an
AGENT PROGRAM agent program. It is important to keep these Percept two ideassequence
distinct. The agent function isAction an
abstract mathematical description; the agent program [A, Clean]is a concrete implementation, running
Right
within some physical system. [A, Dirty] Suck
To illustrate these ideas, we use a very simple
[B, Clean] example—the vacuum-cleaner world Lef t
shown in Figure 2.2. This world is so simple that [B,we can describe everything that happens;
Dirty] Suck
it’s also a made-up world, so we can invent many[A, variations.
Clean],This particular world has just Right
[A, Clean] two
locations: squares A and B. The vacuum agent[A, perceives
Clean],which square it is in and whether
[A, Dirty] Suck
there is dirt in the square. It can choose to move [A, Clean],
left, move[B,right,
Clean]
suck up the dirt, orLef do t
nothing. One very simple agent function is the [A, Clean],if[B,
following: the Dirty]
current square is dirty, thenSuck
percepts:
suck;otherwise, movelocation
to the otherand con-
square. [A, Dirty],
A partial tabulation[A,ofClean]
this agent function is shown Right
[A, Dirty], [A, Dirty] Suck
tents,
in Figure e.g.,
2.3 and an agent program that implements it appears in Figure 2.8 on page 48.
[A, Dirty] .. ..
Looking at Figure 2.3, we see that various. vacuum-world agents can be defined simply .
actions:
by filling in the right-hand
Lef t, column
Right,in Suck,
various ways. The obvious
[A, Clean], question,[A,
[A, Clean], then, is this: What
Clean] Right
is the Nright
oOpway to fill out the table? In other[A, words, what[A,
Clean], makes an agent
Clean], good or bad,
[A, Dirty] Suck
intelligent or stupid? We answer these questions. in the next section. ..
.. .
1 If the agent uses some randomization to choose its actions, then we would have to try each sequence many
times to identify the probability of each action. One might imagine that acting randomly is rather silly, but we
show later in this chapter that it can be very intelligent.
5.3. GOOD BEHAVIOR ; RATIONALITY 73
: 95 2025-05-14
The first implementation idea inspired by the table in last slide would just be table lookup algo-
rithm.
Table-Driven Agents
Idea: We can just implement the agent function as a lookup table and lookup actions.
: 96 2025-05-14
: 97 2025-05-14
Rationality
74 CHAPTER 5. RATIONAL AGENTS: AN AI FRAMEWORK
Idea: Try to design agents that are successful! (aka. “do the right thing”)
Problem: What do we mean by “successful”, how do we measure “success”?
Definition 5.3.1. A performance measure is a function that evaluates a sequence of envi-
ronments.
Example 5.3.2. A performance measure for a vacuum cleaner could
award one point per “square” cleaned up in time T ?
award one point per clean “square” per time step, minus one per move?
penalize for > k dirty squares?
Definition 5.3.3. An agent is called rational, if it chooses whichever action maximizes the
expected value of the performance measure given the percept sequence to date.
Critical Observation: We only need to maximize the expected value, not the actual value
of the performance measure!
: 98 2025-05-14
Let us see how the observation that we only need to maximize the expected value, not the actual
value of the performance measure affects the consequences.
Definition 5.3.4. An agent is called autonomous, if it does not rely on the prior knowledge
about the environment of the designer.
Autonomy avoids fixed behaviors that can become unsuccessful in a changing environment.
(anything else would be irrational)
The agent may have to learn all relevant traits, invariants, properties of the environment and
actions.
: 99 2025-05-14
For the design of agent for a specific task – i.e. choose an agent architecture and design an
agent program, we have to take into account the performance measure, the environment, and the
characteristics of the agent itself; in particular its actions and sensors.
5.3. GOOD BEHAVIOR ; RATIONALITY 75
: 100 2025-05-14
The PEAS criteria are essentially a laundry list of what an agent design task description should
include.
: 101 2025-05-14
Agents
Which are agents?
(D) Thermometer.
Answer: reserved for the plenary sessions ; be there!
: 102 2025-05-14
Environment types
Observation 5.4.1. Agent design is largely determined by the type of environment it is
intended for.
Problem: There is a vast number of possible kinds of environments in AI.
Solution: Classify along a few “dimensions”. (independent characteristics)
Definition 5.4.2. For an agent a we classify the environment e of a by its type, which is
one of the following. We call e
1. fully observable, iff the a’s sensors give it access to the complete state of the environment
at any point in time, else partially observable.
2. deterministic, iff the next state of the environment is completely determined by the current
state and a’s action, else stochastic.
3. episodic, iff a’s experience is divided into atomic episodes, where it perceives and then
performs a single action. Crucially, the next episode does not depend on previous ones.
Non-episodic environments are called sequential.
4. dynamic, iff the environment can change without an action performed by a, else static. If
the environment does not change but a’s performance measure does, we call e semidynamic.
5. discrete, iff the sets of e’s state and a’s actions are countable, else continuous.
6. single-agent, iff only a acts on e; else multi-agent (when must we count parts of e as
agents?)
: 103 2025-05-14
Note: Take the example above with a grain of salt. There are often multiple interpretations
that yield different classifications and different agents. (agent designer’s choice)
Example 5.4.4. Seen as a multi-agent game, chess is deterministic, as a single-agent game,
it is stochastic.
Observation 5.4.5. The real world is (of course) a partially observable, stochastic, sequen-
tial, dynamic, continuous, and multi-agent environment. (worst case for
AI)
Preview: We will concentrate on the “easy” environment types (fully observable, determin-
istic, episodic, static, and single-agent) in AI-1 and extend them to “realworld”-compatible
ones in AI-2.
: 104 2025-05-14
In the AI-2 course we will work our way from the simpler environment types to the more general
ones. Each environment type wil need its own agent types specialized to surviving and doing well
in them.
Agent Types
Observation: So far we have described (and analyzed) agents only by their behavior (cf.
agent function f : P ∗ → A).
Problem: This does not help us to build agents. (the goal of AI)
To build an agent, we need to fix an agent architecture and come up with an agent program
that runs on it.
Preview: Four basic types of agent architectures in order of increasing generality:
1. reflex agents
2. model-based agents
3. goal-based agents
4. utility-based agents
: 105 2025-05-14
Reflex Agents
Definition 5.5.1. An agent ⟨P , A, f ⟩ is called a reflex agent, iff it only takes the last percept
into account when choosing an action, i .e. f (p1 , . . ., pk ) = f (pk ) for all p1 , . . ., pk ∈ P.
Section
Agent 2.4. The Structure of Agents
Schema: 49
Agent Sensors
Environment
Condition-action rules What action I
should do now
Actuators
Figure 2.10 A simple reflex agent. It acts according to a rule whose condition matches
Reflex Agents (continued)
the current state, as defined by the percept.
General trivial;
Agentit gets
Program:
more interesting shortly.) We use rectangles to denote the current internal state
function of
Simple−Reflex−Agent
the agent’s decision process, and ovalsreturns
(percept) anthe
to represent action
background information used in
persistent: /∗ aagent
rules The
the process. set program,
of condition−action rules∗/
which is also very simple, is shown in Figure 2.10. The
I NTERPRET-I NPUT function generates an abstracted description of the current state from the
state :=percept,
Interpret−Input(percept)
and the RULE -M ATCH function returns the first rule in the set of rules that matches
rule :=the
Rule−Match(state,rules)
given state description. Note that the description in terms of “rules” and “matching” is
action := Rule−action[rule]
purely conceptual; actual implementations can be as simple as a collection of logic gates
return action
implementing a Boolean circuit.
Simple reflex agents have the admirable property of being simple, but they turn out to be
Problem:of limited
Reflexintelligence.
agents can The only
agent react to2.10
in Figure thewill
perceived
work onlystate of thedecision
if the correct environment,
can be not to
changes. made on the basis of only the current percept—that is, only if the environment is fully observ-
able. Even a little bit of unobservability can cause serious trouble. For example, the braking
Examplerule
5.5.3. Automobile
given earlier assumes tail lights
that the signalcar-in-front-is-braking
condition braking by brightening. A reflexfrom
can be determined agent would
the currentsubsequent
have to compare percept—a single frame to
percepts of video.
[Link] works if the car in front has a centrally
mounted brake light. Unfortunately, older models have different configurations of taillights,
Problem: Partially observable environments get reflex agents into trouble.
Example 5.5.4. Vacuum cleaner robot with defective location sensor ; infinite loops.
: 107 2025-05-14
5.5. TYPES OF AGENTS 79
Sensors
State
How the world evolves What the world
is like now
Environment
What my actions do
Agent Actuators
Problem: Having a world model does not always determine what to do (rationally).
Example 5.5.8. Coming to an intersection, where the agent has to decide between going
left and right.
: 110 2025-05-14
Goal-based Agents
Problem: A world model does not always determine what to do (rationally).
Observation: Having a goal in mind does! (determines future actions)
52 Chapter 2. Intelligent Agents
Agent Schema:
Sensors
State
What the world
How the world evolves is like now
Environment
What action I
Goals should do now
Agent Actuators
Figure 2.13 A model-based, goal-based agent. It keeps track of the world state as well as
a set : of goals it is trying to achieve, and111
chooses an action that will (eventually) lead to the
2025-05-14
achievement of its goals.
Goal-based agents
example, the taxi may(continued)
be driving back home, and it may have a rule telling it to fill up with
gas on the way home unless it has at least half a tank. Although “driving back home” may
Definition
seem to an 5.5.9. A goal-based
aspect of agent
the world state, theisfact
a model-based
of the taxi’s agent with is
destination transition
actually model T that
an aspect of
deliberates actions based on goals and a world model: It employs
the agent’s internal state. If you find this puzzling, consider that the taxi could be in exactly
the same place at the same time, but intending to reach a different destination.′
a set G of goals and a action function f that given a (new) state s selects an action a
to best reach G.
2.4.4 Goal-based agents
The agent function is then s 7→ f (T (s), G).
Knowing something about the current state of the environment is not always enough to decide
what to do. For example, at a road junction, the taxi can turn left, turn right, or go straight
on. The correct decision depends on where the taxi is trying to get to. In other words, as well
GOAL as a current state description, the agent needs some sort of goal information that describes
situations that are desirable—for example, being at the passenger’s destination. The agent
5.5. TYPES OF AGENTS 81
: 112 2025-05-14
Utility-based Agents
Definition 5.5.11. A utility-based agent uses a world model along with a utility function
that models its preferences among the states of that world. It chooses the action that leads
to the best expected utility.
54 Chapter 2. Intelligent Agents
Agent Schema:
Sensors
State
What the world
How the world evolves is like now
Environment
What it will be like
What my actions do if I do action A
What action I
should do now
Agent Actuators
Figure 2.14 A model-based, utility-based agent. It uses a model of the world, along with
a utility
:
function that measures its preferences
113
among states of the world. Then it chooses the
2025-05-14
action that leads to the best expected utility, where expected utility is computed by averaging
over all possible outcome states, weighted by the probability of the outcome.
Utility-based vs. Goal-based Agents
outcome. (Appendix A defines expectation more precisely.) In Chapter 16, we show that any
Question: What
rational agent mustis behave
the difference between goal-based
as if it possesses and utility-based
a utility function agents?
whose expected value it tries
to maximize. An agent that possesses an explicit utility function can make rational decisions
Utility-based Agents are a Generalization: We can always force goal-directedness by a
with a general-purpose algorithm that does not depend on the specific utility function being
utility function that only rewards goal states.
maximized. In this way, the “global” definition of rationality—designating as rational those
agent functions
Goal-based that have
Agents the less:
can do highestA performance—is turned rational
utility function allows into a “local”
decisions constraint on
where mere
rational-agent
goals designs that can be expressed in a simple program.
are inadequate:
The utility-based agent structure appears in Figure 2.14. Utility-based agent programs
conflicting goals (utility gives tradeoff to make rational decisions)
appear in Part IV, where we design decision-making agents that must handle the uncertainty
goals obtainable
inherent
in stochasticbyoruncertain
partially actions
observable environments. (utility × likelihood helps)
At this point, the reader may be wondering, “Is it that simple? We just build agents that
maximize expected utility, and we’re done?” It’s true that such agents would be intelligent,
: 114 2025-05-14
but it’s not simple. A utility-based agent has to model and keep track of its environment,
tasks that have involved a great deal of research on perception, representation, reasoning,
Learning Agents
and learning. The results of this research fill many of the chapters of this book. Choosing
the utility-maximizing course of action is also a difficult task, requiring ingenious algorithms
that fill several more chapters. Even with these algorithms, perfect rationality is usually
unachievable in practice because of computational complexity, as we noted in Chapter 1.
Definition 5.5.12. A learning agent is an agent that augments the performance element –
which determines actions from percept sequences with
a learning element which makes improvements to the agent’s components,
a critic which gives feedback to the learning element based on an external performance
standard,
a problem generator which suggests actions that lead to new and informative experiences.
The performance element is what we took for the whole agent above.
: 115 2025-05-14
Learning Agents
ction 2.4. The Structure of Agents 55
Agent Schema:
Performance standard
Critic Sensors
feedback
Environment
changes
Learning Performance
element element
knowledge
learning
goals
Problem
generator
Actuators
Agent
Learning
He estimates howAgents:
much work Example
this might take and concludes “Some more expeditious method
seems desirable.” The method he proposes is to build learning machines and then to teach
Example 5.5.13 (Learning Taxi Agent). It has the components
them. In many areas of AI, this is now the preferred method for creating state-of-the-art
Performance element: the knowledge and procedures for selecting driving actions. (this
systems. Learning has another advantage, as we noted earlier: it allows the agent to operate
controls the actual driving)
in initially unknown environments and to become more competent than its initial knowledge
critic: observes the world and informs the learning element (e.g. when passengers
alone might complain
allow. brutal
In this section, we briefly introduce the main ideas of learning agents.
braking)
Throughout the book,
Learning we comment
element modifies the on opportunities
braking and methods
rules in the performance for learning
element in particular
(e.g. earlier,
kinds of agents. Part V goes into much more depth on the learning algorithms themselves.
softer)
A learning agent can be divided into four conceptual components, as shown in Fig-
RNING ELEMENT ure 2.15. The most important distinction is between the learning element, which is re-
FORMANCE
MENT sponsible for making improvements, and the performance element, which is responsible for
5.6. REPRESENTING THE ENVIRONMENT IN AGENTS 83
: 117 2025-05-14
vs.
Solver specific to a particular prob- vs. Solver based on description in a
lem (“domain”). general problem-description language
(e.g., the rules of any board game).
More efficient. vs. Much less design/maintenance work.
: 118 2025-05-14
Next natural question: How do these work? (see the rest of the course)
84 CHAPTER 5. RATIONAL AGENTS: AN AI FRAMEWORK
Also The additional internal structure will make the algorithms more complex.
: 119 2025-05-14
B C
B C
Example 5.6.2. Consider the problem of finding a driving route from one end of a country
to the other via some sequence of cities.
: 120 2025-05-14
Note: The set of states in atomic representations and attributes in factored ones is determined
at design time, while the objects and their relationships in structured ones are discovered at
“runtime”.
Here – as always when we evaluate representations – the crucial aspect to look out for are the
idendity conditions: when do we consider two representations equal, and when can we (or more
crucially algorithms) distinguish them.
For instance for factored representations, make world representations equal, iff the values of
the attributes – that are determined at agent design time and thus immutable by the agent –
5.7. RATIONAL AGENTS: SUMMARY 85
are all equal. So the agent designer has to make sure to add all the attributes to the chosen
representation that are necessary to distinguish environments that the agent program needs to
treat differently.
It is tempting to think that the situation with atomic representations is easier, since we can
“simply” add enough states for the necesssary distictions, but in practice this set of states may
have to be infinite, while in factored or structured representations we can keep representations
finite.
Summary
Agents interact with environments through actuators and sensors.
The agent function describes what the agent does in all circumstances.
The performance measure evaluates the environment sequence.
A perfectly rational agent maximizes expected performance.
: 121 2025-05-14
Consequence: The rational agents paradigm used in this course challenges you to become
a good agent designer.
86 CHAPTER 5. RATIONAL AGENTS: AN AI FRAMEWORK
: 122 2025-05-14
Part II
87
89
This part introduces search-based methods for general problem solving using atomic and
factored representations of states.
Concretely, we discuss the basic techniques of search-based symbolic AI. First in the shape of
classical and heuristic search and adversarial search paradigms. Then in constraint propagation,
where we see the first instances of inference-based methods.
90
Chapter 6
In this chapter, we will look at a class of algorithms called search algorithms. These are
algorithms that help in quite general situations, where there is a precisely described problem, that
needs to be solved. Hence the name “General Problem Solving” for the area.
91
92 CHAPTER 6. PROBLEM SOLVING AND SEARCH
Definition 6.1.1. In offline problem solving an agent computing an action sequence based
complete knowledge of the environment.
Remark 6.1.2. Offline problem solving only works in fully observable, deterministic, static,
and episodic environments.
Definition 6.1.3. In online problem solving an agent computes one action at a time based
on incoming perceptions.
This Semester: We largely restrict ourselves to offline problem solving. (easier)
: 123 2025-05-14
We will use the following problem as a running example. It is simple enough to fit on one slide
and complex enough to show the relevant features of the problem solving algorithms we want to
talk about.
Oradea
71
Neamt
Zerind 87
75 151
Iasi
Arad
140
92
Sibiu Fagaras
99
118
Vaslui
80
Rimnicu Vilcea
Timisoara
142
111 Pitesti 211
Lugoj 97
70 98
85 Hirsova
Mehadia 146 101 Urziceni
75 138 86
Bucharest
Drobeta 120
90
Craiova Eforie
Giurgiu
agent chooses a cost function that reflects its own performance measure. For the agent
trying to get to Bucharest, time is of the essence, so the cost of a path might be its length
Solution: Appropriate sequence
in kilometers. In this of cities,
chapter, e.g.:thatArad,
we assume Sibiu,
the cost of Fagaras,
a path can be describedBucharest
as the
STEP COST sum of the costs of the individual actions along the path.3 The step cost of taking action
! !
a in state s to reach state s is denoted by c(s, a, s ). The step costs for Romania are
shown in Figure 3.2 as route distances. We assume that step costs are nonnegative.4
: 124 2025-05-14
The preceding elements define a problem and can be gathered into a single data structure
that is given as input to a problem-solving algorithm. A solution to a problem is an action
Given this example to sequence fortifythatourleadsintuitions, wetocan
from the initial state a goal now turn quality
state. Solution to the formal
is measured definition
by the of problem
path cost function, and an optimal solution has the lowest path cost among all solutions.
formulation and their solutions.
OPTIMAL SOLUTION
it also limits the objectives by specifying goal states. (excludes, e.g. to stay another
couple of weeks.)
A solution is a sequence of actions that leads from the initial state to a goal state.
Problem solving computes solutions from problem formulations.
Finding the right level of abstraction and the required (not more!) information is often the
key to success.
: 125 2025-05-14
Definition 6.1.7. The graph ⟨S, TA ⟩ is called the state space induced by Π.
Definition 6.1.8. A solution for Π consists of a sequence a1 , . . ., an of actions such that for
all 1 < i ≤ n
ai is applicable to state si−1 , where s0 ∈ I and
si ∈ Tai (si−1 ), and sn ∈ G.
Idea: A solution bring us from I to a goal state via applicable actions.
Definition 6.1.9. Often we add a cost function c : A → R+ 0 that associates a step cost c(a)
to an action a ∈ A. The cost of a solution is the sum of the step costs of its actions.
: 126 2025-05-14
Observation: The formulation of problems from ??? uses an atomic (black-box) state repre-
sentation. It has enough functionality to construct the state space but nothing else. We will come
back to this in slide ??.
Remark 6.1.10. Note that search problems formalize problem formulations by making many of
the implicit constraints explicit.
S Set states,
* +
A Set actions,
search problem = T A×S → P(S) transition model,
I S initial state,
G P(S) goal states
: 127 2025-05-14
We will now specialize ??? to deterministic, fully observable environments, i.e. environments
where actions only have one – assured – outcome state.
: 128 2025-05-14
Note that the definition of a search problem is very general, it applies to many many real-world
problems. So we will try to characterize these by difficulty.
Problem types
Definition 6.2.1. A search problem is called a single state problem, iff it is
fully observable (at least the initial state)
deterministic (unique successor states)
static (states do not change other than by our own actions)
discrete (a countable number of states)
Definition 6.2.2. A search problem is called a multi state problem
states partially observable (e.g. multiple initial states)
deterministic, static, discrete
: 129 2025-05-14
We will explain these problem types with another example. The problem P is very simple: We
have a vacuum cleaner and two rooms. The vacuum cleaner is in one room at a time. The floor
can be dirty or clean.
The possible states are determined by the position of the vacuum cleaner and the information,
whether each room is dirty or not. Obviously, there are eight states: S = {1, 2, 3, 4, 5, 6, 7, 8} for
simplicity.
The goal is to have both rooms clean, the vacuum cleaner can be anywhere. So the set G of
goal states is {7, 8}. In the single-state version of the problem, [right, suck] shortest solution, but
[suck, right, suck] is also one. In the multiple-state version we have
L
S S
Start in 5 L
R
R L
R
R
L L
S S
Figure 3.3 The state space for the vacuum world. Links denote actions: L = Left, R =
Multiple-state Problem: Right, S = Suck.
Contingency Problem:
96 CHAPTER 6. PROBLEM SOLVING AND SEARCH
cation only
L
S S
R R
L R L R
S
R
Solution:
L R
suck → {5, 7} S S
Figure 3.3 The state space for the vacuum world. Links denote actions: L = Left, R =
right → {6, 8} Right, S = Suck.
eight numbered tiles and a blank space. A tile adjacent to the blank space can slide into the
space. The object is to reach a specified goal state, such as the one shown on the right of the
figure. The standard formulation is as follows:
etc. Of course, local sensing can help: narrow {6, 8} to {6} or {8}, if we are in the first, then
suck.
: 132 2025-05-14
“Path cost”: There may be more than one solution and we might want to have the “best” one in
a certain sense.
: 133 2025-05-14
“State”: e.g., we don’t care about tourist attractions found in the cities along the way. But this is
problem dependent. In a different problem it may well be appropriate to include such information
in the notion of state.
“Realizability”: one could also say that the abstraction must be sound wrt. reality.
Example: Example
The Problems
Section 3.2. 8-puzzle 71
7 2 4 1 2
5 6 3 4 5
8 3 1 6 7 8
Before closing this section, we should emphasize that the notion of an agent is meant to
be a tool for analyzing systems, not an absolute characterization that divides the world into
agents and non-agents. One could view a hand-held calculator as an agent that chooses the
98 CHAPTER 6. PROBLEM SOLVING AND SEARCH
States? Actions?. . .
States real-valued coordinates of
robot joint angles and parts of the object to be assembled
Actions continuous motions of robot joints
Goal test assembly complete?
Path cost time to execute
: 136 2025-05-14
General Problems
Question: Which are “Problems”?
(A) You didn’t understand any of the lecture.
(B) Your bus today will probably be late.
(C) Your vacuum cleaner wants to clean your apartment.
(D) You want to win a chess game.
Answer: reserved for the plenary sessions ; be there!
: 137 2025-05-14
6.3 Search
Tree Search Algorithms
Note: The state space of a search problem ⟨S , A, T , I , G ⟩ is a graph ⟨S, TA ⟩.
As graphs are difficult to compute with, we often compute a corresponding tree and work on
that. (standard trick in graph algorithms)
Definition 6.3.1. Given a search problem P := ⟨S , A, T , I , G ⟩, the tree search algorithm
consists of the simulated exploration of state space ⟨S, TA ⟩ in a search tree formed by succes-
sively expanding already explored states. (offline
algorithm)
procedure Tree−Search (problem, strategy) : <a solution or failure>
<initialize the search tree using the initial state of problem>
6.3. SEARCH 99
loop
if <there are no candidates for expansion> <return failure> end if
<choose a leaf node for expansion according to strategy>
if <the node contains a goal state> return <the corresponding solution>
else <expand the node and add the resulting nodes to the search tree>
end if
end loop
end procedure
: 138 2025-05-14
Arad
Arad
Arad
Arad
: 139 2025-05-14
Let us now think a bit more about the implementation of tree search algorithms based on the
ideas discussed above. The abstract, mathematical notions of a search problem and the induced
tree search algorithm gets further refined here.
Figure 3.10 Nodes are the data structures from which the search tree is constructed. Each
has a parent, a state, and various bookkeeping fields. Arrows point from child to parent.
Observation: A set of search tree nodes that can all (recursively) reach a single initial node
form a search tree. (they implement it)
Given the components for a parent node, it is easy to see how to compute the necessary
components for a child node. The function C HILD -N ODE takes a parent node and an action
and returns the resulting child node:
Observation: Paths in the search tree correspond to paths in the state space.
function C HILD -N ODE( problem, parent , action) returns a node
return a node with
Definition 6.3.3. We define the path cost of a node n Sin a= problem.R
search tree T to
([Link] be), the sum of
, action ESULT TATE
P = parent , A = action,
ARENT CTION
the step costs on the path from n to the root of T . P -C = parent .P -C + problem.S
ATH OST -C (parent.S
ATH , action )
OST TEP OST TATE
Observation: As a search tree node has access tostringparents, we can read off the solution
The node data structure is depicted in Figure 3.10. Notice how the PARENT pointers
the nodes together into a tree structure. These pointers also allow the solution path to be
from a goal node. extracted when a goal node is found; we use the S OLUTION function to return the sequence
of actions obtained by following parent pointers back to the root.
Up to now, we have not been very careful to distinguish between nodes and states, but in
writing detailed algorithms it’s important to make that distinction. A node is a bookkeeping
data structure used to represent the search tree. A state corresponds to a configuration of the
: 140 world. Thus, nodes are on particular paths,2025-05-14
as defined by PARENT pointers, whereas states
are not. Furthermore, two different nodes can contain the same world state if that state is
generated via two different search paths.
Now that we have nodes, we need somewhere to put them. The frontier needs to be
It is very important to understand the fundamental difference between a state in a search problem,
stored in such a way that the search algorithm can easily choose the next node to expand
according to its preferred strategy. The appropriate data structure for this is a queue. The
a node search tree employed by the tree search algorithm, and the implementation in a search tree
QUEUE
node. The implementation above is faithful in the sense ••that the implemented data structures
E MPTY ?(queue) returns true only if there are no more elements in the queue.
P OP(queue) removes the first element of the queue and returns it.
contain all the information needed in the tree search algorithm.
• I NSERT (element, queue) inserts an element and returns the resulting queue.
So we can use it to refine the idea of a tree search algorithm into an implementation.
The fringe is the set of search tree nodes not yet expanded in tree search.
Idea: We treat the fringe as an abstract data type with three accessors: the
binary function first retrieves an element from the fringe according to a strategy.
binary function insert adds a (set of) search tree node into a fringe.
unary predicate empty to determine whether a fringe is the empty set.
The strategy determines the behavior of the fringe (data structure) (see below)
: 141 2025-05-14
6.4. UNINFORMED SEARCH STRATEGIES 101
Note: The pseudocode in Definition 6.3.4 is still relatively underspecified – leaves many imple-
mentation details unspecified. Here are the specifications of the functions used without.
• make_node constructs a search tree node from a state.
• initial_state accesses the initial state of a search problem.
• State returns the state associated with its aregument.
• GoalNode checks whether its argument is a goal node
• expand = creates new search tree nodes by for all successor states.
Essentially, only the first function is non-trivial (as the strategy argument shows) In fact it is the
only place, where the strategy is used in the algorithm.
An alternative implementation would have been to make the fringe a queue, and insert order
the fringe as the strategy sees fit. Then first can just return the first element of the queue. This
would have lead to a different signature, possibly different runtimes, but the same overall result
of the algorithm.
Search strategies
Definition 6.3.5. A strategy is a function that picks a node from the fringe of a search tree.
(equivalently, orders the fringe and picks the first.)
Definition 6.3.6 (Important Properties of Strategies).
: 142 2025-05-14
Note that there can be infinite branches, see the search tree for Romania.
: 143 2025-05-14
The opposite of uninformed search is informed or heuristic search that uses a heuristic function
that adds external guidance to the search process. In the Romania example, one could add the
heuristic to prefer cities that lie in the general direction of the goal (here SE).
Even though heuristic search is usually much more efficient, uninformed search is important
nonetheless, because many problems do not allow to extract good heuristics.
Breadth-First Search
Idea: Expand the shallowest unexpanded node.
Definition 6.4.2. The breadth first search (BFS) strategy treats the fringe as a FIFO queue,
i.e. successors go in at the end of the fringe.
Example 6.4.3 (Synthetic).
B C
D E F G
H I J K L M N O
B C
D E F G
H I J K L M N O
6.4. UNINFORMED SEARCH STRATEGIES 103
B C
D E F G
H I J K L M N O
B C
D E F G
H I J K L M N O
B C
D E F G
H I J K L M N O
B C
D E F G
H I J K L M N O
: 144 2025-05-14
We will now apply the breadth first search strategy to our running example: Traveling in Romania.
Note that we leave out the green dashed nodes that allow us a preview over what the search tree
will look like (if expanded). This gives a much cleaner picture we assume that the readers already
have grasped the mechanism sufficiently.
Arad
104 CHAPTER 6. PROBLEM SOLVING AND SEARCH
Arad
Arad
Arad
Arad
: 145 2025-05-14
Disadvantage: Space is the big problem (can easily generate nodes at 500MB/sec =
b
1.8TB/h)
Optimal?: No! If cost varies for different steps, there might be better solutions below the
level of the first one.
An alternative is to generate all solutions and then pick an optimal one. This works only, if
m is finite.
: 146 2025-05-14
The next idea is to let cost drive the search. For this, we will need a non-trivial cost function: we
will take the distance between cities, since this is very natural. Alternatives would be the driving
time, train ticket cost, or the number of tourist attractions along the way.
Of course we need to update our problem formulation with the necessary information.
6.4. UNINFORMED SEARCH STRATEGIES 105
Oradea
71
Neamt
Zerind 87
75 151
Iasi
Arad
140
92
Sibiu Fagaras
99
118
Vaslui
80
Rimnicu Vilcea
Timisoara
142
111 Pitesti 211
Lugoj 97
70 98
85 Hirsova
Mehadia 146 101 Urziceni
75 138 86
Bucharest
Drobeta 120
90
Craiova Eforie
Giurgiu
Sometimes the goal is specified by an abstract property rather than an explicitly enumer-
ated set of states. For example, in chess, the goal is to reach a state called “checkmate,”
Uniform-cost search
where the opponent’s king is under attack and can’t escape.
PATH COST • A path cost function that assigns a numeric cost to each path. The problem-solving
Idea: Expand agent least
chooses a cost
cost function thatnode.
unexpanded reflects its own performance measure. For the agent
trying to get to Bucharest, time is of the essence, so the cost of a path might be its length
Definitionin6.4.5.
kilometers. In this chapter,
Uniform-cost we assume
search (UCS)thatis the
thecost of a pathwhere
strategy can be the
described
fringeasistheordered by
STEP COST
increasing path the costs of the individual actions along the path.3 The step cost of taking action
sum ofcost.
a in state s to reach state s! is denoted by c(s, a, s! ). The step costs for Romania are
shown in Figure
Note: Equivalent 3.2 as route
to breadth firstdistances.
search We if allassume
step that stepare
costs costs are nonnegative.4
equal.
The preceding elements define a problem and can be gathered into a single data structure
Synthetic
that is Example:
given as input to a problem-solving algorithm. A solution to a problem is an action
sequence that leads from the initial state to a goal state. Solution quality is measured by the
OPTIMAL SOLUTION path cost function, and an optimal solution has the lowest path cost among all solutions.
Arad
Oradea Arad
106 CHAPTER 6. PROBLEM SOLVING AND SEARCH
Arad
140 118 75
Sibiu Timisoara Zerind
118 111 71 75
Arad
140 118 75
Sibiu Timisoara Zerind
140 99 151 80 118 111 71 75
: 148 2025-05-14
Note that we must sum the distances to each leaf. That is, we go back to the first level after the
third step.
: 149 2025-05-14
If step cost is negative, the same situation as in breadth first search can occur: later solutions
may be cheaper than the current one.
If step cost is 0, one can run into infinite branches. UCS then degenerates into depth first
search, the next kind of search algorithm we will encounter. Even if we have infinite branches,
where the sum of step costs converges, we can get into trouble, since the search is forced down
these infinite paths before a solution can be found.
Worst case is often worse than BFS, because large trees with small steps tend to be searched
first. If step costs are uniform, it degenerates to BFS.
Depth-first Search
Idea: Expand deepest unexpanded node.
Definition 6.4.6. Depth-first search (DFS) is the strategy where the fringe is organized as
a (LIFO) stack i.e. successors go in at front of the fringe.
Definition 6.4.7. Every node that is pushed to the stack is called a backtrack point. The
action of popping a non-goal node from the stack and continuing the search with the new
top element of the stack (a backtrack point by construction) is called backtracking, and
correspondingly the DFS algorithm backtracking search.
6.4. UNINFORMED SEARCH STRATEGIES 107
: 150 2025-05-14
Depth-First Search
Example 6.4.8 (Synthetic).
B C
D E F G
H I J K L M N O
B C
D E F G
H I J K L M N O
B C
D E F G
H I J K L M N O
B C
D E F G
H I J K L M N O
108 CHAPTER 6. PROBLEM SOLVING AND SEARCH
B C
D E F G
H I J K L M N O
B C
D E F G
H I J K L M N O
B C
D E F G
H I J K L M N O
B C
D E F G
H I J K L M N O
B C
D E F G
H I J K L M N O
6.4. UNINFORMED SEARCH STRATEGIES 109
B C
D E F G
H I J K L M N O
B C
D E F G
H I J K L M N O
B C
D E F G
H I J K L M N O
B C
D E F G
H I J K L M N O
B C
D E F G
H I J K L M N O
: 151 2025-05-14
110 CHAPTER 6. PROBLEM SOLVING AND SEARCH
Arad
Arad
Arad
Arad
: 152 2025-05-14
: 153 2025-05-14
6.4. UNINFORMED SEARCH STRATEGIES 111
: 154 2025-05-14
A A
A A A A
B C B C B C B C
A A A A
B C B C B C B C
D E F G D E F G D E F G D E F G
A A A A
B C B C B C B C
D E F G D E F G D E F G D E F G
112 CHAPTER 6. PROBLEM SOLVING AND SEARCH
: 155 2025-05-14
Completeness Yes
Time complexity (d+1)·b0 +d·b1 +(d−1)·b2 +. . .+bd ∈ O(bd+1 )
Space complexity O(b · d)
Optimality Yes (if step cost = 1)
Consequence: IDS used in practice for search spaces of large, infinite, or unknown depth.
: 156 2025-05-14
Note: To find a solution (at depth d) we have to search the whole tree up to d. Of course
since we do not save the search state, we have to re-compute the upper part of the tree for the
next level. This seems like a great waste of resources at first, however, IDS tries to be complete
without the space penalties.
However, the space complexity is as good as DFS, since we are using DFS along the way. Like
in BFS, the whole tree on level d (of optimal solution) is explored, so optimality is inherited from
there. Like BFS, one can modify this to incorporate uniform cost search behavior.
As a consequence, variants of IDS are the method of choice if we do not have additional
information.
Kohlhase:
Kohlhase:Künstliche
KünstlicheIntelligenz 1 1
Intelligenz 150150 JulyJuly
5, 2018
5, 2018
: 157 2025-05-14
: 158 2025-05-14
a search problem in search of a goal state. Search strategies only differ by the treatment of
the fringe.
Search Strategies and their Properties: We have discussed
: 159 2025-05-14
: 160 2025-05-14
Iterative deepening search uses only linear space and not much more time than other unin-
6.5. INFORMED SEARCH STRATEGIES 115
formed algorithms.
Next Step: Introduce additional knowledge about the problem (heuristic search)
Best-first-, A∗ -strategies (guide the search by heuristics)
Iterative improvement algorithms.
Definition 6.5.1. A search algorithm is called informed, iff it uses some form of external
information – that is not part of the search problem – to guide the search.
: 161 2025-05-14
Best-first search
Idea: Order the fringe by estimated “desirability” (Expand most desirable unexpanded
node)
Definition 6.5.2. An evaluation function assigns a desirability value to each node of the
search tree.
Note: A evaluation function is not part of the search problem, but must be added externally.
Definition 6.5.3. In best first search, the fringe is a queue sorted in decreasing order of
desirability.
Special cases: Greedy search, A∗ search
: 162 2025-05-14
This is like UCS, but with an evaluation function related to problem at hand replacing the path
cost function.
If the heuristic is arbitrary, we expect incompleteness!
Depends on how we measure “desirability”.
Concrete examples follow.
Greedy search
Idea: Expand the node that appears to be closest to the goal.
Definition 6.5.4. A heuristic is an evaluation function h on states that estimates the cost
from n to the nearest goal state. We speak of heuristic search if the search algorithm uses a
heuristic in some way.
Note: All nodes for the same state must have the same h-value!
Definition 6.5.5. Given a heuristic h, greedy search is the strategy where the fringe is
organized as a queue sorted by increasing h value.
Example 6.5.6. Straight-line distance from/to Bucharest.
Note: Unlike uniform cost search the node evaluation function has nothing to do with the
nodes expanded so far
116 CHAPTER 6. PROBLEM SOLVING AND SEARCH
: 163 2025-05-14
In greedy search we replace the objective cost to construct the current solution with a heuristic or
subjective measure from which we think it gives a good idea how far we are from a solution. Two
things have shifted:
• we went from internal (determined only by features inherent in the search space) to an external/heuris-
tic cost
• instead of measuring the cost to build the current partial solution, we estimate how far we are
from the desired goal
Oradea
71
Neamt
Zerind 87
75 151
Iasi
Arad
140
92
Sibiu Fagaras
99
118
Vaslui
80
Rimnicu Vilcea
Timisoara
142
111 Pitesti 211
Lugoj 97
70 98
85 Hirsova
Mehadia 146 101 Urziceni
75 138 86
Bucharest
Drobeta 120
90
Craiova Eforie
Giurgiu
: 164 2025-05-14
Sometimes the goal is specified by an abstract property rather than an explicitly enumer-
ated set of states. For example, in chess, the goal is to reach a state called “checkmate,”
where the opponent’s king is under attack and can’t escape.
Greedy Search: Romania
PATH COST • A path cost function that assigns a numeric cost to each path. The problem-solving
agent chooses a cost function that reflects its own performance measure. For the agent
trying to get to Bucharest, time is of the essence, so the cost of a path might be its length
in kilometers. In this chapter, we assume
Arad that the cost of a path can be described as the
STEP COST sum of the costs of the individual actions along the path.3 The step cost of taking action
366 by c(s, a, s! ). The step costs for Romania are
a in state s to reach state s! is denoted
shown in Figure 3.2 as route distances. We assume that step costs are nonnegative.4
The preceding elements define a problem and can be gathered into a single data structure
that is given as input to a problem-solving algorithm. A solution to a problem is an action
sequence that leads from the initial state to a goal state. Solution quality is measured by the
OPTIMAL SOLUTION path cost function, and an optimal solution has the lowest path cost among all solutions.
Arad
366
Sibiu Timisoara Zerind
253 329 374
Arad
366
Sibiu Timisoara Zerind
253 329 374
Arad Fagaras Oradea R. Vilcea
Arad
366
Sibiu Timisoara Zerind
253 329 374
Arad Fagaras Oradea R. Vilcea
Sibiu Bucharest
253 0
: 165 2025-05-14
Let us fortify our intuitions with another example: navigation in a simple maze. Here the states
are the cells in the grid underlying the maze and the actions navigating to one of the adjoining
cells. The initial and goal states are the left upper and right lower corners of the grid. To see the
influence of the chosen heuristic (indicated by the red number in the cell), we compare the search
induced goal distance function with a heuristic based on the Manhattan distance. Just follow the
greedy search by following the heuristic gradient.
Heuristic
Heuristic Functions
Functions in Path
in Path Planning
Planning
I Example
Example [Link] (The
(The mazemaze solved).
solved). We indicate h∗ by giving the goal distance:
We indicate h⇤ by giving the goal distance
I 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
1 24 18 17 16 15 14 12 13 14 15 16 17 18
2 23 19 18 17 13 12 11 12 13 14 15 16 17
3 22 21 20 16 12 11 10
4 23 22 21 15 14 13 9 8 4 3 2 1
5 24 23 22 16 15 9 8 7 6 5 1 0
G
I Example 4.5 (Maze Heuristic: the good case).
Example 6.5.9
We use the (Maze Heuristic:
Manhattan distanceThe good
to the goalcase). We use the Manhattan distance to
as a heuristic
the goal as a heuristic:
I 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
1 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4
2 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3
3 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2
4 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1
5 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0
G
Kohlhase: Künstliche Intelligenz 1 160 July 5, 2018
: 166 2025-05-14
Not surprisingly, the first maze is searchless, since we are guided by the perfect heuristic. In cases,
where there is a choice, the this has no influence on the length (or in other cases cost) of the
solution.
In the “good case” example, greedy search performs well, but there is some limited backtracking
needed, for instance when exploring the left lower corner 3×3 area before climbing over the second
wall.
In the “bad case”, greedy search is led down the lower garden path, which has a dead end, and
does not lead to the goal. This suggests that there we can construct adversary examples – i.e.
example mazes where we can force greedy search into arbitrarily bad performance.
Example 6.5.11. Greedy search can get stuck going from Iasi to Oradea:
Iasi → Neamt → Iasi → Neamt → · · ·
6.5. INFORMED SEARCH STRATEGIES 119
68 Chapter 3. Solving Problems by Searching
Oradea
71
Neamt
Zerind 87
75 151
Iasi
Arad
140
92
Sibiu Fagaras
99
118
Vaslui
80
Rimnicu Vilcea
Timisoara
142
111 Pitesti 211
Lugoj 97
70 98
85 Hirsova
Mehadia 146 101 Urziceni
75 138 86
Bucharest
Drobeta 120
90
Craiova Eforie
Giurgiu
has nothing to do with the nodes explored so far. This can prevent nodes from being enumerated
3.1.2 Formulating problems
In the preceding section we proposed a formulation of the problem of getting to Bucharest in
systematically as they are interms
UCS andstate,BFS.
of the initial actions, transition model, goal test, and path cost. This formulation
For completeness, we need repeated state checking as the example shows. This enforces complete
seems reasonable, but it is still a model—an abstract mathematical description—and not the
This assumption is algorithmically convenient but also theoretically justifiable—see page 649 in Chapter 17.
3
Heuristic Functions
Definition 6.5.13. Let Π be a search problem with states S. A heuristic function (or short
heuristic) for Π is a function h : S → R+
0 ∪ {∞} so that h(s) = 0 whenever s is a goal state.
h(s) is intended as an estimate the distance between state s and the nearest goal state.
Definition 6.5.14. Let Π be a search problem with states S, then the function h∗ : S →
R+ ∗
0 ∪ {∞}, where h (s) is the cost of a cheapest path from s to a goal state, or ∞ if no
such path exists, is called the goal distance function for Π.
Notes:
h(s) = 0 on goal states: If your estimator returns “I think it’s still a long way” on a goal
state, then its intelligence is, um . . .
Return value ∞: To indicate dead ends, from which the goal state can’t be reached
anymore.
The distance estimate depends only on the state s, not on the node (i.e., the path we
took to reach s).
120 CHAPTER 6. PROBLEM SOLVING AND SEARCH
: 168 2025-05-14
: 169 2025-05-14
In practice, we want it to be accurate (aka: informative), i.e., close to the actual goal
distance.
We also want it to be fast, i.e., a small overhead for computing h.
These two wishes are in contradiction!
Example 6.5.15 (Extreme cases).
: 170 2025-05-14
: 171 2025-05-14
Proof: we prove h(s) ≤ h∗ (s) for all s ∈ S by induction over the length of the cheapest path to a
goal node.
1. base case
1.1. h(s) = 0 by definition of heuristic, so h(s) ≤ h∗ (s) as desired.
3. step case
3.1. We assume that h(s′ ) ≤ h∗ (s) for all states s′ with a cheapest goal node path of length n.
3.2. Let s be a state whose cheapest goal path has length n+1 and the first transition is o = (s,s′ ).
3.3. By consistency, we have h(s) − h(s′ ) ≤ c(o) and thus h(s) ≤ h(s′ ) + c(o).
3.4. By construction, h∗ (s) has a cheapest goal path of length n and thus, by induction hypothesis
h(s′ ) ≤ h∗ (s′ ).
3.5. By construction, h∗ (s) = h∗ (s′ ) + c(o).
3.6. Together this gives us h(s) ≤ h∗ (s) as desired.
□
: 172 2025-05-14
: 173 2025-05-14
Definition 6.5.21. Best first search with evaluation function g + h is called A∗ search.
: 174 2025-05-14
122 CHAPTER 6. PROBLEM SOLVING AND SEARCH
This works, provided that h does not overestimate the true cost to achieve the goal. In other
words, h must be optimistic wrt. the real cost h∗ . If we are too pessimistic, then non-optimal
solutions have a chance.
A∗ Search: Optimality
Theorem 6.5.22. A∗ search with admissible heuristic is optimal.
Proof: We show that suboptimal goal nodes are never expanded by A∗
1. Suppose a suboptimal goal node G has been generated then we are in the following situation:
start
n
O G
: 175 2025-05-14
A∗ Search Example
Arad
366=0+366
Arad
Arad
Arad
Arad
646=280+366 671=291+380
Arad
646=280+366 671=291+380
: 176 2025-05-14
To extend our intuitions about informed search algorithms to A∗ -search, we take up the maze
examples from above again. We first show the good maze with Manhattan distance again.
G
We will find a solution with little search.
Kohlhase: Künstliche Intelligenz 1 160 July 5, 2018
: 177 2025-05-14
To compare it to A∗ -search, here is the same maze but now with the numbers in red for the
evaluation function f where h is the Manhattan distance.
I 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
1 18 22 22 22 22 22 24 24 24 24 24 24 24
2 18 20 20 20 22 22 22 22 22 22 22 22 22
3 18 18 18 20 22 22 22
4 18 18 18 20 20 20 22 22 24 24 24 24
5 18 18 18 20 20 24 22 22 22 22 24 24
G
I A with a consistent heuristic g + h always increases monotonically
⇤
(h cannot
In A∗ with a consistent heuristic, g + h always increases monotonically (h cannot
decrease mor than g increases)
decrease moremore
I We need thansearch,
g increases)
in the “right upper half”. This is typical: Greedy best-first
We need
searchmore
tendssearch, in thethan
to be faster “right
A⇤ .upper half”. This is typical: Greedy best first search
∗
tends to be faster than A .
Let’s now consider the “bad maze” with Manhattan distance again.
G
Kohlhase: Künstliche Intelligenz 1 160 July 5, 2018
: 179 2025-05-14
And we compare it to A∗ -search; again the numbers in red are for the evaluation function f .
I 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
1 18 17 24 24 24 24 24 24 24 24 24 24 24 24 24
2 18 16 22 14 13 12 11 10 9 8 7 6 5 4 24
3 18 15 20 13 22 22 22 9 26 26 26 5 30 3 24
4 18 18 18 12 20 10 22 8 24 6 26 4 28 2 24
5 18 18 18 18 18 9 22 22 22 5 26 26 26 1 24
G
We will search less of the “dead-end street”. Sometimes g + h gives better
We willsearch
search less of the
guidance than“dead-end
h. street”. Sometimes g + h gives
(; Abetter
⇤ search
is faster guidance
there)
than h. (; A∗ is faster there)
: 180 2025-05-14
I 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
1 24 17 24 24 24 24 24 24 24 24 24 24 24 24 24
2 24 16 24 14 13 12 11 10 9 8 7 6 5 4 24
3 24 15 24 13 34 36 38 9 50 52 54 5 66 3 24
4 24 24 24 12 32 10 40 8 48 6 56 4 64 2 24
5 26 26 26 28 30 9 42 44 46 5 58 60 62 1 24
G
In A⇤ , node values always increase monotonically (with any heuristic). If the
In A∗ ,heuristic
node values always
is perfect, increase
they remainmonotonically (with any
constant on optimal heuristic). If the heuristic is
paths.
perfect, they remain constant on optimal paths.
: 181 2025-05-14
Kohlhase: Künstliche Intelligenz 1 180 July 5, 2018
A∗ search: f -contours
Section 3.5. Informed (Heuristic) Search Strategies 97
Intuition: A -search gradually adds “f -contours” (areas of the same f -value) to the search.
∗
Z N
A I
380 S
F
V
400
T R
L P
H
M U
420 B
D
C E
G
Figure
:
3.25 Map of Romania showing 182
contours at f = 380, f = 400, and2025-05-14
f = 420, with
Arad as the start state. Nodes inside a given contour have f -costs less than or equal to the
contour value.
A∗ search: Properties
Figure 3.9; because f is nondecreasing along any path, n! would have lower f -cost than n
and wouldor
Properties have been selected first.
A∗ -search:
From the two preceding observations, it follows that the sequence of nodes expanded
by A∗ usingCompleteness
G RAPH -S EARCH isYes in nondecreasing
(unless there areorderinfinitely
of f (n).many
Hence, the first
nodes n goal node
selected for expansion must be with
an optimal
f (n) ≤solution
f (0)) because f is the true cost for goal nodes
(which haveTime 0) and all laterExponential
h = complexity goal nodes will be at leasterror
in [relative as expensive.
in h × length of
nondecreasing along any path also means that wencan draw
The fact that f -costs are solution]
CONTOUR contours in the state
Space space, justSame
complexity like the contours
as time in a of
(variant topographic
BFS) map. Figure 3.25 shows
an example. Inside the contourYes
Optimality labeled 400, all nodes have f (n) less than or equal to 400,
and so on. Then, because A∗ expands the frontier node of lowest f -cost, we can see that an
A∗ search fans out from the start node, adding nodes in concentric bands of increasing f -cost.
With uniform-cost search (A∗ search using h(n) = 0), the bands will be “circular”
around the start state. With more accurate heuristics, the bands will stretch toward the goal
state and become more narrowly focused around the optimal path. If C ∗ is the cost of the
6.5. INFORMED SEARCH STRATEGIES 127
: 183 2025-05-14
Admissible
Section 3.2. heuristics:
Example ProblemsExample 8-puzzle 71
7 2 4 1 2
5 6 3 4 5
8 3 1 6 7 8
away actions such as shaking the board when pieces get stuck and ruled out extracting the
pieces with a knife and putting them back again. We are left with a description of the rules of
Actually, the crucialthedifference
puzzle, avoiding between the
all the details heuristics
of physical h1 and h2 is that – not only in the example
manipulations.
configuration
PUZZLES above, but
SLIDING-BLOCK
Thefor all belongs
8-puzzle configurations
to the family of–sliding-block
the the value of the
puzzles, which are latter
often usedisas larger than that of
the former. We willtest problems for new search algorithms in AI. This family is known to be NP-complete,
explore this next.
so one does not expect to find methods significantly better in the worst case than the search
algorithms described in this chapter and the next. The 8-puzzle has 9!/2 = 181, 440 reachable
Dominance states and is easily solved. The 15-puzzle (on a 4 × 4 board) has around 1.3 trillion states, and
random instances can be solved optimally in a few milliseconds by the best search algorithms.
The 24-puzzle (on a 5 × 5 board) has around 1025 states, and random instances take several
Definition 6.5.31. Letoptimally.
hours to solve h1 and h2 be two admissible heuristics we say that h2 dominates h1
The goal of the 8-queens problem is to place eight queens on a chessboard such that
if h28-QUEENS ≥ h1 (n)
(n) PROBLEM for all n.
no queen attacks any other. (A queen attacks any piece in the same row, column or diago-
nal.) Figure 3.5 shows an attempted solution that fails: the queen in the rightmost column is
Theorem 6.5.32. attacked by h2queen
If the dominates h1 , then h2 is better for search than h1 .
at the top left.
: 185 2025-05-14
We now try to generalize these insights into (the beginnings of) a general method for obtaining
admissible heuristics.
128 CHAPTER 6. PROBLEM SOLVING AND SEARCH
Relaxed problems
Observation: Finding good admissible heuristics is an art!
Idea: Admissible heuristics can be derived from the exact solution cost of a relaxed version
of the problem.
Example 6.5.33. If the rules of the 8-puzzle are relaxed so that a tile can move anywhere,
then we get heuristic h1 .
Example 6.5.34. If the rules are relaxed so that a tile can move to any adjacent square,
then we get heuristic h2 . (Manhattan distance)
Definition 6.5.35. Let Π := ⟨S , A, T , I , G ⟩ be a search problem, then we call a search
problem P r := ⟨S, Ar , T r , I r , G r ⟩ a relaxed problem (wrt. Π; or simply relaxation of Π), iff
A ⊆ Ar , T ⊆ T r , I ⊆ I r , and G ⊆ G r .
Lemma 6.5.36. If P r relaxes Π, then every solution for Π is one for P r .
Key point: The optimal solution cost of a relaxed problem is not greater than the optimal
solution cost of the real problem.
: 186 2025-05-14
Relaxation means to remove some of the constraints or requirements of the original problem,
so that a solution becomes easy to find. Then the cost of this easy solution can be used as an
optimistic approximation of the problem.
See [Link]
Difference to Breadth-first Search?: That would explore all grid cells in a circle around
the initial state!
: 187 2025-05-14
6.6. LOCAL SEARCH 129
: 188 2025-05-14
: 189 2025-05-14
: 190 2025-05-14
Kohlhase: Künstliche Intelligenz 1 189 July 5, 2018
Definition 6.6.9. Hill climbing (also gradient ascent) is a local search algorithm that itera-
tively selects the best successor:
procedure Hill−Climbing (problem) /∗ a state that is a local minimum ∗/
local current, neighbor /∗ nodes ∗/
current := Make−Node(Initial−State[problem])
loop
neighbor := <a highest−valued successor of current>
if Value[neighbor] < Value[current] return [current] end if
current := neighbor
end loop
end procedure
: 191 2025-05-14
In order to understand the procedure on a more intuitive level, let us consider the following
scenario: We are in a dark landscape (or we are blind), and we want to find the highest hill. The
search procedure above tells us to start our search anywhere, and for every step first feel around,
and then take a step into the direction with the steepest ascent. If we reach a place, where the
next step would take us down, we are finished.
Of course, this will only get us into local maxima, and has no guarantee of getting us into
global ones (remember, we are blind). The solution to this problem is to re-start the search at
random (we do not have any information) places, and hope that one of the random jumps will get
us to a slope that leads to a global maximum.
a single current node (rather than multiple paths) and generally move only to neighbors
CURRENT NODE
with heuristic cost estimate h of=that17node. Typically, the paths followed by the search are not retained. Although local
showing h-values for moving a queen
search algorithms are not systematic, they have two key advantages: (1) they use very little
memory—usually a constant amount; and (2) they can often find reasonable solutions in large
within its column: or infinite (continuous) state spaces for which systematic algorithms are unsuitable.
In addition to finding goals, local search algorithms are useful for solving pure op-
OPTIMIZATION
timization problems, in which the aim is to find the best state according to an objective
Problem: The state space hasfunction.
local Many optimization problems do not fit the “standard” search model introduced in
PROBLEM
OBJECTIVE
FUNCTION
: 193 2025-05-14
Recent work on hill climbing algorithms tries to combine complete search with randomization to
escape certain odd phenomena occurring in statistical distribution of solutions.
124 Chapter 4. Beyond Classical Search
Simulated annealing (Idea)
Annealing is the process of heating steel and let it cool gradually to give it time to grow an
Figure 4.4 Illustration of why ridges cause difficulties for hill climbing. The grid of states
(dark circles) is superimposed on a ridge rising from left to right, creating a sequence of local
maxima that are not directly connected to each other. From each local maximum, all the
available actions point downhill.
132 CHAPTER 6. PROBLEM SOLVING AND SEARCH
: 194 2025-05-14
: 195 2025-05-14
E(x)
=e kT ≫1
e kT
for small T .
Question: Is this necessarily an interesting guarantee?
: 196 2025-05-14
6.6. LOCAL SEARCH 133
Observation: Local beam search is not the same as k searches run in parallel! (Searches
that find good states recruit other searches to join them)
Problem: Quite often, all k searches end up on the same local hill!
Idea: Choose k successors randomly, biased towards good ones.(Observe the close analogy
to natural selection!)
: 197 2025-05-14
Figure 4.6 The genetic algorithm, illustrated for digit strings representing 8-queens states.
The initial population in (a) is ranked by the fitness function in (b), resulting in pairs for
: 198 2025-05-14
mating in (c). They produce offspring in (d), which are subject to mutation in (e).
Figure 4.7 The 8-queens states corresponding to the first two parents in Figure 4.6(c) and
the first offspring in Figure 4.6(d). The shaded columns are lost in the crossover step and the
unshaded columns are retained.
Like beam searches, GAs begin with a set of k randomly generated states, called the
POPULATION population. Each state, or individual, is represented as a string over a finite alphabet—most
INDIVIDUAL commonly, a string of 0s and 1s. For example, an 8-queens state must specify the positions of
8 queens, each in a column of 8 squares, and so requires 8 × log2 8 = 24 bits. Alternatively,
the state could be represented as 8 digits, each in the range from 1 to 8. (We demonstrate later
that the two encodings behave differently.) Figure 4.6(a) shows a population of four 8-digit
24415124 20 26% 32752411 32752124 32252124
32543213 11 14% 24415124 24415411 24415417
Figure 4.6 The genetic algorithm, illustrated for digit strings representing 8-queens states.
The initial population in (a) is ranked by the fitness function in (b), resulting in pairs for
mating in (c). They produce offspring in (d), which are subject to mutation in (e).
134 CHAPTER 6. PROBLEM SOLVING AND SEARCH
+ =
Figure 4.7 The 8-queens states corresponding to the first two parents in Figure 4.6(c) and
Note: Geneticthe first offspring in Figure 4.6(d). The shaded columns are lost in the crossover step and the
algorithms ̸= evolution: e.g., real genes also encode replication machinery!
unshaded columns are retained.
: 199 2025-05-14
Like beam searches, GAs begin with a set of k randomly generated states, called the
POPULATION population. Each state, or individual, is represented as a string over a finite alphabet—most
INDIVIDUAL commonly, a string of 0s and 1s. For example, an 8-queens state must specify the positions of
8 queens, each in a column of 8 squares, and so requires 8 × log2 8 = 24 bits. Alternatively,
the state could be represented as 8 digits, each in the range from 1 to 8. (We demonstrate later
that the two encodings behave differently.) Figure 4.6(a) shows a population of four 8-digit
strings representing 8-queens states.
The production of the next generation of states is shown in Figure 4.6(b)–(e). In (b),
FITNESS FUNCTION each state is rated by the objective function, or (in GA terminology) the fitness function. A
fitness function should return higher values for better states, so, for the 8-queens problem
we use the number of nonattacking pairs of queens, which has a value of 28 for a solution.
The values of the four states are 24, 23, 20, and 11. In this particular variant of the genetic
algorithm, the probability of being chosen for reproducing is directly proportional to the
fitness score, and the percentages are shown next to the raw scores.
In (c), two pairs are selected at random for reproduction, in accordance with the prob-
Chapter 7
7.1 Introduction
The Problem
The Problem of Game-Play: cf. chapter 6
Example 7.1.1.
: 200 2025-05-14
135
136 CHAPTER 7. ADVERSARIAL SEARCH FOR GAME PLAYING
: 201 2025-05-14
: 202 2025-05-14
An Example Game
7.1. INTRODUCTION 137
: 203 2025-05-14
Many of these more general game types can be handled by similar/extended algorithms.
: 204 2025-05-14
: 205 2025-05-14
We don’t know how the opponent will react, and need to prepare for all possibilities.
Definition 7.1.7. A strategy is called optimal if it yields the best possible utility for X
assuming perfect opponent play (not formalized here).
Problem: In (almost) all games, computing an optimal strategy is infeasible. (state/search
tree too huge)
Solution: Compute the next move “on demand”, given the current state instead.
: 206 2025-05-14
It’s even worse: Our algorithms here look at search trees (game trees), no duplicate pruning.
Example 7.1.10.
Chess without duplicate pruning: 35100 ≃ 10154 .
Go without duplicate pruning: 200300 ≃ 10690 .
: 207 2025-05-14
Answer: Declarative!
With “game description language” =
b natural language.
: 208 2025-05-14
7.2. MINIMAX SEARCH 139
Human knowledge is key: evaluation functions (see later), opening databases (chess!!),
end game databases.
Declarative: General game playing, active area of research in AI.
Generic game description language (GDL), based on logic.
Solvers are given only “the rules of the game”, no other knowledge/input whatsoever
(cf. chapter 6).
Regular academic competitions since 2005.
: 209 2025-05-14
Minimax is the canonical (and easiest to understand) algorithm for solving games, i.e.,
computing an optimal strategy.
Evaluation functions: But what if we don’t have the time/memory to solve the entire
game?
Given limited time, the best we can do is look ahead as far as we can. Evaluation functions
tell us how to evaluate the leaf states at the cut off.
Alphabeta search: How to prune unnecessary parts of the tree?
Often, we can detect early on that a particular action choice cannot be part of the optimal
strategy. We can then stop considering this part of the game tree.
State of the art: What is the state of affairs, for prominent games, of computer game
playing vs. human experts?
Just FYI (not part of the technical content of this course).
: 210 2025-05-14
Idea: Use tree search using an extension û of the utility function u to inner nodes. û is
computed recursively from u during search:
Max
Section 5.2. attempts
Optimal to maximize
Decisions in Gamesû(s) of the terminal states reachable during play. 163
Min attempts to minimize û(s).
until we reach leaf nodes corresponding to terminal states such that one player has three in
The computation
a row or all thealternates
squares arebetween minimization
filled. The and leaf
number on each maximization hence
; the
node indicates “minimax”.
utility value
of the terminal state from the point of view of MAX; high values are assumed to be good for
MAX and bad for MIN (which is how the players get their names).
: 211 2025-05-14
For tic-tac-toe the game tree is relatively small—fewer than 9! = 362, 880 terminal
40
nodes. But for chess there are over 10 nodes, so the game tree is best thought of as a
theoretical construct that we cannot realize in the physical world. But regardless of the size
Example
SEARCH TREE
Tic-Tac-Toe
of the game tree, it is MAX’s job to search for a good move. We use the term search tree for a
tree that is superimposed on the full game tree, and examines enough nodes to allow a player
Example 7.2.1. what
to determine A full game
move tree for tic-tac-toe
to make.
MAX (X)
X X X
MIN (O) X X X
X X X
XO X O X ...
MAX (X) O
X O X X O X O ...
MIN (O) X X
X O X X O X X O X ...
TERMINAL O X O O X X
O X X O X O O
Utility –1 0 +1
Figure 5.1 A (partial) game tree for the game of tic-tac-toe. The top node is the initial
currentstate,
player and action marked on the left.
and MAX moves first, placing an X in an empty square. We show part of the tree, giving
Last row: terminal
alternating movespositions
by MIN ( Owith their( Xutility.
) and MAX ), until we eventually reach terminal states, which
can be assigned utilities according to the rules of the game.
: 212 2025-05-14
If it’s Max’s turn: Set û(n) to the maximum of the utilities of n’s successor nodes.
If it’s Min’s turn: Set û(n) to the minimum of the utilities of n’s successor nodes.
4. Selecting a move for Max at the root: Choose one move that leads to a successor node
with maximal utility.
: 213 2025-05-14
Minimax: Example
Max 3
3 12 8 2 4 6 14 5 2
: 214 2025-05-14
: 215 2025-05-14
Max −∞
Max −∞
Min ∞
Max −∞
Min ∞
Max −∞
Min 3
Max −∞
Min 3
3 12
7.2. MINIMAX SEARCH 143
Max −∞
Min 3
3 12 8
Max 3
Min 3
3 12 8
Max 3
Min 3 Min ∞
3 12 8
Max 3
Min 3 Min ∞
3 12 8 2
144 CHAPTER 7. ADVERSARIAL SEARCH FOR GAME PLAYING
Max 3
Min 3 Min ∞
3 12 8 2
Max 3
Min 3 Min 2
3 12 8 2 4
Max 3
Min 3 Min 2
3 12 8 2 4 6
Max 3
3 12 8 2 4 6
7.2. MINIMAX SEARCH 145
Max 3
3 12 8 2 4 6 14
Max 3
3 12 8 2 4 6 14
Max 3
3 12 8 2 4 6 14 5
Max 3
3 12 8 2 4 6 14 5 2
146 CHAPTER 7. ADVERSARIAL SEARCH FOR GAME PLAYING
Max 3
3 12 8 2 4 6 14 5 2
Max 3
3 12 8 2 4 6 14 5 2
Leftmost branch.
Note: The maximal possible pay-off is higher for the rightmost branch, but assuming perfect
play of Min, it’s better to go left. (Going right would be “relying on your opponent to do
something stupid”.)
: 216 2025-05-14
There’s no need to re-run minimax for every game state: Run it once, offline before the
game starts. During the actual game, just follow the branches taken in the tree. Whenever
it’s your turn, choose an action maximizing the value of the successor states.
Minimax disadvantages: It’s completely infeasible in practice.
7.3. EVALUATION FUNCTIONS 147
When the search tree is too large, we need to limit the search depth and apply an evaluation
function to the cut off states.
: 217 2025-05-14
Solution: We impose a search depth limit (also called horizon) d, and apply an evaluation
function to the cut-off states, i.e. states s with dp(s) = d.
Definition 7.3.1. An evaluation function f maps game states to numbers:
f (s) is an estimate of the actual value of s (as would be computed by unlimited-depth
minimax for s).
If cut-off state is terminal: Just use û instead of f .
Analogy to heuristic functions (cf. section 6.5): We want f to be both (a) accurate and (b)
fast.
Another analogy: (a) and (b) are in contradiction ; need to trade-off accuracy against
overhead.
In typical game playing algorithms today, f is inaccurate but very fast. (usually no good
methods known for computing accurate f )
: 218 2025-05-14
Max 3
3 12 8 2 4 6 14 5 2
: 219 2025-05-14
Example Chess
: 220 2025-05-14
: 221 2025-05-14
This assumes that the features (their contribution towards the actual value of the state) are
independent. That’s usually not the case (e.g. the value of a rook depends on the pawn struc-
ture).
Example 7.3.3.
7.4. ALPHA-BETA SEARCH 149
Black to move
: 222 2025-05-14
: 223 2025-05-14
Max (A)
Say n > m.
By choosing to go to the left in search
node (A), Max already can get utility of
Min at least n in this part of the game.
value: n
So, if “later on” (further down in the same
subtree), in search node (B) we already
Min (B) know that Min can force Max to get value
m < n.
: 224 2025-05-14
Max 3
3 12 8 2 4 6 14 5 2
: 225 2025-05-14
Max ≥3
3 12 8 2
Idea: We can use this to prune the search tree ; better algorithm
: 226 2025-05-14
Alpha Pruning
Definition 7.4.1. For each node n in a minimax search tree, the alpha value α(n) is the
highest Max-node utility that search has encountered on its path from the root to n.
Max −∞; α = −∞
Max −∞; α = −∞
Min ∞; α = −∞
Max −∞; α = −∞
Min ∞; α = −∞
3
152 CHAPTER 7. ADVERSARIAL SEARCH FOR GAME PLAYING
Max −∞; α = −∞
Min 3; α = −∞
Max −∞; α = −∞
Min 3; α = −∞
3 12
Max −∞; α = −∞
Min 3; α = −∞
3 12 8
Max 3; α = 3
Min 3; α = −∞
3 12 8
7.4. ALPHA-BETA SEARCH 153
Max 3; α = 3
Min 3; α = −∞ Min ∞; α = 3
3 12 8
Max 3; α = 3
Min 3; α = −∞ Min ∞; α = 3
3 12 8 2
Max 3; α = 3
Min 3; α = −∞ Min 2; α = 3
3 12 8 2
Max 3; α = 3
3 12 8 2
How to use α?: In a Min-node n, if û(n′ ) ≤ α(n) for one of the successors, then stop
considering n. (pruning out its remaining successors)
154 CHAPTER 7. ADVERSARIAL SEARCH FOR GAME PLAYING
: 227 2025-05-14
Alpha-Beta Pruning
Recall:
What is α: For each search node n, the highest Max-node utility that search has en-
countered on its path from the root to n.
How to use α: In a Min-node n, if one of the successors already has utility ≤ α(n), then
stop considering n. (Pruning out its remaining successors)
Idea: We can use a dual method for Min!
Definition 7.4.3. For each node n in a minimax search tree, the beta value β(n) is the
highest Min-node utility that search has encountered on its path from the root to n.
How to use β: In a Max-node n, if one of the successors already has utility ≥ β(n), then
stop considering n. (pruning out its remaining successors)
. . . and of course we can use α and β together! ; alphabeta-pruning
: 228 2025-05-14
: 229 2025-05-14
Note: Note that α only gets assigned a value in Max-nodes, and β only gets assigned a value in
Min-nodes.
Notation: v; [α, β]
Min ∞; [−∞, ∞]
Min ∞; [−∞, ∞]
Min 3; [−∞, 3]
Min 3; [−∞, 3]
3 12
156 CHAPTER 7. ADVERSARIAL SEARCH FOR GAME PLAYING
Min 3; [−∞, 3]
3 12 8
Max 3; [3, ∞]
Min 3; [−∞, 3]
3 12 8
Max 3; [3, ∞]
3 12 8
Max 3; [3, ∞]
3 12 8 2
7.4. ALPHA-BETA SEARCH 157
Max 3; [3, ∞]
3 12 8 2
Max 3; [3, ∞]
3 12 8 2
Max 3; [3, ∞]
3 12 8 2 14
Max 3; [3, ∞]
3 12 8 2 14
158 CHAPTER 7. ADVERSARIAL SEARCH FOR GAME PLAYING
Max 3; [3, ∞]
3 12 8 2 14 5
Max 3; [3, ∞]
3 12 8 2 14 5
Max 3; [3, ∞]
3 12 8 2 14 5 2
Max 3; [3, ∞]
3 12 8 2 14 5 2
Note: We could have saved work by choosing the opposite order for the successors of the
7.4. ALPHA-BETA SEARCH 159
rightmost Min-node.
Choosing the best moves (for each of Max and Min) first yields more pruning!
: 230 2025-05-14
Max 3; [3, ∞]
3 12 8 2
Max 3; [3, ∞]
3 12 8 2 5
Max 3; [3, ∞]
3 12 8 2 5
160 CHAPTER 7. ADVERSARIAL SEARCH FOR GAME PLAYING
Max 3; [3, ∞]
Max 3; [3, ∞]
14
Max 3; [3, ∞]
14
7.4. ALPHA-BETA SEARCH 161
Max 3; [3, ∞]
14
Max 3; [3, ∞]
14
: 231 2025-05-14
Move ordering: Try captures first, then threats, then forward moves, then backward
moves.
d
From 35d to 35 2 . E.g., if we have the time to search a billion (109 ) nodes, then minimax
looks ahead d = 6 moves, i.e., 3 rounds (white-black) of the game. Alpha-beta search
looks ahead 6 rounds.
: 232 2025-05-14
And now . . .
AlphaGo = Monte Carlo tree search (AI-1) + neural networks (AI-2)
: 233 2025-05-14
Definition 7.5.2. For the Monte Carlo tree search algorithm (MCTS) we maintain a search
tree T , the MCTS tree.
while time not up do
apply actions within T to select a leaf state s′
7.5. MONTE-CARLO TREE SEARCH (MCTS) 163
: 234 2025-05-14
This looks only at a fraction of the search tree, so it is crucial to have good guidance where to go,
i.e. which part of the search tree to look at.
Expansions: 0, 0, 0
avg. reward: 0, 0, 0 Expan-
sions: 0, 1, 0
avg. reward: 0, 10, 0 Ex-
pansions: 1, 1, 0
avg. reward: 70, 10, 0 Ex-
pansions: 1, 1, 1
avg. reward: 70, 10, 40 Ex-
pansions: 1, 1, 2
avg. reward: 70, 10, 35 Ex- Expansions: 0, 0
pansions: 2, 1, 2 avg. reward: 0, 0
avg. reward: 60, 10, 35 Ex-
pansions: 2, 2, 2
avg. reward: 60, 55, 35 Ex-
pansions: 2, 2, 2
avg. reward: 60, 55, 35 40
70 50 30
100 10
: 235 2025-05-14
The sampling goes middle, left, right, right, left, middle. Then it stops and selects the highest-
average action, 60, left. After first sample, when values in initial state are being updated, we
have the following “expansions” and “avg. reward fields”: small number of expansions favored for
exploration: visit parts of the tree rarely visited before, what is out there? avg. reward: high
values favored for exploitation: focus on promising parts of the search tree.
164 CHAPTER 7. ADVERSARIAL SEARCH FOR GAME PLAYING
Expansions: 0, 0, 0
avg. reward: 0, 0, 0 Expan-
sions: 0, 1, 0
avg. reward: 0, 10, 0 Expan-
sions: 1, 1, 0
avg. reward: 70, 10, 0 Ex-
Expansions: 1, 0 Expansions: 1 pansions: 1, 1, 1
avg. reward: 70, 0 Ex- avg. reward: 10 avg. reward: 70, 10, 40 Ex-
pansions: 2, 0 Expansions: 2 pansions: 1, 1, 2
avg. reward: 60, 0 avg. reward: 55 avg. reward: 70, 10, 35 Ex-
Expansions: 1, 0
Expansions: 1 pansions: 2, 1, 2 avg. reward: 40, 0 Ex-
avg. reward: 100 avg. reward: 60, 10, 35 Ex- 2, 0
pansions:
pansions: 2, 2, 2 avg. reward: 35, 0
avg. reward: 60, 55, 35 Ex-
Expansions: 0, 1 pansions: 2, 2, 2 Expansions: 0, 1
avg. reward: 0, 50 avg. reward: 60, 55, 35 avg. reward: 0, 30
40
70 50 30
100 10
: 236 2025-05-14
This is the exact same search as on previous slide, but incrementally building the search tree,
by always keeping the first state of the sample. The first three iterations middle, left, right, go
to show the tree extension; do point out here that, like the root node, the nodes added to the
tree have expansions and avg reward counters for every applicable action. Then in next iteration
right, after 30 leaf node was found, an important thing is that the averages get updated *along
the entire path*, i.e., not only in the root as we did before, but also in the nodes along the way.
After all six iterations have been done, as before we select the action left, value 60; but we keep
the part of the tree below that action, “saving relevant work already done before”.
: 237 2025-05-14
AlphaGo: Overview
Definition 7.5.5 (Neural Networks in AlphaGo).
Policy networks: Given a state s, output a probability distribution over the actions appli-
cable in s.
Value networks: Given a state s, output a number estimating the game value of s.
Combination with MCTS:
Policy networks bias the action choices within the MCTS tree (and hence the leaf state
selection), and bias the random samples.
Value networks are an additional source of state values in the MCTS tree, along with the
random samples.
And now in a little more detail
: 238 2025-05-14
Policy gradient
on
Cla
Se
ati
on
ssi
lf P
fic
ssi
fi
ssi
lay
gre
ca
Cla
tio
Re
n
Data
s s′
Human expert positions Self-play positions
Figure 1 | Neural network training pipeline and architecture. a, A fast the current player wins) in positions from the self-play data set.
rollout policy pπ and supervised learning (SL) policy network pσ are b, Schematic representation of the neural network architecture used in
trained to predict human
Illustration expert from
taken moves in[silver:etal:nature-16]
a data set of positions. AlphaGo.
. The policy network takes a representation of the board position
A reinforcement learning (RL) policy network pρ is initialized to the SL s as its input, passes it through many convolutional layers with parameters
policy network, and is then improved by policy gradient learning to σ (SL policy network) or ρ (RL policy network), and outputs a probability
maximize Rollout
the outcome policy pπ : Simple
(that is, winning more games) but fast,
against ≈ prior distribution
previous work on pσGo. (a | s) or pρ (a | s) over legal moves a, represented by a
versions of the policy network. A new data set is generated by playing probability map over the board. The value network similarly uses many
games of SL policy
self-play with thenetwork pσ : Supervised
RL policy network. learning,
Finally, a value network vθ human-expert
convolutional layers with data (“learnθ, but
parameters to outputs
choose anvalue
a scalar expert
vθ(s′)
is trained by regression to predict the expected outcome (that is, whether that predicts the expected outcome in position s′.
action”).
sampled
state-action
RL policypairs (s, a), using
network pρstochastic gradient ascent
: Reinforcement to and its
learning, weights ρ (“learn
self-play are initialized to the same values, ρ = σ. We play
to win”).
maximize the likelihood of the human move a selected in state s games between the current policy network pρ and a randomly selected
previous iteration of the policy network. Randomizing from a pool
∂log pσ (a | s ) of opponents in this way stabilizes training by preventing overfitting
∆σ ∝
∂σ to the current policy. We use a reward function r(s) that is zero for all
non-terminal time steps t < T. The outcome zt = ± r(sT) is the termi-
We trained a 13-layer policy network, which we call the SL policy nal reward at the end of the game from the perspective of the current
network, from 30 million positions from the KGS Go Server. The net- player at time step t: +1 for winning and −1 for losing. Weights are
166 CHAPTER 7. ADVERSARIAL SEARCH FOR GAME PLAYING
Value network vθ : Use self-play games with pρ as training data for game-position evalu-
ation vθ (“predict which player will win in this state”).
: 239 2025-05-14
QT
P P Q Q
Q + u(P) max Q + u(P)
QT QT
Q Q
P P
Q + u(P) max Q + u(P)
pV QT QT QT
P P
pS
r r r r
Figure 3 | Monte Carlo tree search in AlphaGo. a, Each simulation is evaluated in two ways: using the value network vθ; and by running
traverses the tree by selecting the edge with maximum action value Q, a rollout to the end of the game with the fast rollout policy pπ, then
Illustration
plus a bonus takenonfrom
u(P) that depends a stored[silver:etal:nature-16]
prior probability P for that computing the winner with function r. d, Action values Q are updated to
edge. b, The leaf node may be expanded; the new node is processed once track the mean value of all evaluations r(·) and vθ(·) in the subtree below
by the policy network pσ and the output probabilities are stored as prior that action.
Rollout policy pπ : Action choice in random samples.
probabilities P for each action. c, At the end of a simulation, the leaf node
SL policy network p : Action choice bias within the UCTS tree (stored as “P ”, gets
learning of convolutional networks, won 11% σ of games against Pachi23 (s, a) of the search tree stores an action value Q(s, a), visit count N(s, a),
smaller
and 12% against to weaker
a slightly “u(P )” with Fuego
program, number
24
. of visits); along with
and prior qualityP(s,
probability Q.a). The tree is traversed by simulation (that
is, descending the tree in complete games without backup), starting
RL policy
Reinforcement learningnetwork
of value : Not used here (used from
pρnetworks onlythe toroot
learn θ ).
[Link] each time step t of each simulation, an action at
The final stage of the training pipeline focuses on position evaluation, is selected from state st
Value network p v : Used to evaluate leaf
estimating a value function v (s) that predicts the outcome from posi-
θ states s, in linear sum with the value returned
by played
tion s of games a random
by usingsample onboth
policy p for s. players28–30 a t = argmax(Q(s t , a ) + u(s t , a ))
a
v p(s ) = E[z t|s t = s, a t … T ~ p]
so as to maximize action value plus a bonus
: 240 2025-05-14
Ideally, we would like to know the optimal value function under
perfect play v*(s); in practice, we instead estimate the value function P(s, a )
u(s, a ) ∝
v pρ for our strongest
Comments onpolicy,theusing the RL policy network pρ. We approx-
Figure: 1 + N (s, a )
imate the value function using a value network vθ(s) with weights θ,
pρ ⁎
a vθEach (s ) ≈ v (s ) . Thistraverses
(s ) ≈ v simulation neural network
thehas a similar
tree architecture the
by selecting thatedge with maximum
is proportional to the prioraction valuebut
probability plus awith
Q,decays
to the policy network, but outputs a single prediction instead of a prob- repeated visits to encourage exploration. When the traversal reaches a
bonus
ability u(P ) that
distribution. We train depends
the weightson a value
of the stored prior
network probability
by regres- leaf nodeP sL atfor
stepthat
L, the edge.
leaf node may be expanded. The leaf position
sion on state-outcome pairs (s, z), using stochastic gradient descent to sL is processed just once by the SL policy network pσ. The output prob-
minimize the mean squared error (MSE) between the predicted value abilities are stored as prior probabilities P for each legal action a,
vθ(s), and the corresponding outcome z P(s, a ) = pσ (a|s ) . The leaf node is evaluated in two very different ways:
first, by the value network vθ(sL); and second, by the outcome zL of a
∂vθ(s )
7.6. STATE OF THE ART 167
b The leaf node may be expanded; the new node is processed once by the policy network pσ and
the output probabilities are stored as prior probabilities P for each action.
c At the end of a simulation, the leaf node is evaluated in two ways:
• The AlphaGo design is quite intricate (architecture, learning workflow, training data design,
neural network architectures, . . . ).
• How much of this is reusable in/generalizes to other problems?
• Still lots of human expertise in here. Not as much, like in chess, about the game itself. But
rather, in the design of the neural networks + learning architecture.
: 241 2025-05-14
: 242 2025-05-14
: 243 2025-05-14
: 244 2025-05-14
7.7 Conclusion
Summary
Games (2-player turn-taking zero-sum discrete and finite games) can be understood as a
simple extension of classical search problems.
Each player tries to reach a terminal state with the best possible utility (maximal vs. minimal).
Minimax searches the game depth-first, max’ing and min’ing at the respective turns of each
7.7. CONCLUSION 169
player. It yields perfect play, but takes time O(bd ) where b is the branching factor and d the
search depth.
Except in trivial games (Tic-Tac-Toe), minimax needs a depth limit and apply an evaluation
function to estimate the value of the cut-off states.
Alpha-beta search remembers the best values achieved for each player elsewhere in the tree
already, and prunes out sub-trees that won’t be reached in the game.
Monte Carlo tree search (MCTS) samples game branches, and averages the findings. AlphaGo
controls this using neural networks: evaluation function (“value network”), and action filter
(“policy network”).
: 245 2025-05-14
Suggested Reading:
In the last chapters we have studied methods for “general problem”, i.e. such that are applicable to
all problems that are expressible in terms of states and “actions”. It is crucial to realize that these
states were atomic, which makes the algorithms employed (search algorithms) relatively simple
and generic, but does not let them exploit the any knowledge we might have about the internal
structure of states.
In this chapter, we will look into algorithms that do just that by progressing to factored states
representations. We will see that this allows for algorithms that are many orders of magnitude
more efficient than search algorithms.
To give an intuition for factored states representations we, we present some motivational exam-
ples in section 8.1 and go into detail of the Waltz algorithm, which gave rise to the main ideas
of constraint satisfaction algorithms in section 8.2. section 8.3 and section 8.5 define constraint
satisfaction problems formally and use that to develop a class of backtracking/search based al-
gorithms. The main contribution of the factored states representations is that we can formulate
advanced search heuristics that guide search based on the structure of the states.
171
172 CHAPTER 8. CONSTRAINT SATISFACTION PROBLEMS
: 246 2025-05-14
A constraint of order 1 is called unary, one of order 2 binary, and a constraint c is higher-order,
iff ord(c) > 2.
Definition 8.1.4. A CSP γ is called satisfiable, iff it has a solution: a total variable assign-
ment φ that satisfies all constraints.
Definition 8.1.5. The process of finding solutions to CSPs is called constraint solving.
Remark 8.1.6. We are using factored representation for world states now!
Allows useful general-purpose algorithms with more power than standard tree search algo-
rithm.
: 247 2025-05-14
8.1. CONSTRAINT SATISFACTION PROBLEMS: MOTIVATION 173
: 248 2025-05-14
Figure 6.1 (a) The principal states and territories of Australia. Coloring this map can
be viewed as a constraint satisfaction problem (CSP). The goal is to assign colors to each
Variables: vAvs.B where A and B are teams, with domains {1, . . . ,34}: For each match, the
index of the weekend where it is scheduled.
(Some) constraints:
If {A, B} ∩ {C, D} ̸= ∅: vAvs.B ̸=
vCvs.D (each team only one match
per day).
If {A, B} = {C, D}: vAvs.B ≤ 17 <
vCvs.D or vCvs.D ≤ 17 < vAvs.B
(each pairing exactly once in each
half-season).
If A = C: vAvs.B + 1 ̸= vCvs.D
(each team alternates between home
matches and away matches).
: 250 2025-05-14
Estimated running time: End of this universe, and the next couple billion ones after it
...
Directly enumerate all permutations of the numbers 1, . . . , 306, test for each whether it’s a
legal Bundesliga schedule.
Estimated running time: Maybe only the time span of a few thousand universes.
View this as variables/constraints and use backtracking (this chapter)
Executed running time: About 1 minute.
How do they actually do it?: Modern computers and CSP methods: fractions of a second.
19th (20th/21st?) century: Combinatorics and manual work.
Try it yourself: with an off-the shelf CSP solver, e.g. Minion [minion:URL]
: 251 2025-05-14
: 252 2025-05-14
1. U.S. Major League Baseball, 30 teams, each 162 games. There’s one crucial additional difficulty,
in comparison to Bundesliga. Which one? Travel is a major issue here!! Hence “Traveling
Tournament Problem” in reference to the TSP.
2. This particular scheduling problem is called “car sequencing”, how to most efficiently get cars
through the available machines when making the final customer configuration (non-standard/flexible/custom
extras).
3. Another common form of scheduling . . .
4. The problem of assigning radio frequencies so that all can operate together without noticeable
interference. Variable domains are available frequencies, constraints take form of |x − y| > δxy ,
where delta depends on the position of x and y as well as the physical environment.
: 253 2025-05-14
How are constraint networks, and assignments, consistency, solutions: How are constraint
satisfaction problems defined? What is a solution?
Get ourselves on firm ground.
Naïve Backtracking: How does backtracking work? What are its main weaknesses?
Serves to understand the basic workings of this wide-spread algorithm, and to motivate
its enhancements.
Variable- and Value Ordering: How should we guide backtracking searchs?
Simple methods for making backtracking aware of the structure of the problem, and
thereby reduce search.
: 254 2025-05-14
We will now have a detailed look at the problem (and innovative solution) that started the
field of constraint satisfaction problems.
Background:
Adolfo Guzman worked on an algorithm to count the number of simple objects (like children’s
blocks) in a line drawing. David Huffman formalized the problem and limited it to objects in
general position, such that the vertices are always adjacent to three faces and each vertex is
formed from three planes at right angles (trihedral). Furthermore, the drawings could only have
three kinds of lines: object boundary, concave, and convex. Huffman enumerated all possible
configurations of lines around a vertex. This problem was too narrow for real-world situations, so
Waltz generalized it to include cracks, shadows, non-trihedral vertices and light. This resulted in
over 50 different line labels and thousands of different junctions. [mit-ocw:line-drawings]
: 255 2025-05-14
8.2. THE WALTZ ALGORITHM 177
Observation 8.2.1. Then each line on the images is one of the following:
a boundary line (edge of an object) (<) with right hand of arrow denoting “solid” and left
hand denoting “space”
an interior convex edge (label with “+”)
an interior concave edge (label with “-”)
: 256 2025-05-14
: 257 2025-05-14
Waltz’s Examples
In his dissertation 1972 [Waltz:uldss75] David Waltz used the following examples
: 258 2025-05-14
: 259 2025-05-14
: 260 2025-05-14
We will now work our way towards a definition of CSPs that is formal enough so that we can
define the concept of a solution. This gives use the necessary grounding to talk about algorithms
later.
Types of CSPs
Definition 8.3.1. We call a CSP discrete, iff all of the variables have countable domains; we
have two kinds:
Theorem 8.3.4. Linear constraints solvable in poly time by linear programming methods.
Theorem 8.3.5. There cannot be optimal algorithms for nonlinear constraint systems.
: 261 2025-05-14
180 CHAPTER 8. CONSTRAINT SATISFACTION PROBLEMS
Types of Constraints
We classify the constraints by the number of variables they involve.
Definition 8.3.6. Unary constraints involve a single variable, e.g., SA ̸= green.
Definition 8.3.7. Binary constraints involve pairs of variables, e.g., SA ̸= WA.
: 262 2025-05-14
Definition 8.3.11. Problems like the one in Example 8.3.10 are called crypto-arithmetic
puzzles.
: 263 2025-05-14
D+E = Y + 10 · X1
S E N D
X1 + N + R = E + 10 · X2
+ M O R E
X2 + E + O = N + 10 · X3 M O N E Y
X3 + S + M = O + 10 · M
Problem: The problem structure gets hidden. (search algorithms can get confused)
: 264 2025-05-14
Constraint Graph
Definition 8.3.13. A binary CSP is a CSP where each constraint is unary or binary.
Observation 8.3.14. A binary CSP forms a graph called the constraint graph whose nodes
are variables, and whose edges represent the constraints.
NT NT
Q Q
NorthernNorthern WA WA
Territory
Territory
Queensland
Queensland
WesternWestern
Australia
SA SA NSW NSW
Australia
South South
Australia
Australia New New
South South V
Wales Wales
V
VictoriaVictoria
Tasmania
Tasmania
T T
(a) (a) (b) (b)
FigureFigure
6.1 6.1 (a) The(a)principal states states
The principal and territories of Australia.
and territories Coloring
of Australia. this map
Coloring this can
map can
Intuition: General-purpose CSP algorithms use the graph structure to speed up search.
be viewed as a constraint
be viewed satisfaction
as a constraint problem
satisfaction (CSP).(CSP).
problem The goal
Theisgoal
to assign colorscolors
is to assign to eachto each
(E.g., Tasmania is an independent subproblem!)
regionregion
so thatsonothat
represented
neighboring regions
no neighboring
as a constraint
represented
have the
regions
[Link].
as a constraint
same
have the color. (b) The
same color. (b)map-coloring problem
The map-coloring problem
immediately discard
immediately furtherfurther
discard refinements of theofpartial
refinements assignment.
the partial Furthermore,
assignment. we can
Furthermore, weseecan see
: why the
whyassignment is not isa solution—we
the assignment see
265 which
not a solution—we variables
see which violate
variables a constraint—so
violate we can
a constraint—so we 2025-05-14
can
focus focus
attention on theonvariables
attention that matter.
the variables As a result,
that matter. manymany
As a result, problems that are
problems thatintractable
are intractable
for regular state-space
for regular searchsearch
state-space can becan
solved quickly
be solved when when
quickly formulated as a CSP.
formulated as a CSP.
Real-world CSPs
[Link].2
Example
Factories have the
Factories have
problem:
Example
problem
the problem
Job-shop
problem: scheduling
Job-shop
of scheduling a day’s
of scheduling
scheduling
worthworth
a day’s of jobs,
of subject to various
jobs, subject constraints.
to various constraints.
In practice, manymany
In practice, of these problems
of these are solved
problems with CSP
are solved withtechniques. Consider
CSP techniques. the problem
Consider of of
the problem
Example 8.3.16 (Assignment
scheduling the assembly
scheduling of problems).
a car.
the assembly of aThe
[Link] job e.g.,
The wholeis job whoof tasks,
composed teaches
is composed and we
of tasks, what
can
and can class
wemodel each each
model
task as a variable,
task wherewhere
as a variable, the value of each
the value of variable is the istime
each variable the that
timethe thattask
thestarts, expressed
task starts, expressed
as an asinteger number
an integer of minutes.
number of minutes. Constraints can assert
Constraints that one
can assert that task
one must occuroccur
task must beforebefore
Example 8.3.17 (Timetabling
another—for example,
another—for example, problems).
a wheel must must
a wheel be installed e.g., which
beforebefore
be installed the hubcap class is on—and
is putison—and
the hubcap put offered thatwhen
that only only and where?
so many tasks tasks
so many can go canongoat ononce. Constraints
at once. can also
Constraints can specify that athat
also specify taska takes a certain
task takes a certain
Example 8.3.18 (Hardware
amount of time
amount
We consider
of to to configuration).
complete.
time
a small
complete.
part ofpart
theofcartheassembly, consisting of 15 of tasks: installinstall
axles axles
(front(front
We consider a small car assembly, consisting 15 tasks:
and back), affix all
and back), four
affix all wheels (right(right
four wheels and left,andfront and back),
left, front tighten
and back), nuts for
tighten nutseach
for wheel,
each wheel,
Example 8.3.19 affix(Spreadsheets).
hubcaps, and inspect
affix hubcaps, the final
and inspect the assembly. We can
final assembly. Werepresent the tasks
can represent with 15
the tasks withvariables:
15 variables:
X =X{Axle F , Axle
= {Axle F ,B , Wheel
Axle RF , Wheel
B , Wheel LF , Wheel
RF , Wheel RB , Wheel
LF , Wheel LB , Nuts
RB , Wheel LB , RF , RF ,
Nuts
Example 8.3.20 (Transportation Nuts LF Nuts, Nuts
LF , RB
Nuts scheduling).
, Nuts
RB , LB
Nuts, Cap
LB ,RF , Cap
Cap RF ,LF
Cap , Cap
LF ,RB
Cap, Cap
RB ,LB , Inspect
Cap }. }.
LB , Inspect
The value of each
The value of variable is theistime
each variable the that
timethethattask
the starts. Next Next
task starts. we represent precedence
we represent precedence
PRECEDENCE constraints between individual tasks. Whenever a task T must occur before task T , and
PRECEDENCE
CONSTRAINTS
CONSTRAINTS constraints between individual tasks. Whenever a task 1 T1 must occur before task 2 T2 , and
task Ttask
1 takes duration
T1 takes d1 to dcomplete,
duration we add
1 to complete, weanaddarithmetic constraint
an arithmetic of theofform
constraint the form
T1 + T d1 +≤ dT12 ≤. T2 .
182 CHAPTER 8. CONSTRAINT SATISFACTION PROBLEMS
: 266 2025-05-14
: 267 2025-05-14
Note that the ideas are still the same as Example 8.1.7, but in constraint networks we have
a language to formulate things precisely.
: 268 2025-05-14
Definition 8.4.8. We call a consistent (total) assignment a solution for γ and γ itself solvable
or satisfiable.
: 269 2025-05-14
: 270 2025-05-14
184 CHAPTER 8. CONSTRAINT SATISFACTION PROBLEMS
: 271 2025-05-14
W A = red W A = red
N T = green N T = blue
W A = red W A = red
N T = green N T = green
Q = red Q = blue
: 272 2025-05-14
Backtracking Search
Assignments for different variables are independent!
e.g. first WA = red then NT = green vs. first NT = green then WA = red
; we only need to consider assignments to a single variable at each node
; b = d and there are dn leaves.
Definition 8.5.3. Depth first search for CSPs with single-variable assignment extensions
actions is called backtracking search.
Backtracking search is the basic uninformed algorithm for CSPs.
: 273 2025-05-14
: 274 2025-05-14
Backtracking in Australia
Example 8.5.5. We apply backtracking search for a map coloring problem:
186 CHAPTER 8. CONSTRAINT SATISFACTION PROBLEMS
Step 1:
Step 2:
8.5. CSP AS SEARCH 187
Step 3:
Step 4:
: 275 2025-05-14
: 276 2025-05-14
Intuition: By choosing a most constrained variable v first, we reduce the branching factor
(number of sub trees generated for v) and thus reduce the size of our search tree.
Extreme case: If #({d ∈ Dv | a ∪ {v 7→ d} is consistent}) = 1, then the value assignment
to v is forced by our previous choices.
Example 8.5.7. In step 3 of Example 8.5.5, there is only one remaining value for SA!
: 277 2025-05-14
Problem: Need a tie-breaker among MRV variables! (there was no preference in step 1,2)
Definition 8.5.8. The degree heuristic in backtracking search always chooses a most con-
straining variable, i.e. given an initial assignment a always pick a variable v with #({v ∈
(V \dom(a)) | C uv ∈ C}) maximal.
By choosing a most constraining variable first, we detect inconsistencies earlier on and thus
reduce the size of our search tree.
Commonly used strategy combination: From the set of most constrained variable, pick
a most constraining variable.
Example 8.5.9.
: 278 2025-05-14
Where in Example 8.5.9 does the most constraining variable play a role in the choice? SA (only
possible choice), NT (all choices possible except WA, V, T). Where in the illustration does most
constrained variable play a role in the choice? NT (all choices possible except T), Q (only Q and
WA possible).
By choosing the least constraining value first, we increase the chances to not rule out the
solutions below the current node.
Example 8.5.11.
: 279 2025-05-14
: 280 2025-05-14
190 CHAPTER 8. CONSTRAINT SATISFACTION PROBLEMS
Suggested Reading: p
• Chapter 6: Constraint Satisfaction Problems, Sections 6.1 and 6.3, in [RusNor:AIMA09].
– Compared to our treatment of the topic “Constraint Satisfaction Problems” (chapter 8 and
chapter 9), RN covers much more material, but less formally and in much less detail (in par-
ticular, my slides contain many additional in-depth examples). Nice background/additional
reading, can’t replace the lectures.
– Section 6.1: Similar to our “Introduction” and “Constraint Networks”, less/different examples,
much less detail, more discussion of extensions/variations.
– Section 6.3: Similar to my “Naïve Backtracking” and “Variable- and Value Ordering”, with
less examples and details; contains part of what we cover in chapter 9 (RN does inference
first, then backtracking). Additional discussion of backjumping.
Chapter 9
Constraint Propagation
In this chapter we discuss another idea that is central to symbolic AI as a whole. The
first component is that with the factored state representations, we need to use a representation
language for (sets of) states. The second component is that instead of state-level search, we can
graduate to representation-level search (inference), which can be much more efficient that state
level search as the respective representation language actions correspond to groups of state-level
actions.
9.1 Introduction
Illustration: Constraint Propagation
Example 9.1.1. A constraint
204 network γ: Chapter 6. Constraint Satisfaction Problems
NT
Q
Northern WA
Territory
Queensland
Western
Australia
SA NSW
South
Australia New
South V
Wales
Victoria
Tasmania
T
(a) (b)
Figure 6.1 (a) The principal states and territories of Australia. Coloring this map can
Example 9.1.2. C WAQ := “=”. If WA and Q are assigned different colors, then NT must
immediately discard further refinements of the partial assignment. Furthermore, we can see
why the assignment is not a solution—we see which variables violate a constraint—so we can
be assigned the 3rd color, leaving no color for SA. focus attention on the variables that matter. As a result, many problems that are intractable
for regular state-space search can be solved quickly when formulated as a CSP.
Illustration: Decomposition
CONSTRAINTS
task T1 takes duration d1 to complete, we add an arithmetic constraint of the form
T1 + d1 ≤ T2 .
191
192 204
CHAPTERChapter
9. [Link] PROPAGATION
Constraint Satisfaction Problems
NT
Q
Northern WA
Territory
Queensland
Western
Australia
SA NSW
South
Australia New
South V
Wales
Victoria
Tasmania
T
(a) (b)
Figure 6.1 (a) The principal states and territories of Australia. Coloring this map can
Tasmania is not adjacent to any other state. Thus we can color Australia first, and assign
immediately discard further refinements of the partial assignment. Furthermore, we can see
why the assignment is not a solution—we see which variables violate a constraint—so we can
an arbitrary color to Tasmania afterwards. focus attention on the variables that matter. As a result, many problems that are intractable
for regular state-space search can be solved quickly when formulated as a CSP.
Constraint propagation: How does inference work in principle? What are relevant practical
aspects?
Arc consistency: How to make inferences between variables whose value is not fixed yet?
Details a state of the art inference method.
Decomposition: Constraint graphs, and two simple cases
How to capture dependencies in a constraint network? What are “simple cases”?
Basic results on this subject.
Cutset conditioning: What if we’re not in a simple case?
Outlines the most easily understandable technique for decomposition in the general case.
: 283 2025-05-14
Example 9.2.2. It’s what you do all the time when playing SuDoKu:
: 284 2025-05-14
v1 v1
γ red red
γ′
blue blue
̸= ̸= ̸= ̸=
v1 v1
γ red red
γ′
blue blue
̸= ̸= ̸= ̸=
: 285 2025-05-14
Tightness
194 CHAPTER 9. CONSTRAINT PROPAGATION
v1 v1
γ red red
γ′
blue blue
̸= ̸= ̸= ̸=
v1 v1
γ red red
γ′
blue blue
̸= ̸= ̸= ̸=
v1 v1
γ red red
γ′
blue blue
̸= ̸= ̸=
: 286 2025-05-14
v1 v1
γ red red
γ′
blue blue
̸= ̸= ̸= ̸=
: 287 2025-05-14
Idea: Encode variable assignments as unary constraints (i.e., for a(v) = d, set the unary con-
straint Dv = {d}), so that inference reasons about the network restricted to the commitments
already made in the search.
: 288 2025-05-14
: 289 2025-05-14
return
I Example 3.1.
WA Intelligenz
Kohlhase: Künstliche NT 1 Q NSW
295 V SA
July 5, 2018 T
WA NT Q NSW V SA T
: 290 2025-05-14
Note: It’s a bit strange that we start with d′ here; this is to make link to arc consistency –
coming up next – as obvious as possible (same notations u, and d vs. v and d′ ).
Incremental computation: Instead of the first for-loop in Definition 9.3.3, use only the inner
one every time a new assignment a(v) = d′ is added.
Practical Properties:
Cheap but useful inference method.
Rarely a good idea to not use forward checking (or a stronger inference method subsuming
it).
Up next: A stronger inference method (subsuming forward checking).
Definition 9.3.7. Let p and q be inference procedures, then p subsumes q, if p(γ)⊑q(γ) for
any input γ.
: 291 2025-05-14
v1 v1 v1
1 1 1
v1 < v 2 v1 < v2 v1 < v2
v2 123 1 2 3 v3 v2 23 1 2 3 v3 v2 23 3 v3
v2 < v3 v2 < v3 v2 < v3
We could do better here: value 3 for v2 is not consistent with any remaining value for v3 ;
it can be removed!
But forward checking does not catch this.
: 292 2025-05-14
Intuition: Arc consistency = b for every domain value and constraint, at least one value on
the other side of the constraint “works”.
Note the asymmetry between u and v: arc consistency is directed.
: 293 2025-05-14
v1 v1 v1
1 1 1
v1 < v 2 v1 < v2 v1 < v2
v2 123 1 2 3 v3 v2 23 1 2 3 v3 v2 23 3 v3
v2 < v3 v2 < v3 v2 < v3
: 294 2025-05-14
Examplereturn
9.4.6.
I Example 3.1.
WA NT Q NSW V SA T
WA NT Q NSW V SA T
;?
;?
Forward checking
Note: SA is not
Kohlhase: makes inferences
arc Intelligenz
Künstliche consistent1 onlyto“from
relative NT inassigned
295 to5, unassigned”
3rd [Link] 2018 variables.
Kohlhase: Künstliche Intelligenz 1 297 July 5, 2018
: 295 2025-05-14
200 CHAPTER 9. CONSTRAINT PROPAGATION
Proof sketch: If, for d ∈ Du , there does not exist a value d′ ∈ Dv such that (d,d′ ) ∈ C uv ,
then u = d cannot be part of any solution.
Observation 9.4.8. AC(γ) subsumes forward checking: AC(γ)⊑ForwardChecking(γ).
Proof: Recall from slide 286 that γ ′ ⊑γ means γ ′ is tighter than γ.
1. Forward checking removes d from Du only if there is a constraint C uv such that Dv = {d′ }
(i.e. when v was assigned the value d′ ), and (d,d′ ) ̸∈ C uv .
2. Clearly, enforcing arc consistency of u relative to v removes d from Du as well.
□
: 296 2025-05-14
Lemma 9.4.10. If d is maximal domain size in γ and the test “(d,d′ ) ∈ C uv ?” has time
complexity O(1), then the running time of Revise(γ, u, v) is O(d2 ).
Example 9.4.11. Revise(γ, v 3 , v 2 )
v1 v1
1 1
v1 < v2 v1 < v 2
v2 23 123 v3 v2 23 123 v3
v2 < v3 v2 < v3
9.4. ARC CONSISTENCY 201
v1 v1
1 1
v1 < v2 v1 < v 2
v2 23 123 v3 v2 23 23 v3
v2 < v3 v2 < v3
v1 v1
1 1
v1 < v2 v1 < v 2
v2 23 23 v3 v2 23 3 v3
v2 < v3 v2 < v3
v1
v1 < v2
v2 23 3 v3
v2 < v3
: 297 2025-05-14
Redundant computations: u and v are revised even if theirdomains haven’t changed since
the last time.
Better algorithm avoiding this: AC 3 (coming up)
: 298 2025-05-14
: 299 2025-05-14
AC-3: Example
Example 9.4.15. y div x = 0: y modulo x is 0, i.e., y is divisible by x
9.4. ARC CONSISTENCY 203
v1
25
v 2 div v 1 = 0 v 3 div v 1 = 0
M
v2 24 25 v3 (v 2 ,v 1 )
(v 1 ,v 2 )
(v 3 ,v 1 )
(v 1 ,v 3 )
v1
25
v 2 div v 1 = 0 v 3 div v 1 = 0
M
v2 24 25 v3 (v 2 ,v 1 )
(v 1 ,v 2 )
(v 3 ,v 1 )
(v 1 ,v 3 )
v1
25
v 2 div v 1 = 0 v 3 div v 1 = 0
M
v2 24 25 v3 (v 2 ,v 1 )
(v 1 ,v 2 )
(v 3 ,v 1 )
204 CHAPTER 9. CONSTRAINT PROPAGATION
v1
25
v 2 div v 1 = 0 v 3 div v 1 = 0
M
v2 24 25 v3 (v 2 ,v 1 )
(v 1 ,v 2 )
v1
v 2 div v 1 = 0 v 3 div v 1 = 0
M
v2 24 25 v3 (v 2 ,v 1 )
v1
v 2 div v 1 = 0 v 3 div v 1 = 0
M
v2 24 25 v3 (v 2 ,v 1 )
(v 3 ,v 1 )
9.4. ARC CONSISTENCY 205
v1
v 2 div v 1 = 0 v 3 div v 1 = 0
M
v2 24 25 v3 (v 2 ,v 1 )
(v 3 ,v 1 )
v1
v 2 div v 1 = 0 v 3 div v 1 = 0
M
v2 24 2 v3 (v 2 ,v 1 )
v1
v 2 div v 1 = 0 v 3 div v 1 = 0
M
v2 24 2 v3
: 300 2025-05-14
AC-3: Runtime
Theorem 9.4.16 (Runtime of AC-3). Let γ := ⟨V , D, C , C , C , V , E ⟩ be a constraint
network with m constraints, and maximal domain size d. Then AC − 3(γ) runs in time
O(md3 ).
1. Each call to Revise(γ, u, v) takes time O(d2 ) so it suffices to prove that at most O(md)
of these calls are made.
2. The number of calls to Revise(γ, u, v) is the number of iterations of the while-loop, which
is at most the number of insertions into M .
3. Consider any constraint C uv .
4. Two variable pairs corresponding to C uv are inserted in the for-loop. In the while loop, if
a pair corresponding to C uv is inserted into M , then
5. beforehand the domain of either u or v was reduced, which happens at most 2d times.
6. Thus we have O(d) insertions per constraint, and O(md) insertions overall, as desired.
□
: 301 2025-05-14
: 302 2025-05-14
Problem Structure
9.5. DECOMPOSITION: CONSTRAINT GRAPHS, AND THREE SIMPLE CASES 207
T
E.g., n = 80, d = 2, c = 20 Tasmania
(a) (b)
b 4 billion years at
280 = 106.1million
Figure (a) The nodes/sec
principal states and territories of Australia. Coloring this map can
be viewed as a constraint satisfaction problem (CSP). The goal is to assign colors to each
b 0.4 seconds at 10 million nodes/sec
4 · 220 = region so that no neighboring regions have the same color. (b) The map-coloring problem
represented as a constraint graph.
: immediately discard
303 further refinements of the partial assignment. Furthermore,
2025-05-14 we can see
why the assignment is not a solution—we see which variables violate a constraint—so we can
focus attention on the variables that matter. As a result, many problems that are intractable
for regular state-space search can be solved quickly when formulated as a CSP.
“Decomposition” 1.0: Disconnected Constraint
6.1.2 Example problem: Graphs
Job-shop scheduling
Factories have the problem of scheduling a day’s worth of jobs, subject to various constraints.
In practice, many of these problems are solved with CSP techniques. Consider the problem of
Theorem 9.5.2 (Disconnectedscheduling
Constraint
the assemblyGraphs).
of a car. The whole := ⟨V of, D,
Letjobγis composed tasks,C ,C
and we,can
Cmodel E ⟩ be
, V , each
a constraint network. Let
S ai be a solution
task as a variable,to each
where connected
the value of each variable is the time thatγthe
component i of
task the
starts, constraint
expressed
as an integer number of minutes. Constraints can assert that one task must occur before
graph of γ. Then a := i ai is aanother—for to γ.a wheel must be installed before the hubcap is put on—and that only
solutionexample,
so many tasks can go on at once. Constraints can also specify that a task takes a certain
Proof: amount of time to complete.
We consider a small part of the car assembly, consisting of 15 tasks: install axles (front
and back), affix all four wheels (right and left, front and back), tighten nuts for each wheel,
1. a satisfies all C uv where u and v are inside the same connected component.
affix hubcaps, and inspect the final assembly. We can represent the tasks with 15 variables:
2. The latter is the case for all C uv . X = {Axle F , Axle B , Wheel RF , Wheel LF , Wheel RB , Wheel LB , Nuts RF ,
Nuts LF , Nuts RB , Nuts LB , Cap RF , Cap LF , Cap RB , Cap LB , Inspect } .
The value of each variable is the time that the task starts. Next we represent precedence
3. If two parts of γ are PRECEDENCE
not connected,
CONSTRAINTS
then they are independent.
constraints between individual tasks. Whenever a task T1 must occur before task T2 , and
task T1 takes duration d1 to complete, we add an arithmetic constraint of the form
T1 + d1 ≤ T2 . □
Example
204 9.5.3. Color Tasmania separately
Chapter 6. inSatisfaction
Constraint Australia Problems
NT
Q
Northern WA
Territory
Queensland
Western
Australia
SA NSW
South
Australia New
South V
Wales
Victoria
Tasmania
T
(a) (b)
Figure 6.1 (a) The principal states and territories of Australia. Coloring this map can
Example 9.5.4
be viewed (Doing the Numbers).
as a constraint satisfaction problem (CSP). The goal is to assign colors to each
region so that no neighboring regions have the same color. (b) The map-coloring problem
represented as a constraint graph.
γ with n = 40 variables, each domain size k = 2. Four separate connected components
immediately discard further refinements of the partial assignment. Furthermore, we can see
each of
why size 10. is not a solution—we see which variables violate a constraint—so we can
the assignment
focus attention on the variables that matter. As a result, many problems that are intractable
Reduction
for regularof worst-case
state-space search can bewhen using
solved quickly decomposition:
when formulated as a CSP.
: 304 2025-05-14
Tree-structured CSPs
Definition 9.5.6. We call a CSP tree-structured, iff its constraint graph is acyclic
Theorem 9.5.7. Tree-structured CSP can be solved in O(nd2 ) time.
Compare to general CSPs, where worst case time is O(dn ).
This property also applies to logical and probabilistic reasoning: an important example of the
relation between syntactic restrictions and the complexity of reasoning.
: 305 2025-05-14
: 306 2025-05-14
Example 9.5.9.
Definition 9.5.10. Cutset conditioning: instantiate (in all ways) a set of variables such that
the remaining constraint graph is a tree.
Cutset size c ; running time O(dc (n − c)d2 ), very fast for small c.
: 307 2025-05-14
NT
Q
Northern WA
Territory
Queensland
Western
Australia
SA NSW
South
Australia New
South V
Wales
Victoria
T
Example 9.5.12. Australia is not acyclic. (But see next section)
Tasmania
(a) (b)
Example 9.5.13 (Doing the Numbers). Figure 6.1 (a) The principal states and territories of Australia. Coloring this map can
be viewed as a constraint satisfaction problem (CSP). The goal is to assign colors to each
region so that no neighboring regions have the same color. (b) The map-coloring problem
represented as a constraint graph.
γ with n = 40 variables, each domain size k = 2. Acyclic constraint graph.
immediately discard further refinements of the partial assignment. Furthermore, we can see
Reduction of worst-case when using decomposition:
why the assignment is not a solution—we see which variables violate a constraint—so we can
focus attention on the variables that matter. As a result, many problems that are intractable
No decomposition: 240 . for regular state-space search can be solved quickly when formulated as a CSP.
: 309 2025-05-14
a We
assume here that γ’s constraint graph is connected. If it is not, do this and the following for each
component separately.
AcyclicCG(γ): Example
Example 9.5.16 (AcyclicCG() execution).
v1
123
v1 < v2
v2 123 123 v3
v2 < v3
v1
123
v1 < v2
v2 123 123 v3
v2 < v3
Input network γ.
Step 1: Directed tree for root v 1 .
9.6. CUTSET CONDITIONING 211
v1
123
v1 < v2
v2 12 123 v3
v2 < v3
Step 2: Order v 1 , v 2 , v 3 .
v1
v1 < v2
v2 12 123 v3
v2 < v3
v1 < v2
v2 2 123 v3
v2 < v3
v1 < v2
v2 2 3 v3
v2 < v3
v1 < v2
v2 2 3 v3
v2 < v3
: 310 2025-05-14
: 311 2025-05-14
Remark 9.6.5. Finding optimal cutsets is NP hard, but good approximations exist.
: 312 2025-05-14
Value selection by min conflicts heuristic: choose value that violates the fewest constraints
i.e., hill climb with h(n):=total number of violated constraints.
: 313 2025-05-14
Example: 4-Queens
States: 4 queens in 4 columns (44 = 256 states)
Actions: Move queen in column
: 314 2025-05-14
Performance of min-conflicts
Given a random initial state, can solve n-queens in almost constant time for arbitrary n with
high probability (e.g., n = 10,000,000)
The same appears to be true for any randomly-generated CSP except in a narrow range of
the ratio
number of constraints
R=
number of variables
214 CHAPTER 9. CONSTRAINT PROPAGATION
: 315 2025-05-14
Arc consistency removes values that do not comply with any value still available at the other
end of a constraint. This subsumes forward checking.
The constraint graph captures the dependencies between variables. Separate connected com-
ponents can be solved independently. Networks with acyclic constraint graphs can be solved
in low order polynomial time.
A cutset is a subset of variables removing which renders the constraint graph acyclic. Cutset
conditioning backtracks only on such a cutset, and solves a sub-problem with acyclic constraint
graph at each search leaf.
: 316 2025-05-14
Backjumping: Like backtracking search, but with ability to back up across several levels
(to a previous variable assignment identified to be responsible for failure).
9.8. CONCLUSION & SUMMARY 215
: 317 2025-05-14
Suggested Reading:
217
219
This part of the course introduces representation languages and inference methods for
structured state representations for agents: In contrast to the atomic and factored state repre-
sentations from ???, we look at state representations where the relations between objects are not
determined by the problem statement, but can be determined by inference-based methods, where
the knowledge about the environment is represented in a formal langauge and new knowledge is
derived by transforming expressions of this language.
We look at propositional logic – a rather weak representation langauge – and first-order logic
– a much stronger one – and study the respective inference procedures. In the end we show that
computation in Prolog is just an inference process as well.
220
Chapter 10
: 318 2025-05-14
221
222 CHAPTER 10. PROPOSITIONAL LOGIC & REASONING, PART I: PRINCIPLES
percepts and could explore the world via actions. The main difference is that we use it as an agent
environment in this course.
Definition 10.1.2 (Actions). The agent can perform the following actions: goForward,
turnRight (by 90◦ ), turnLeft (by 90◦ ), shoot arrow in direction you’re facing (you got
exactly one arrow), grab an object in current cell, leave cave if you’re in cell [1, 1].
Definition 10.1.3 (Initial and Terminal States). Initially, the agent is in cell [1, 1] facing
east. If the agent falls down a pit or meets live Wumpus it dies.
Definition 10.1.4 (Percepts). The agent can experience the following percepts: stench,
breeze, glitter, bump, scream, none.
Cell adjacent (i.e. north, south, west, east) to Wumpus: stench (else: none).
Cell adjacent to pit: breeze (else: none).
Cell that contains gold: glitter (else: none).
You walk into a wall: bump (else: none).
Wumpus shot by arrow: scream (else: none).
: 319 2025-05-14
The game is complex enough to warrant structured state representations and can easily be extended
to include uncertainty and non-determinism later.
As our focus is on inference processes here, let us see how a human player would reason when
entering the Wumpus world. This can serve as a model for designing our artificial agents.
(1) Initial state (2) One step to right (3) Back, and up to [1,2]
10.1. INTRODUCTION: INFERENCE WITH STRUCTURED STATE REPRESENTATIONS223
Note: The agent has more knowledge than just the percepts ⇝ inference!
: 320 2025-05-14
Let us now look into what kind of agent we would need to be successful in the Wumpus world:
it seems reasonable that we should build on a model-based agent and specialize it to structured
state representations and inference.
Sensors
State
How the world evolves What the world
is like now
Environment
What my actions do
Agent Actuators
The formal language of the logical system acts as a world description language. Agent
function: function M ODEL -BASED -R EFLEX -AGENT( percept ) returns an action
persistent: state, the agent’s current conception of the world state
function KB−AGENT (percept) returns
model , a description of howan
the action
next state depends on current state and action
persistent: KB, a knowledge base
rules, a set of condition–action rules
action, the most recent action, initially none
t, a counter, initially 0, indicating time
state ← U PDATE -S TATE(state, action , percept , model )
TELL(KB, MAKE−PERCEPT−SENTENCE(percept,t))
rule ← RULE -M ATCH(state, rules)
action := ASK(KB, action ←MAKE−ACTION−QUERY(t))
[Link]
return action
TELL(KB, MAKE−ACTION−SENTENCE(action,t))
t := t+1 Figure 2.12 A model-based reflex agent. It keeps track of the current state of the world,
return action using an internal model. It then chooses an action in the same way as the reflex agent.
Definition 10.1.12. The process of representing a natural language text in the formal
language of a logical system is called formalization.
Observation: Formalizing a NL text or utterance makes it machine-actionable. (the
ultimate purpose of AI)
: 322 2025-05-14
It is critical to understand that while PL0 as a logical system is given once and for all, the agent
designer still has to formalize the situation (here the Wumpus world) in the world description
language (here PL0 ; but we will look at more expressive logical systems below). This formalization
is the seed of the knowledge base, the logic-based agent can then add to via its percepts and action
descriptions, and that also forms the basis of its inferences. We will look at this aspect now.
Definition 10.1.14. Deduction: Which formulas B can be derived from A using a set C of
inference rules (a calculus), written A⊢C B?
A A⇒B
Example 10.1.15. If C contains then P, P ⇒ Q⊢C Q
B
Intuition: Deduction =b process in an actual computer trying to reason about entailment.
E.g. a mechanical process attempting to determine Wumpus position.
: 323 2025-05-14
: 324 2025-05-14
Syntax: Atomic propositions that can be either true or false, connected by “and, or, and
not”.
Semantics: Assign value to every proposition, evaluate connectives.
Applications: Despite its simplicity, widely applied!
: 325 2025-05-14
226 CHAPTER 10. PROPOSITIONAL LOGIC & REASONING, PART I: PRINCIPLES
Next Section (chapter 13): The Davis Putnam procedure and clause learning; practical
problem structure.
State-of-the-art algorithms for reasoning about propositional logic, and an important ob-
servation about how they behave.
: 326 2025-05-14
Killing a Wumpus: How can we use all this to figure out where the Wumpus is?
Coming back to our introductory example.
: 327 2025-05-14
Definition 10.2.1 (Syntax). The formulae of propositional logic (write PL0 ) are made up
from
propositional variables: V0 := {P , Q, R, P 1 , P 2 , . . .} (countably infinite)
A propositional signature: constants/constructors called connectives: Σ0 := {T , F , ¬, ∨, ∧, ⇒, ⇔, . . .}
We define the set wff 0 (V0 ) of well-formed propositional formulae (wffs) as
propositional variables,
the logical constants T and F ,
10.2. PROPOSITIONAL LOGIC (SYNTAX/SEMANTICS) 227
negations ¬A,
conjunctions A ∧ B(A and B are called conjuncts),
disjunctions A ∨ B (A and B are called disjuncts),
implications A ⇒ B, and
equivalences (or biimplications). A ⇔ B,
where A, B ∈ wff 0 (V0 ) themselves.
Example 10.2.2. P ∧ Q, P ∨ Q, ¬P ∨ Q ⇔ P ⇒ Q ∈ wff 0 (V0 )
Definition 10.2.3. Propositional formulae without connectives are called atomic (or an
atoms) and complex otherwise.
: 328 2025-05-14
We can also express the formal language introduced by ??? as a context-free grammar.
: 329 2025-05-14
Propositional logic is a very old and widely used logical system. So it should not be surprising
that there are other notations for the connectives than the ones we are using in AI-2. We list the
most important ones here for completeness.
: 330 2025-05-14
These notations will not be used in AI-2, but sometimes appear in the literature.
228 CHAPTER 10. PROPOSITIONAL LOGIC & REASONING, PART I: PRINCIPLES
The semantics of PL0 is defined relative to a model, which consists of a universe of discourse and
an interpretation function that we specify now.
Warning: For the official semantics of PL0 we will separate the tasks of giving meaning to
connectives and propositional variables to different mappings.
This will generalize better to other logical systems. (and thus applications)
Definition 10.2.4. A model M := ⟨D0 , I⟩ for propositional logic consists of
the universe D0 = {T, F}
the interpretation I that assigns values to essential connectives.
I(¬) : D0 → D0 ; T 7→ F, F 7→ T
I(∧) : D0 × D0 → D0 ; ⟨α, β⟩ 7→ T, iff α = β = T
We call a constant a logical constant, iff its value is fixed by the interpretation.
Treat the other connectives as abbreviations, e.g. A ∨ B=b ¬(¬A ∧ ¬B) and A ⇒ B= b
¬A ∨ B, and T = b P ∨ ¬P (only need to treat ¬, ∧ directly)
Note: PL0 is a single-model logical system with canonical model ⟨D0 , I⟩.
: 331 2025-05-14
We have a problem in the exposition of the theory here: As PL0 semantics only has a single,
canonical model, we could simplify the exposition by just not mentioning the universe and inter-
pretation function. But we choose to expose both of them in the construction, since other versions
of propositional logic – in particular the system PLnq below – that have a choice of models as they
use a different distribution of the representation among constants and variables.
: 332 2025-05-14
In particular in a interpretation-less exposition of propositional logic would have elided the ho-
momorphic construction of the value function and could have simplified the recursive cases in
Definition 10.2.6 to I φ (A ∧ B) = T, iff I φ (A) = T = I φ (B).
But the homomorphic construction via I(∧) is standard to definitions in other logical systems
and thus generalizes better.
Computing Semantics
Example 10.2.8. Let φ := [T/P 1 ], [F/P 2 ], [T/P 3 ], [F/P 4 ], . . . then
I φ (P 1 ∨ P 2 ∨ ¬(¬P 1 ∧ P 2 ) ∨ P 3 ∧ P 4 )
= I(∨)(I φ (P 1 ∨ P 2 ), I φ (¬(¬P 1 ∧ P 2 ) ∨ P 3 ∧ P 4 ))
= I(∨)(I(∨)(I φ (P 1 ), I φ (P 2 )), I(∨)(I φ (¬(¬P 1 ∧ P 2 )), I φ (P 3 ∧ P 4 )))
= I(∨)(I(∨)(φ(P 1 ), φ(P 2 )), I(∨)(I(¬)(I φ (¬P 1 ∧ P 2 )), I(∧)(I φ (P 3 ), I φ (P 4 ))))
= I(∨)(I(∨)(T, F), I(∨)(I(¬)(I(∧)(I φ (¬P 1 ), I φ (P 2 ))), I(∧)(φ(P 3 ), φ(P 4 ))))
= I(∨)(T, I(∨)(I(¬)(I(∧)(I(¬)(I φ (P 1 )), φ(P 2 ))), I(∧)(T, F)))
= I(∨)(T, I(∨)(I(¬)(I(∧)(I(¬)(φ(P 1 )), F)), F))
= I(∨)(T, I(∨)(I(¬)(I(∧)(I(¬)(T), F)), F))
= I(∨)(T, I(∨)(I(¬)(I(∧)(F, F)), F))
= I(∨)(T, I(∨)(I(¬)(F), F))
= I(∨)(T, I(∨)(T, F))
= I(∨)(T, T)
= T
What a mess!
: 333 2025-05-14
Now we will also review some propositional identities that will be useful later on. Some of them we
have already seen, and some are new. All of them can be proven by simple truth table arguments.
Propositional Identities
Definition 10.2.9. We have the following identities in propositional logic:
Idea: How about using these as inference component (simplification) to simplify calculations
like the one in ???. (see below)
230 CHAPTER 10. PROPOSITIONAL LOGIC & REASONING, PART I: PRINCIPLES
: 334 2025-05-14
We will now use the distribution of values of a propositional formula under all variable assignments
to characterize them semantically. The intuition here is that we want to understand theorems,
examples, counterexamples, and inconsistencies in mathematics and everyday reasoning1 .
The idea is to use the formal language of propositional formulae as a model for mathematical
language. Of course, we cannot express all of mathematics as propositional formulae, but we can
at least study the interplay of mathematical statements (which can be true or false) with the
copula “and”, “or” and “not”.
: 335 2025-05-14
Let us now see how these semantic properties model mathematical practice.
In mathematics we are interested in assertions that are true in all circumstances. In our model
of mathematics, we use variable assignments to stand for “circumstances”. So we are interested
in propositional formulae which are true under all variable assignments; we call them valid. We
often give examples (or show situations) which make a conjectured formula false; we call such
examples counterexamples, and such assertions falsifiable. We also often give examples for certain
formulae to show that they can indeed be made true (which is not the same as being valid yet);
such assertions we call satisfiable. Finally, if a formula cannot be made true in any circumstances
we call it unsatisfiable; such assertions naturally arise in mathematical practice in the form of
refutation proofs, where we show that an assertion (usually the negation of the theorem we want
to prove) leads to an obviously unsatisfiable conclusion, showing that the negation of the theorem
is unsatisfiable, and thus the theorem valid.
1 Here (and elsewhere) we will use mathematics (and the language of mathematics) as a test tube for under-
standing reasoning, since mathematics has a long history of studying its own reasoning processes and assumptions.
10.2. PROPOSITIONAL LOGIC (SYNTAX/SEMANTICS) 231
: 336 2025-05-14
Let us finally test our intuitions about propositional logic with a “real-world example”: a logic
puzzle, as you could find it in a Sunday edition of the local newspaper.
3. 1. together with 2.2a entails that ai(x) ⇒ bla(x) for every x ∈ {S, N , J},
4. thus ¬bla(S) ∧ ¬bla(J) by 2.2c and 2.2b and
5. so ¬ai(S) ∧ ¬ai(J) by 3. and 4.
6. With 2. the latter entails ai(N ).
: 337 2025-05-14
The example shows that puzzles like that are a bit difficult to solve without writing things down.
But if we formalize the situation in PL0 , then we can solve the puzzle quite handily with inference.
232 CHAPTER 10. PROPOSITIONAL LOGIC & REASONING, PART I: PRINCIPLES
Note that we have been a bit generous with the names of propositional variables; e.g. bla(x),
where x ∈ {S, N , J}, to keep the representation small enough to fit on the slide. This does not
hinder the method in any way.
Sensors
State
How the world evolves What the world
is like now
Environment
What my actions do
Agent Actuators
The formal language of the logical system acts as a world description language. Agent
function: function M ODEL -BASED -R EFLEX -AGENT( percept ) returns an action
persistent: state, the agent’s current conception of the world state
function KB−AGENT (percept) returns
model , a description of howan
the action
next state depends on current state and action
persistent: KB, a knowledge base
rules, a set of condition–action rules
action, the most recent action, initially none
t, a counter, initially 0, indicating time
state ← U PDATE -S TATE(state, action , percept , model )
TELL(KB, MAKE−PERCEPT−SENTENCE(percept,t))
rule ← RULE -M ATCH(state, rules)
action := ASK(KB, action ←MAKE−ACTION−QUERY(t))
[Link]
return action
TELL(KB, MAKE−ACTION−SENTENCE(action,t))
t := t+1 Figure 2.12 A model-based reflex agent. It keeps track of the current state of the world,
return action using an internal model. It then chooses an action in the same way as the reflex agent.
K S
P ⇒Q⇒P (P ⇒ Q ⇒ R) ⇒ (P ⇒ Q) ⇒ P ⇒ R
A⇒B A A
MP Subst
B [B/X](A)
: 339 2025-05-14
This is indeed a very simple formal system, but it has all the required parts:
• A formal language: expressions built up from variables and implications.
• A semantics: given by the obvious interpretation function
• A calculus: given by the two axioms and the two inference rules.
The calculus gives us a set of rules with which we can derive new formulae from old ones. The
axioms are very simple rules, they allow us to derive these two formulae in any situation. The
proper inference rules are slightly more complicated: we read the formulae above the horizontal
line as assumptions and the (single) formula below as the conclusion. An inference rule allows us
to derive the conclusion, if we have already derived the assumptions.
Now, we can use these inference rules to perform a proof – a sequence of formulae that can be
derived from each other. The representation of the proof in the slide is slightly compactified to fit
onto the slide: We will make it more explicit here. We first start out by deriving the formula
(P ⇒ Q ⇒ R) ⇒ (P ⇒ Q) ⇒ P ⇒ R (10.1)
which we can always do, since we have an axiom for this formula, then we apply the rule Subst,
where A is this result, B is C, and X is the variable P to obtain
(C ⇒ Q ⇒ R) ⇒ (C ⇒ Q) ⇒ C ⇒ R (10.2)
Next we apply the rule Subst to this where B is C ⇒ C and X is the variable Q this time to obtain
(C ⇒ (C ⇒ C) ⇒ R) ⇒ (C ⇒ C ⇒ C) ⇒ C ⇒ R (10.3)
234 CHAPTER 10. PROPOSITIONAL LOGIC & REASONING, PART I: PRINCIPLES
And again, we apply the rule Subst this time, B is C and X is the variable R yielding the first
formula in our proof on the slide. To conserve space, we have combined these three steps into one
in the slide. The next steps are done in exactly the same way.
In general, formulae can be used to represent facts about the world as propositions; they have a
semantics that is a mapping of formulae into the real world (propositions are mapped to truth
values.) We have seen two relations on formulae: the entailment relation and the derivation
relation. The first one is defined purely in terms of the semantics, the second one is given by a
calculus, i.e. purely syntactically. Is there any relation between these relations?
: 340 2025-05-14
Ideally, both relations would be the same, then the calculus would allow us to infer all facts
that can be represented in the given formal language and that are true in the real world, and only
those. In other words, our representation and inference is faithful to the world.
A consequence of this is that we can rely on purely syntactical means to make predictions
about the world. Computers rely on formal representations of the world; if we want to solve a
problem on our computer, we first represent it in the computer (as data structures, which can be
seen as a formal language) and do syntactic manipulations on these structures (a form of calculus).
Now, if the provability relation induced by the calculus and the validity relation coincide (this will
be quite difficult to establish in general), then the solutions of the program will be correct, and
we will find all possible ones. Of course, the logics we have studied so far are very
simple, and not able to express interesting facts about the world, but we will study them as a
simple example of the fundamental problem of CS: How do the formal representations correlate
with the real world. Within the world of logics, one can derive new propositions (the
conclusions, here: “Socrates is mortal”) from given ones (the premises, here: “Every human is
mortal” and “Sokrates is human”). Such derivations are proofs.
In particular, logics can describe the internal structure of real-life facts; e.g. individual things,
actions, properties. A famous example, which is in fact as old as it appears, is illustrated in the
slide below.
: 341 2025-05-14
If a formal system is correct, the conclusions one can prove are true (= hold in the real world)
whenever the premises are true. This is a miraculous fact (think about it!)
: 342 2025-05-14
The most characteristic rule in the natural deduction calculus is the ⇒I a rule and the hypothetical
reasoning it introduce. ⇒I a corresponds to the mathematical way of proving an implication A⇒B:
We assume that A is true and show B from this local hypothesis. When we can do this we discharge
the assumption and conclude A ⇒ B.
Note that the local hypothesis is discharged by the rule ⇒I a , i.e. it cannot be used in any
other part of the proof. As the ⇒I a rules may be nested, we decorate both the rule and the
corresponding local hypothesis with a marker (here the number 1).
Let us now consider an example of hypothetical reasoning in action.
1
[(A ∧ B)]1 [(A ∧ B)]1 [A]
∧Er ∧El 2
B A [B]
∧I A
B∧A ⇒I 2
1
⇒I B⇒A
A∧B⇒B∧A ⇒I 1
A⇒B⇒A
: 343 2025-05-14
Here we see hypothetical reasoning with local local hypotheses at work. In the left example, we
assume the formula A ∧ B and can use it in the proof until it is discharged by the rule ∧El on
the bottom – therefore we decorate the hypothesis and the rule by corresponding numbers (here
the label “1”). Note the local assumption A ∧ B is local to the proof fragment delineated by the
corresponding (local) hypothesis and the discharging rule, i.e. even if this derivation is only a
fragment of a larger proof, then we cannot use its (local) hypothesis anywhere else.
Note also that we can use as many copies of the local hypothesis as we need; they are all
discharged at the same time.
In the right example we see that local hypotheses can be nested as long as they are kept local. In
10.4. PROPOSITIONAL NATURAL DEDUCTION CALCULUS 237
particular, we may not use the hypothesis B after the ⇒I 2 , e.g. to continue with a ⇒E.
One of the nice things about the natural deduction calculus is that the deduction theorem is
almost trivial to prove. In a sense, the triviality of the deduction theorem is the central idea of
the calculus and the feature that makes it so natural.
: 344 2025-05-14
Another characteristic of the natural deduction calculus is that it has inference rules (introduction
and elimination rules) for all connectives. So we extend the set of rules from ??? for disjunction,
negation and falsity.
Introduction Elimination
[A]1 [B]1
A∨B . .
. .
. .
A B C C
∨Il ∨Ir ∨E 1
A∨B A∨B C
[A]1 [A]1
. .
. .
. .
C ¬C ¬¬A
¬I 1 ¬E
¬A A
¬A A F
FI FE
F A
: 345 2025-05-14
Ax Ax
A∧B⊢A∧B A∧B⊢A∧B Ax
∧Er ∧El A, B ⊢ A
A∧B⊢B A∧B⊢A ⇒I
∧I A⊢B⇒A
A∧B⊢B∧A ⇒I
⇒I ⊢A⇒B⇒A
⊢A∧B⇒B∧A
Note: Even though the antecedent of a sequent is written like a sequences, it is actually
a set. In particular, we can permute and duplicate members at will.
: 346 2025-05-14
Γ⊢B
Ax weaken TND
Γ, A ⊢ A Γ, A ⊢ B Γ ⊢ A ∨ ¬A
Γ⊢A Γ⊢B Γ ⊢ A ∨ B Γ, A ⊢ C Γ, B ⊢ C
∨Il ∨Ir ∨E
Γ⊢A∨B Γ⊢A∨B Γ⊢C
Γ, A ⊢ B Γ⊢A⇒B Γ⊢A
⇒I ⇒E
Γ⊢A⇒B Γ⊢B
Γ, A ⊢ F Γ ⊢ ¬¬A
¬I ¬E
Γ ⊢ ¬A Γ⊢A
Γ ⊢ ¬A Γ ⊢ A Γ⊢F
FI FE
Γ⊢F Γ⊢A
: 347 2025-05-14
1. H1 ⊢ A1 (J 1 )
H1 ⊢ A1 H2 ⊢ A2
2. H2 ⊢ A2 (J 2 ) corresponds to R
H3 ⊢ A3
3. H3 ⊢ A3 (J 3 1, 2)
Example 10.4.11. We show a linearized version of the ND0 examples ???
Ax Ax
A∧B⊢A∧B A∧B⊢A∧B Ax
∧Er ∧El A, B ⊢ A
A∧B⊢B A∧B⊢A ⇒I
∧I A⊢B⇒A
A∧B⊢B∧A ⇒I
⇒I ⊢A⇒B⇒A
⊢A∧B⇒B∧A
: 348 2025-05-14
Each row in the table represents one inference step in the proof. It consists of line number (for
referencing), a formula for the statement, a justification via a ND inference rule (and the rows this
one is derived from), and finally a sequence of row numbers of proof steps that are local hypotheses
in effect for the current row.
This is essentially the same as PL0 , so we can reuse the calculi. (up next)
: 349 2025-05-14
: 350 2025-05-14
: 351 2025-05-14
PLnq Semantics
Definition 10.5.3. Domains D0 = {T, F} of truth values and Dι ̸= ∅ of individuals.
Definition 10.5.4. Interpretation I assigns values to constants, e.g.
: 352 2025-05-14
All of the definitions above are quite abstract, we now look at them again using a very concrete –
if somewhat contrived – example: The relevant parts are a universe D with four elements, and an
interpretation that maps the signature into individuals, functions, and predicates over D, which
are given as concrete sets.
: 353 2025-05-14
The example above also shows how we can compute of meaning by in a concrete model: we just
follow the evaluation rules to the letter.
We now come to the central technical result about PLnq : it is essentially the same as propositional
logic (PL0 ). We say that the two logic are isomorphic. Technically, this means that the formulae
of PLnq can be translated to PL0 and there is a corresponding model translation from the models
of PL0 to those of PLnq such that the respective notions of evaluation are assignped to each other.
Lemma 10.5.10. For every model M = ⟨D, I ⟩, there is a variable assignment φM , such
that I φM (A) = I(A).
Proof sketch: We just define φM (X) := I(θ−1
Σ (X)), then the assertion follows by induction
on A.
ψ 7→ Mψ
⟨Dψ , I ψ ⟩ V Σ → {T, F}
I ψ () I φM ()
θΣ
PLnq (Σ) PL0 (AΣ )
Note: This constellation with a language isomorphism and a corresponding model isomor-
phism (in converse direction) is typical for a logic isomorphism.
: 354 2025-05-14
The practical upshot of the commutative diagram from ??? is that if we have a way of computing
evaluation (or entailment for that matter) in PL0 , then we can “borrow” it for PLnq by composing
it with the language and model translations. In other words, we can reuse calculi and automated
theorem provers from PL0 for PLnq .
But we still have to provide the proof for ???, which we do now.
4.2. If A = ¬B, then I ψ (A) = T, iff I ψ (B) = F, iff I ψ (B) = I ψ (B), iff I ψ (A) = I ψ (A).
4.3. If A = B ∧ C then we argue similarly
6. Hence I ψ (A) = I ψ (A) for all PLnq formulae and we have concluded the proof.
10.6. CONCLUSION 243
: 355 2025-05-14
10.6 Conclusion
Summary
Sometimes, it pays off to think before acting.
In AI, “thinking” is implemented in terms of reasoning to deduce new knowledge from a
knowledge base represented in a suitable logic.
Logic prescribes a syntax for formulas, as well as a semantics prescribing which interpretations
satisfy them. A entails B if all interpretations that satisfy A also satisfy B. Deduction is the
process of deriving new entailed formulae.
Propositional logic formulae are built from atomic propositions, with the connectives “and”,
“or”, “not”.
: 356 2025-05-14
: 357 2025-05-14
Suggested Reading:
• Chapter 7: Logical Agents, Sections 7.1 – 7.5 [RusNor:AIMA09].
– Sections 7.1 and 7.2 roughly correspond to my “Introduction”, Section 7.3 roughly corresponds
to my “Logic (in AI)”, Section 7.4 roughly corresponds to my “Propositional Logic”, Section
7.5 roughly corresponds to my “Resolution” and “Killing a Wumpus”.
– Overall, the content is quite similar. I have tried to add some additional clarifying illustra-
tions. RN gives many complementary explanations, nice as additional background reading.
– I would note that RN’s presentation of resolution seems a bit awkward, and Section 7.5 con-
tains some additional material that is imho not interesting (alternate inference rules, forward
and backward chaining). Horn clauses and unit resolution (also in Section 7.5), on the other
hand, are quite relevant.
244 CHAPTER 10. PROPOSITIONAL LOGIC & REASONING, PART I: PRINCIPLES
Chapter 11
We will now take a more abstract view and introduce the necessary prerequisites of abstract
rule systems. We will also take the opportunity to discuss the quality criteria for calculi.
Observation: The set wff 0 (V0 ) of well-formed propositional formulae is a formal language
over the alphabet given by V0 , the connectives, and brackets.
: 358 2025-05-14
The notion of a logical system is at the basis of the field of logic. In its most abstract form, a
logical system consists of set of propositions, a class of models, and a satisfaction relation between
models and propositions. The satisfaction relation tells us when an expression is deemed true in
this model.
245
246 CHAPTER 11. FORMAL SYSTEMS
Logical Systems
Definition 11.0.1. A logical system (or simply a logic) is a triple S := ⟨L, M, ⊨⟩, where
1. L is a set of propositions,
2. M a set of models, and
3. a relation ⊨ ⊆ M × L called the satisfaction relation. We read M ⊨ A as M satisfies A
and correspondingly M ̸⊨ A as M falsifies A.
Example 11.0.2 (Propositional Logic). ⟨wff(ΣP L0 , V P L0 ), Ko , |=⟩ is a logical system, if
we define Ko := V0 ⇀ D0 (the set of variable assignments) and φ |= A iff I φ (A) = T.
Definition 11.0.3. Let ⟨L, M, ⊨⟩ be a logical system, M ∈ M a model and A ∈ L a
proposition. Then we say that A is
satisfied by M iff M ⊨ A.
satisfiable iff A is satisfied by some model.
unsatisfiable iff A is not satisfiable.
falsified by M iff M ̸⊨ A.
valid or unfalsifiable (write ⊨ A) iff A is satisfied by every model.
invalid or falsifiable (write ̸⊨ A) iff A is not valid.
: 359 2025-05-14
Let us now turn to the syntactical counterpart of the entailment relation: derivability in a calcu-
lus. Again, we take care to define the concepts at the general level of logical systems.
The intuition of a calculus is that it provides a set of syntactic rules that allow to reason by
considering the form of propositions alone. Such rules are called inference rules, and they can be
strung together to derivations — which can alternatively be viewed either as sequences of formulae
where all formulae are justified by prior formulae or as trees of inference rule applications. But we
can also define a calculus in the more general setting of logical systems as an arbitrary relation on
formulae with some general properties. That allows us to abstract away from the homomorphic
setup of logics and calculi and concentrate on the basics.
where A1 , . . ., An and C are schemata for words in L and N is a name. The Ai are called
assumptions of N , and C is called its conclusion.
Any n + 1-tuple
a1 . . . an
c
in N is called an application of N and we say that we apply N to a set M of words with
a1 , . . ., an ∈ M to obtain c.
Definition 11.0.6. An inference rule without assumptions is called an axiom.
Definition 11.0.7. A calculus (or inference system) is a formal language L equipped with a
set C of inference rules over L.
: 360 2025-05-14
With formula schemata we mean representations of sets of formulae, we use boldface uppercase
letters as (meta)-variables for formulae, for instance the formula schema A ⇒ B represents the set
of formulae whose head is ⇒.
Derivations
Definition [Link] L := ⟨L, ⊨⟩ be a logical system and C a calculus for L, then a C-
derivation of a proposition C ∈ L from a set H ⊆ L of hypotheses (write H⊢C C) is a
sequence A1 , . . ., Am of propositions
Am = C, (derivation culminates in C)
for all 1 ≤ i ≤ m, either Ai ∈ H, or (hypothesis)
Al1 . . . Alk
there is an inference rule in C with lj < i for all j ≤ k. (rule application)
Ai
We can also see a derivation as a derivation tree, where the Alj are the children of the node
Ai .
Example 11.0.9.
In the propositional Hilbert calculus H0 we have the K
derivation P ⊢H0 Q ⇒ P : the sequence is P ⇒ Q ⇒ P ⇒ Q ⇒ P P
MP
P , P , Q ⇒ P and the corresponding tree on the right. Q⇒P
: 361 2025-05-14
Inference rules are relations on formulae represented by formula schemata (where boldface, upper-
case letters are used as metavariables for formulae). For instance, in Example 11.0.9 the inference
A⇒B A
rule was applied in a situation, where the metavariables A and B were instantiated
B
by the formulae P and Q ⇒ P .
As axioms do not have assumptions, they can be added to a derivation at any time. This is just
what we did with the axioms in Example 11.0.9.
Formal Systems
Let ⟨L, ⊨⟩ be a logical system and C a calculus, then ⊢C is a derivation relation and thus
⟨L, |=, ⊨, ⊢C ⟩ a derivation system.
248 CHAPTER 11. FORMAL SYSTEMS
Therefore we will sometimes also call ⟨L, C , ⊨⟩ a formal system, iff L := ⟨L, ⊨⟩ is a logical
system, and C a calculus for L.
Definition 11.0.10. Let C be a calculus, then a C-derivation ∅⊢C A is called a proof of A
and if one exists (write ⊢C A) then A is called a C-theorem.
Definition 11.0.11. The act of finding a proof for A is called proving A.
Definition 11.0.12. An inference rule I is called admissible in a calculus C, if the extension
of C by I does not yield new theorems.
Definition 11.0.13. An inference rule
A1 . . . An
C
is called derivable (or a derived rule) in a calculus C, if there is a C-derivation A1 , . . ., An ⊢C C.
Observation 11.0.14. Derivable inference rules are admissible, but not the other way around.
: 362 2025-05-14
The notion of a formal system encapsulates the most general way we can conceptualize a logical
system with a calculus, i.e. a system in which we can do “formal reasoning”.
Chapter 12
: 363 2025-05-14
Unsatisfiability Theorem
Theorem 12.1.1 (Unsatisfiability Theorem). H ⊨ A iff H ∪ {¬A} is unsatisfiable.
Proof: We prove both directions separately
1. “⇒”: Say H ⊨ A
1.1. For any φ with φ |= H we have φ |= A and thus φ ̸|= (¬A).
3. “⇐”: Say H ∪ {¬A} is unsatisfiable.
3.1. For any φ with φ |= H we have φ ̸|= (¬A) and thus φ |= A.
□
: 364 2025-05-14
249
250 CHAPTER 12. MACHINE-ORIENTED CALCULI FOR PROPOSITIONAL LOGIC
Problem: ATP as a search problem does not admit good heuristics, since these need to
take the conjecture A into account.
Idea: Turn the search around – using the unsatisfiability theorem (Theorem 12.1.1).
Definition 12.1.5. For a given conjecture A and hypotheses H a test calculus T tries to
derive a refutation H, A⊢T ⊥ instead of H⊢A, where A is unsatisfiable iff A is valid and ⊥,
an “obviously” unsatisfiable proposition.
Observation: A test calculus C induces a search problem where the initial state is H ∪{¬A}
and S ∈ S is a goal state iff ⊥ ∈ S. (proximity of ⊥ easier for heuristics)
Searching for ⊥ admits simple heuristics, e.g. size reduction. (⊥ minimal)
: 365 2025-05-14
: 366 2025-05-14
The idea about literals is that they are atoms (the simplest formulae) that carry around their
intended truth value.
12.2. ANALYTICAL TABLEAUX 251
: 367 2025-05-14
Normal Forms
There are two quintessential normal forms for propositional formulae: (there are others as
well)
Definition 12.1.13. A formula is in conjunctive normal
^ _ form (CNF) if it is T or a conjunction
of disjunctions of literals: i.e. if it is of the form ni=1 mj=1 lij
i
Observation 12.1.15. Every formula has equivalent formulae in CNF and DNF.
: 368 2025-05-14
: 369 2025-05-14
Tableau calculi develop a formula in a tree-shaped arrangement that represents a case analysis
on when a formula can be made true (or false). Therefore the formulae are decorated with upper
indices that hold the intended truth value.
On the left we have a refutation tableau that analyzes a negated formula (it is decorated with
the intended truth value F). Both branches contain an elementary contradiction ⊥.
On the right we have a model generation tableau, which analyzes a positive formula (it is
decorated with the intended truth value T). This tableau uses the same rules as the refutation
tableau, but makes a case analysis of when this formula can be satisfied. In this case we have a
closed branch and an open one. The latter corresponds a model.
Now that we have seen the examples, we can write down the tableau rules formally.
Aα
T F α ̸= β
(A ∧ B) (A ∧ B) ¬A T
¬A F
Aβ
T0 ∧ T0 ∨ T0 ¬T T0 ¬F T0 ⊥
AT AF BF AF AT ⊥
BT
Definition 12.2.3. We call any tree ( introduces branches) produced by the T0 inference
rules from a set Φ of labeled formulae a tableau for Φ.
12.2. ANALYTICAL TABLEAUX 253
Definition 12.2.4. Call a tableau saturated, iff no rule adds new material and a branch
closed, iff it ends in ⊥, else open. A tableau is closed, iff all of its branches are.
In analogy to the ⊥ at the end of closed branches, we sometimes decorate open branches with
a 2 symbol.
: 370 2025-05-14
These inference rules act on tableaux have to be read as follows: if the formulae over the line
appear in a tableau branch, then the branch can be extended by the formulae or branches below
the line. There are two rules for each primary connective, and a branch closing rule that adds the
special symbol ⊥ (for unsatisfiability) to a branch.
We use the tableau rules with the convention that they are only applied, if they contribute new
material to the branch. This ensures termination of the tableau procedure for propositional logic
(every rule eliminates one primary connective).
Definition 12.2.5. We will call a closed tableau with the labeled formula Aα at the root a
tableau refutation for Aα .
The saturated tableau represents a full case analysis of what is necessary to give A the truth
value α; since all branches are closed (contain contradictions) this is impossible.
: 371 2025-05-14
Definition 12.2.7. We will call a tableau refutation for AF a tableau proof for A, since it refutes
the possibility of finding a model where A evaluates to F. Thus A must evaluate to T in all
models, which is just our definition of validity.
Thus the tableau procedure can be used as a calculus for propositional logic. In contrast to the
propositional Hilbert calculus it does not prove a theorem A by deriving it from a set of axioms,
but it proves it by refuting its negation – here in form of a F label. Such calculi are called negative
or test calculi. Generally test calculi have computational advantages over positive ones, since they
have a built-in sense of direction.
We have rules for all the necessary connectives (we restrict ourselves to ∧ and ¬, since the others
can be expressed in terms of these two via the propositional identities above. For instance, we can
write A ∨ B as ¬(¬A ∧ ¬B), and A ⇒ B as ¬A ∨ B,. . . .)
We now look at a formulation of propositional logic with fancy variable names. Note that
loves(mary, bill) is just a variable name like P or X, which we have used earlier.
Example 12.2.8. “If Mary loves Bill and John loves Mary, then John loves Mary”
F
(loves(mary, bill) ∧ loves(john, mary) ⇒ loves(john, mary))
F
¬(¬¬(loves(mary, bill) ∧ loves(john, mary)) ∧ ¬loves(john, mary))
T
(¬¬(loves(mary, bill) ∧ loves(john, mary)) ∧ ¬loves(john, mary))
T
¬¬(loves(mary, bill) ∧ loves(john, mary))
F
¬(loves(mary, bill) ∧ loves(john, mary))
T
(loves(mary, bill) ∧ loves(john, mary))
T
¬loves(john, mary)
T
loves(mary, bill)
T
loves(john, mary)
F
loves(john, mary)
⊥
This is a closed tableau, so the loves(mary, bill) ∧ loves(john, mary) ⇒ loves(john, mary) is
a T0 -theorem.
As we will see, T0 is sound and complete, so
is valid.
: 372 2025-05-14
We could have used the unsatisfiability theorem (Theorem 12.1.1) here to show that “If Mary
loves Bill and John loves Mary” entails “John loves Mary”. But there is a better way to show
entailment: we directly use derivability in T0 .
Deriving Entailment in T0
Example 12.2.9. “Mary loves Bill” and “John loves Mary” together entail that “John loves
Mary”
T
loves(mary, bill)
T
loves(john, mary)
F
loves(john, mary)
⊥
This is a closed tableau, so {loves(mary, bill), loves(john, mary)}⊢T0 loves(john, mary).
Again, as T0 is sound and complete we have
: 373 2025-05-14
Note: We can also use the tableau calculus to try and show entailment (and fail). The nice thing
is that the failed proof attempt, we can see what went wrong.
: 374 2025-05-14
Obviously, the tableau above is saturated, but not closed, so it is not a tableau proof for our initial
entailment conjecture. We have marked the literal on the open branch green, since they allow us
to read of the conditions of the situation, in which the entailment fails to hold. As we intuitively
argued above, this is the situation, where “Mary loves Bill”. In particular, the open branch gives
us a variable assignment (marked in green) that satisfies the initial formula. In this case, “Mary
loves Bill”, which is a situation, where the entailment fails.
Again, the derivability version is much simpler:
This saturated tableau has an open branch that shows that the interpretation with I φ (loves(mary, bill)) =
T but I φ (loves(john, mary)) = F falsifies the derivability/entailment conjecture.
: 375 2025-05-14
We have seen in the examples above that while it is possible to get by with only the connectives
∨ and ¬, it is a bit unnatural and tedious, since we need to eliminate the other connectives first.
In this section, we will make the calculus less frugal by adding rules for the other connectives,
without losing the advantage of dealing with a small calculus, which is good making statements
about the calculus itself.
AT AT
T T
(A ⇒ B)
T
(A ⇒ B)
F
(A ⇒ B) (A ⇒ B)
T
AT BT (¬A ∨ B)
AF BT T
BF ¬(¬¬A ∧ ¬B)
F
T F T F
(¬¬A ∧ ¬B)
(A ∨ B) (A ∨ B) (A ⇔ B) (A ⇔ B) ¬¬AF ¬BF
AT BT AF AT AF AT AF ¬AT BT
BF BT BF BF BT AF
⊥
: 376 2025-05-14
With these derived rules, theorem proving becomes quite efficient. With these rules, the tableau
(???) would have the following simpler form:
: 377 2025-05-14
Soundness (Tableau)
Idea: A test calculus is refutation sound, iff its inference rules preserve satisfiability and the
goal formulae are unsatisfiable.
12.2. ANALYTICAL TABLEAUX 257
Theorem 12.2.19 (Completeness). T0 is complete, i.e. if Φ ⊆ wff 0 (V0 ) is valid, then there
is a closed tableau T for ΦF .
Proof sketch: Proof difficult/interesting; see Corollary A.3.2
: 378 2025-05-14
Thus we only have to prove Lemma 12.2.17, this is relatively easy to do. For instance for the first
T
rule: if we have a tableau that contains (A ∧ B) and is satisfiable, then it must have a satisfiable
T
branch. If (A ∧ B) is not on this branch, the tableau extension will not change satisfiability,
so we can assume that it is on the satisfiable branch and thus I φ (A ∧ B) = T for some variable
assignment φ. Thus I φ (A) = T and I φ (B) = T, so after the extension (which adds the formulae
AT and BT to the branch), the branch is still satisfiable. The cases for the other rules are
similar.
The next result is a very important one, it shows that there is a procedure (the tableau procedure)
that will always terminate and answer the question whether a given propositional formula is valid
or not. This is very important, since other logics (like the often-studied first-order logic) do not
enjoy this property.
5. At some point the tableau only contains worked off formulae and literals.
6. Since there are only finitely many literals in T , so we can only apply T0 ⊥ a finite number of times.
□
: 379 2025-05-14
Note: The proof above only works for the “base T0 ” because (only) there the rules do not “copy”.
A rule like
T
(A ⇔ B)
AT AF
T
B BF
does, and in particular the number of non-worked-off variables below the line is larger than above
the line. For such rules, we would have a more intricate version of µ which – instead of returning
a natural number – returns a more complex object; a multiset of numbers would work here. In
our proof we are just assuming that the defined connectives have already eliminated. The
tableau calculus basically computes the disjunctive normal form: every branch is a disjunct that
is a conjunction of literals. The method relies on the fact that a DNF is unsatisfiable, iff each
literal is, i.e. iff each branch contains a contradiction in form of a pair of opposite literals.
the “empty” disjunction (no disjuncts) and call it the empty clause. A clause with exactly one
literal is called a unit clause.
Definition 12.3.2. We will often write a clause set {C 1 , . . ., C n } as C 1 ; . . . ; C n , use S ; T
for the union of the clause sets S and T , and S ; C for the extension by a clause C.
PT ∨ A PF ∨ B
R
A∨B
This rule allows to add the resolvent (the clause below the line) to a clause set which contains
the two clauses above. The literals P T and P F are called cut literals.
12.3. RESOLUTION FOR PROPOSITIONAL LOGIC 259
: 380 2025-05-14
C ∨ ¬AT C ∨ ¬AF
CNF ¬T CNF ¬F
C ∨ AF C ∨ AT
Definition 12.3.7. We write CNF0 (Aα ) for the set of all clauses derivable from Aα via the
rules above.
: 381 2025-05-14
that the C-terms in the definition of the inference rules are necessary, since we assumed that
the assumptions of the inference rule must match full clauses. The C terms are used with the
T
convention that they are optional. So that we can also simplify (A ∨ B) to AT ∨ BT .
Background: The background behind this notation is that A and T ∨A are equivalent for any A.
That allows us to interpret the C-terms in the assumptions as T and thus leave them out.
The clause normal form translation as we have formulated it here is quite frugal; we have left
out rules for the connectives ∨, ⇒, and ⇔, relying on the fact that formulae containing these
connectives can be translated into ones without before CNF transformation. The advantage of
having a calculus with few inference rules is that we can prove meta properties like soundness and
completeness with less effort (these proofs usually require one case per inference rule). On the
other hand, adding specialized inference rules makes proofs shorter and more readable.
Fortunately, there is a way to have your cake and eat it. Derivable inference rules are formally
redundant, since they do not change the expressive power of the calculus. Therefore we can leave
them out when proving meta-properties, but include them when actually using the calculus.
T
C ∨ (A ⇒ B)
T
C ∨ (¬A ∨ B) C ∨ (A ⇒ B)
T
Example 12.3.9. ;
C ∨ ¬AT ∨ BT C ∨ A F ∨ BT
C ∨ A F ∨ BT
: 382 2025-05-14
With these derivable rules, theorem proving becomes quite efficient. To get a better under-
standing of the calculus, we look at an example: we prove an axiom of the Hilbert Calculus we
have studied above.
Result {P F ∨ QF ∨ RT , P F ∨ QT , P T , RF }
Example 12.3.11. Resolution Proof
1 P F ∨ QF ∨ R T initial
2 P F ∨ QT initial
3 PT initial
4 RF initial
5 P F ∨ QF resolve 1.3 with 4.1
6 QF resolve 5.1 with 3.1
7 PF resolve 2.2 with 6.1
8 2 resolve 7.1 with 3.1
: 383 2025-05-14
Corollary 12.3.12. Adding clause set simplification wrt. unit clauses to R0 does not affect
soundness and completeness.
This is almost always a good idea! (clause set simplification is cheap)
: 384 2025-05-14
Let us now consider an extended example, where we also address the question how inference
in PL0 – here resolution is embedded into the rational agent metaphor we use in AI-2: we come
back to the Wumpus world.
: 385 2025-05-14
Before we come to the general mechanism, we will go into how we would “convince ourselves that
the Wumpus is in [1, 3].
262 CHAPTER 12. MACHINE-ORIENTED CALCULI FOR PROPOSITIONAL LOGIC
Idea: We formalize the knowledge about the Wumpus world in PL0 and use a test calculus
to check for entailment.
: 386 2025-05-14
The first in is to compute the clause normal form of the relevant knowledge.
: 387 2025-05-14
Given this clause normal form, we only need to find generate empty clause via repeated applications
of the resolution rule.
: 388 2025-05-14
Now that we have seen how we can use propositional inference to derive consequences of the
percepts and world knowledge, let us come back to the question of a general mechanism for agent
functions with propositional inference.
: 389 2025-05-14
Admittedly, the search framework from chapter 6 does not quite cover the agent function we
have here, since that assumes that the world is fully observable, which the Wumpus world is
emphatically not. But it already gives us a good impression of what would be needed for the
“general mechanism”.
264 CHAPTER 12. MACHINE-ORIENTED CALCULI FOR PROPOSITIONAL LOGIC
12.4 Conclusion
Summary
Every propositional formula can be brought into conjunctive normal form (CNF), which can
be identified with a set of clauses.
The tableau and resolution calculi are deduction procedures based on trying to derive a
contradiction from the negated theorem (a closed tableau or the empty clause). They are
refutation complete, and can be used to prove KB ⊨ A by showing that KB ∪ {¬A} is
unsatisfiable.
: 390 2025-05-14
Excursion: A full analysis of any calculus needs a completeness proof. We will not cover this
in AI-2, but provide one for the calculi introduced so far inAppendix A.
Chapter 13
13.1 Introduction
Reminder: Our Agenda for Propositional Logic
chapter 10: Basic definitions and concepts; machine-oriented calculi
Sets up the framework. Tableaux and resolution are the quintessential reasoning proce-
dures underlying most successful SAT solvers.
: 391 2025-05-14
A is commonly assumed to be in CNF. This is without loss of generality, because any A can
be transformed into a satisfiability-equivalent CNF formula (cf. chapter 10) in polynomial
time.
Active research area, annual SAT conference, lots of tools etc. available: [Link]
[Link]/
Definition 13.1.2. Tools addressing SAT are commonly referred to as SAT solvers.
Recall: To decide whether KB ⊨ A, decide satisfiability of θ := KB ∪ {¬A}: θ is
unsatisfiable iff KB ⊨ A.
Consequence: Deduction can be performed using SAT solvers.
265
266 CHAPTER 13. PROPOSITIONAL REASONING: SAT SOLVERS
: 392 2025-05-14
Upshot: Anything we can do with CSP, we can (in principle) do with SAT.
: 393 2025-05-14
: 394 2025-05-14
DPLL is (A Restricted Form of) Resolution: How does this relate to what we did in the
last chapter?
mathematical understanding of DPLL.
Why Did Unit Propagation Yield a Conflict?: How can we analyze which mistakes were
made in “dead” search branches?
Knowledge is power, see next.
Clause Learning: How can we learn from our mistakes?
One of the key concepts, perhaps the key concept, underlying the success of SAT.
Phase Transitions – Where the Really Hard Problems Are: Are all formulas “hard” to
solve?
The answer is “no”. And in some cases we can figure out exactly when they are/aren’t
hard to solve.
: 395 2025-05-14
: 396 2025-05-14
: 397 2025-05-14
4. UP Rule: P 7→ T
2
: 398 2025-05-14
P F
T
X1
T F
Xn Xn
T F T F
Q Q Q Q
T F T F T F T F
T T T T T T T T
R ; 2R ; 2R ; 2R ; 2R ; 2R ; 2R ; 2R ; 2
: 399 2025-05-14
Properties of DPLL
Unsatisfiable case: What can we say if “unsatisfiable” is returned?
In this case, we know that ∆ is unsatisfiable: Unit propagation is sound, in the sense that
it does not reduce the set of solutions.
Satisfiable case: What can we say when a partial interpretation I is returned?
Any extension of I to a complete interpretation satisfies ∆. (By construction, I suffices
to satisfy all clauses.)
: 400 2025-05-14
UP =
b Unit Resolution
Observation: The unit propagation (UP) rule corresponds to a calculus:
while ∆′ contains a unit clause {l} do
270 CHAPTER 13. PROPOSITIONAL REASONING: SAT SOLVERS
extend I ′ with the respective truth value for the proposition underlying l
simplify ∆′ /∗ remove false literals ∗/
Definition 13.3.1 (Unit Resolution). Unit resolution (UR) is the test calculus consisting
of the following inference rule:
C ∨ P α P β α ̸= β
UR
C
Unit propagation =
b resolution restricted to cases where one parent is unit clause.
Observation 13.3.2 (Soundness). UR is refutation sound. (since resolution is)
Observation 13.3.3 (Completeness). UR is not refutation complete (alone).
Example 13.3.4. P T ∨ QT ; P T ∨ QF ; P F ∨ QT ; P F ∨ QF is unsatisfiable but UR cannot
derive the empty clause 2.
UR makes only limited inferences, as long as there are unit clauses. It does not guarantee to
infer everything that can be inferred.
: 401 2025-05-14
: 402 2025-05-14
DPLL: (Without UP; leaves an- Resolution proof from that DPLL tree:
notated with clauses that became
empty)
S 2
F
T
Q ST SF ST
F
T
R QT ∨ S F QF ∨ S F QT ∨ S F
F
T
P F
RT ∨ S F QF ∨ RF ∨ S F RT ∨ S F
T
Q ∨ P F P T ∨ QF ∨ R F ∨ S F
F
QF ∨ P F P T ∨ QF ∨ RF ∨ S F
: 403 2025-05-14
or have removed N 1 and thus must already have derived the empty clause (because C(N ) ⊆
{L1 , . . . , Lk }\{L1 , . . . , Lk }).
8. Unit propagation can be simulated via applications of the splitting rule, choosing a proposition
that is constrained by a unit clause: One of the two truth values then immediately yields an
empty clause.
□
Definition 13.3.9. In a tree resolution, each derived clause C is used only once (at its
parent).
Problem: The same C must be derived anew every time it is used!
This is a fundamental weakness: There are inputs ∆ whose shortest tree resolution proof
is exponentially longer than their shortest (general) resolution proof.
Intuitively: DPLL makes the same mistakes over and over again.
Idea: DPLL should learn from its mistakes on one search branch, and apply the learned
knowledge to other branches.
To the rescue: clause learning (up next)
: 404 2025-05-14
Excursion: Practical SAT solvers use a technique called CDCL that analyzes failure and learns
from that in terms of inferred clauses. Unfortunately, we cannot cover this in [Link] B.
13.4 Conclusion
Summary
SAT solvers decide satisfiability of CNF formulas. This can be used for deduction, and is
highly successful as a general problem solving technique (e.g., in verification).
DPLL = b backtracking with inference performed by unit propagation (UP), which iteratively
instantiates unit clauses and simplifies the formula.
DPLL proofs of unsatisfiability correspond to a restricted form of resolution. The restriction
forces DPLL to “makes the same mistakes over again”.
Implication graphs capture how UP derives conflicts. Their analysis enables us to do clause
learning. DPLL with clause learning is called CDCL. It corresponds to full resolution, not
“making the same mistakes over again”.
CDCL is state of the art in applications, routinely solving formulas with millions of proposi-
tions.
13.4. CONCLUSION 273
: 405 2025-05-14
: 406 2025-05-14
local search is not as successful in SAT applications, and the underlying ideas are very similar
to those presented in section 6.6 (Not covered here)
: 407 2025-05-14
274 CHAPTER 13. PROPOSITIONAL REASONING: SAT SOLVERS
Local search: In space of all truth value assignments. GSAT (slide 407) had huge impact
at the time (1992), caused huge amount of follow-up work. Less intensely researched since
clause learning hit the scene in the late 90s.
Portfolios: How to combine several SAT solvers efficiently?
Random restarts: Tackling heavy-tailed runtime distributions.
: 408 2025-05-14
Suggested Reading:
A D B E C
I You
Yousay:
say: “All
“Allblocks arered”;
blocks are red”;“All
“All blocks
blocks arethe
are on ontable”;
the table”;
“A is a “A is a block”.
block”.
I And
Andnow:
now: Say
Say itit in propositional
in propositional logic!
logic!
: 409 2025-05-14
275
276 CHAPTER 14. FIRST-ORDER PREDICATE LOGIC
Note: Even when we can describe the problem suitably, for the desired reasoning, the
propositional formulation typically is way too large to write (by hand).
PL1 solution: “∀[Link](x) ⇒ (∀[Link](x, y) ⇒ stench(y))”
: 410 2025-05-14
: 411 2025-05-14
Example 14.1.3.
Read: “Forall n > 2, there are no a, b, c, such that an + bn = cn ” (Fermat’s last theorem)
: 412 2025-05-14
: 413 2025-05-14
: 414 2025-05-14
: 415 2025-05-14
: 416 2025-05-14
14.2. FIRST-ORDER LOGIC 279
“There is a surjective function from the natural numbers into the reals”.
First-Order Predicate Logic has many good properties (complete calculi, compactness,
unitary, linear unification,. . . )
But too weak for formalizing: (at least directly)
: 417 2025-05-14
Definition 14.2.1. First-order logic (PL1 ), is a formal system extensively used in mathemat-
ics, philosophy, linguistics, and CS. It combines propositional logic with the ability to quantify
over individuals.
PL1 talks about two kinds of objects: (so we have two kinds of symbols)
: 418 2025-05-14
We make the deliberate, but non-standard design choice here to include Skolem constants into
the signature from the start. These are used in inference systems to give names to objects and
construct witnesses. Other than the fact that they are usually introduced by need, they work
exactly like regular constants, which makes the inclusion rather painless. As we can never predict
how many Skolem constants we are going to need, we give ourselves countably infinitely many for
every arity. Our supply of individual variables is countably infinite for the same reason.
The formulae of first-order logic are built up from the signature and variables as terms (to rep-
resent individuals) and first-order proposition (to represent proposition). The latter include the
connectives from PL0 , but also quantifiers.
: 419 2025-05-14
Note: We only need e.g. conjunction, negation, and universal quantifier, all other log-
ical constants can be defined from them (as we will see when we have fixed their interpreta-
tions).
14.2. FIRST-ORDER LOGIC 281
Here Elsewhere
V
∀x.A x.A (x)A
W
∃x.A x.A
: 420 2025-05-14
The introduction of quantifiers to first-order logic brings a new phenomenon: variables that are
under the scope of a quantifiers will behave very differently from the ones that are not. Therefore
we build up a vocabulary that distinguishes the two.
free(X) := {X} S
free(f (A1 , . . ., An )) := S 1≤i≤n free(Ai )
free(p(A1 , . . ., An )) := 1≤i≤n free(Ai )
free(¬A) := free(A)
free(A ∧ B) := free(A) ∪ free(B)
free(∀X.A) := free(A)\{X}
Definition 14.2.11. We call a formula A closed or ground, iff free(A) = ∅. We call a closed
proposition a sentence, and denote the set of all ground term with cwff ι (Σι ) and the set of
sentences with cwff o (Σι ).
Axiom 14.2.12. Bound variables can be renamed, i.e. any subterm ∀X.B of a formula A
can be replaced by A′ := (∀Y .B′ ), where B′ arises from B by replacing all X ∈ free(B) with
a new variable Y that does not occur in A. We call A′ an alphabetical variant of A – and
the other way around too.
: 421 2025-05-14
We will be mainly interested in (sets of) sentences – i.e. closed propositions – as the represen-
tations of meaningful statements about individuals. Indeed, we will see below that free variables
do not gives us expressivity, since they behave like constants and could be replaced by them in all
situations, except the recursive definition of quantified formulae. Indeed in all situations where
variables occur freely, they have the character of metavariables, i.e. syntactic placeholders that
can be instantiated with terms when needed in a calculus.
The semantics of first-order logic is a Tarski-style set-theoretic semantics where the atomic syn-
tactic entities are interpreted by mapping them into a well-understood structure, a first-order
universe that is just an arbitrary set.
Definition 14.2.13. We inherit the domain D0 = {T, F} of truth values from PL0 and
assume an arbitrary domain Dι ̸= ∅ of individuals. (this choice is a parameter to the
semantics)
Definition 14.2.14. An interpretation I assigns values to constants, e.g.
: 422 2025-05-14
We do not have to make the domain of truth values part of the model, since it is always the same;
we determine the model by choosing a domain and an interpretation functiong.
Given a first-order model, we can define the evaluation function as a homomorphism over the
construction of formulae.
Definition 14.2.17. Given a model ⟨D, I⟩, the value function I φ is recursively defined:
(two parts: terms & propositions)
: 423 2025-05-14
The only new (and interesting) case in this definition is the quantifier case, there we define the
value of a quantified formula by the value of its scope – but with an extension of the incoming
variable assignment. Note that by passing to the scope A of ∀x.A, the occurrences of the variable
x in A that were bound in ∀x.A become free and are amenable to evaluation by the variable
assignment ψ := φ,[a/X]. Note that as an extension of φ, the assignment ψ supplies exactly the
right value for x in A. This variability of the variable assignment in the definition of the value
function justifies the somewhat complex setup of first-order evaluation, where we have the (static)
interpretation function for the symbols from the signature and the (dynamic) variable assignment
for the variables.
14.2. FIRST-ORDER LOGIC 283
Note furthermore, that the value I φ (∃x.A) of ∃x.A, which we have defined to be ¬(∀x.¬A) is
true, iff it is not the case that I φ (∀x.¬A) = I ψ (¬A) = F for all a ∈ Dι and ψ := φ,[a/X]. This is
the case, iff I ψ (A) = T for some a ∈ Dι . So our definition of the existential quantifier yields the
appropriate semantics.
: 424 2025-05-14
We will now turn our attention to substitutions, special formula-to-formula mappings that
operationalize the intuition that (individual) variables stand for arbitrary terms.
Substitutions on Terms
Intuition: If B is a term and X is a variable, then we denote the result of systematically
replacing all occurrences of X in a term A by B with [B/X](A).
Problem: What about [Z/Y ], [Y /X](X), is that Y or Z?
: 425 2025-05-14
The extension of a substitution is an important operation, which you will run into from time
to time. Given a substitution σ, a variable x, and an expression A, σ,[A/x] extends σ with a
new value for x. The intuition is that the values right of the comma overwrite the pairs in the
substitution on the left, which already has a value for x, even though the representation of σ may
not show it.
Substitution Extension
Definition 14.2.23 (Substitution Extension). Let σ be a substitution, then we denote the
extension of σ with [A/X] by σ,[A/X] and define it as {(Y ,B) ∈ σ | Y ̸= X} ∪ {(X,A)}:
σ,[A/X] coincides with σ off X, and gives the result A there.
: 426 2025-05-14
Note that the use of the comma notation for substitutions defined in ??? is consistent with
substitution extension. We can view a substitution [a/x], [f (b)/y] as the extension of the empty
substitution (the identity function on variables) by [f (b)/y] and then by [a/x]. Note furthermore,
that substitution extension is not commutative in general.
For first-order substitutions we need to extend the substitutions defined on terms to act on propo-
sitions. This is technically more involved, since we have to take care of bound variables.
Substitutions on Propositions
Problem: We want to extend substitutions to propositions, in particular to quantified
formulae: What is σ(∀X.A)?
Idea: σ should not instantiate bound variables. ([A/X](∀X.B) = ∀A.B′ ill-formed)
Definition 14.2.25. σ(∀X.A) := (∀X.σ−X (A)).
Problem: This can lead to variable capture: [f (X)/Y ](∀X.p(X, Y )) would evaluate to
∀X.p(X, f (X)), where the second occurrence of X is bound after instantiation, whereas it
was free before. Solution: Rename away the bound variable X in ∀X.p(X, Y ) before
applying the substitution.
: 427 2025-05-14
14.2. FIRST-ORDER LOGIC 285
We now introduce a central tool for reasoning about the semantics of substitutions: the “sub-
stitution value Lemma”, which relates the process of instantiation to (semantic) evaluation. This
result will be the motor of all soundness proofs on axioms and inference rules acting on variables
via substitutions. In fact, any logic with variables and substitutions will have (to have) some form
of a substitution value Lemma to get the meta-theory going, so it is usually the first target in any
development of such a logic. We establish the substitution-value Lemma for first-order logic in
two steps, first on terms, where it is very simple, and then on propositions.
by induction hypothesis
3.2. This completes the induction step, and we have proven the assertion.
□
: 428 2025-05-14
(otherwise rename)
5.1. then I ψ (A) = I ψ (∀Y .C) = T, iff I ψ,[a/Y ] (C) = T for all a ∈ Dι .
5.2. But I ψ,[a/Y ] (C) = I φ,[a/Y ] ([B/X](C)) = T, by induction hypothesis.
5.3. So I ψ (A) = I φ (∀Y .[B/X](C)) = I φ ([B/X](∀Y .C)) = I φ ([B/X](A))
□
: 429 2025-05-14
To understand the proof fully, you should think about where the “WLOG” – it stands for without
loss of generality comes from.
A ∀X.A
∀I ∗ ∀E
∀X.A [B/X](A)
[[c/X](A)]1
.
∃X.A .
. 0 new
c ∈ Σsk
[B/X](A) C
∃I ∃E 1
∃X.A C
∗
means that A does not depend on any hypothesis in which X is free.
: 430 2025-05-14
The intuition behind the rule ∀I is that a formula A with a (free) variable X can be generalized
to ∀X.A, if X stands for an arbitrary object, i.e. there are no restricting assumptions about X.
The ∀E rule is just a substitution rule that allows to instantiate arbitrary terms B for X in A.
The ∃I rule says if we have a witness B for X in A (i.e. a concrete term B that makes A true),
then we can existentially close A. The ∃E rule corresponds to the common mathematical practice,
where we give objects we know exist a new name c and continue the proof by reasoning about this
concrete object c. Anything we can prove from the assumption [c/X](A) we can prove outright if
∃X.A is known.
14.3. FIRST-ORDER NATURAL DEDUCTION 287
Γ ⊢ A X ̸∈ free(Γ) Γ ⊢ ∀X.A
∀I ∀E
Γ ⊢ ∀X.A Γ ⊢ [B/X](A)
Γ ⊢ [B/X](A) 0 new
Γ ⊢ ∃X.A Γ, [c/X](A) ⊢ C c ∈ Σsk
∃I ∃E
Γ ⊢ ∃X.A Γ⊢C
: 431 2025-05-14
A = B C [A]p
=I =E
A=A [B/p]C
where C [A]p if the formula C has a subterm A at position p and [B/p]C is the result of
replacing that subterm with B.
In many ways equivalence behaves like equality, we will use the following rules in ND1
: 432 2025-05-14
Again, we have two rules that follow the introduction/elimination pattern of natural deduction
calculi.
Definition 14.3.6. We have the canonical sequent rules that correspond to them: =I, =E, ⇔I,
and ⇔E
To make sure that we understand the constructions here, let us get back to the “replacement at
position” operation used in the equality rules.
288 CHAPTER 14. FIRST-ORDER PREDICATE LOGIC
Positions in Formulae
Idea: Formulae are (naturally) trees, so we can use tree positions to talk about subformulae
Definition 14.3.7. A position p is a tuple of natural numbers that in each node of an
expression (tree) specifies into which child to descend. For an expression A we denote the
subexpression at p with A|p .
We will sometimes write an expression C as C [A]p to indicate that C the subexpression A
at position p.
If C [A]p and A is atomic, then we speak of an occurrence of A in C.
Definition 14.3.8. Let p be a position, then [A/p]C is the expression obtained from C by
replacing the subexpression at p by A.
Example 14.3.9 (Schematically).
C [B/p]C
p p
A = C|p B
: 433 2025-05-14
The operation of replacing a subformula at position p is quite different from e.g. (first-order)
substitutions:
• We are replacing subformulae with subformulae instead of instantiating variables with terms.
• Substitutions replace all occurrences of a variable in a formula, whereas formula replacement
only affects the (one) subformula at position p.
We conclude this section with an extended example: the proof of a classical mathematical result
in the natural deduction calculus with equality. This shows us that we can derive strong properties
about complex situations (here the real numbers; an uncountably infinite set of numbers).
1
√
ND= Example: 2 is Irrational
: 434 2025-05-14
If we want to formalize this into ND1 , we have to write down all the assertions in the proof steps
in PL1 syntax and come up with justifications for them in terms of ND1 inference rules. The next
two slides show such a proof, where we write ′n to denote that n is prime, use #(n) for the number
of prime factors of a number n, and write irr(r) if r is irrational.
1
√
ND= Example: 2 is Irrational (the Proof)
: 435 2025-05-14
Lines 6 and 9 are local hypotheses for the proof (they only have an implicit counterpart in the
inference rules as defined above). Finally we have abbreviated the arithmetic simplification of line
9 with the justification “arith” to avoid having to formalize elementary arithmetic.
1
√
ND= Example: 2 is Irrational (the Proof continued)
13 prime(2) lemma
14 6,9 #(2q 2 ) = #(q 2 ) + 1 ⇒E(13, 12)
15 6,9 #(q 2 ) = 2#(q) ∀E 2 (2)
16 6,9 #(2q 2 ) = 2#(q) + 1 =E(14, 15)
17 #(p2 ) = #(p2 ) =I
18 6,9 #(2q 2 ) = #(q 2 ) =E(17, 10)
19 6.9 2#(q) + 1 = #(p2 ) =E(18, 16)
20 6.9 2#(q) + 1 = 2#(p) =E(19, 11)
21 6.9 ¬(2#(q) + 1) = (2#(p)) ∀E 2 (1)
22 6,9 F FI(20, 21)
23 6 F √ ∃E 6 (22)
24 ¬¬irr(
√ 2) ¬I 6 (23)
25 irr( 2) ¬E 2 (23)
: 436 2025-05-14
We observe that the ND1 proof is much more detailed, and needs quite a few Lemmata about
# to go through. Furthermore, we have added a definition of irrationality (and treat definitional
290 CHAPTER 14. FIRST-ORDER PREDICATE LOGIC
equality via the equality rules). Apart from these artefacts of formalization, the two representations
of proofs correspond to each other very directly.
14.4 Conclusion
Summary (Predicate Logic)
First-order logic allows to explicitly speak about objects and their properties. It is thus a
more natural and compact representation language than propositional logic; it also enables us
to speak about infinite sets of objects.
: 437 2025-05-14
Recap: We can express mathematical theorems in PL1 and prove them in ND1 .
Problem: These proofs can be huge (giga-steps), how can we trust them?
Definition 14.4.1. A proof checker for a calculus C is a program that reads (a formal
representation) of a C-proof P and performs proof-checking, i.e. it checks whether all rule
applications in P are (syntactically) correct.
Remark: Proof-checking goes step-by-step ; proof checkers run in linear time.
Idea: If the logic can express (safety)-properties of programs, we can use proof checkers for
formal program verification. (there are extensions of PL1 that can)
Problem: These proofs can be humongous, how can humans write them?
Idea: Automate proof construction via
lemma/theorem libraries that collect useful intermediate results
tactics =
b subroutines that construct recurring sub-proofs
calls to automated theorem prover (ATP) (next chapter)
Proof checkers that do any/all of these are called proof assistants.
Definition 14.4.2. Formal methods are logic-based techniques for the specification, devel-
opment, analysis, and verification of software and hardware.
14.4. CONCLUSION 291
: 438 2025-05-14
Suggested Reading:
• Chapter 8: First-Order Logic, Sections 8.1 and 8.2 in [RusNor:AIMA09]
– A less formal account of what I cover in “Syntax” and “Semantics”. Contains different exam-
ples, and complementary explanations. Nice as additional background reading.
• Sections 8.3 and 8.4 provide additional material on using PL1, and on modeling in PL1, that I
don’t cover in this lecture. Nice reading, not required for exam.
• Chapter 9: Inference in First-Order Logic, Section 9.5.1 in [RusNor:AIMA09]
– A very brief (2 pages) description of what I cover in “Normal Forms”. Much less formal; I
couldn’t find where (if at all) RN cover transformation into prenex normal form. Can serve
as additional reading, can’t replace the lecture.
• Excursion: A full analysis of any calculus needs a completeness proof. We will not cover this
in AI-2, but provide one for the calculi introduced so far insection C.2.
292 CHAPTER 14. FIRST-ORDER PREDICATE LOGIC
Chapter 15
In this chapter, we take up the machine-oriented calculi for propositional logic from chapter 12
and extend them to the first-order case. While this has been relatively easy for the natural
deduction calculus – we only had to introduce the notion of substitutions for the elimination rule
for the universal quantifier we have to work much more here to make the calculi effective for
implementation.
293
294 CHAPTER 15. AUTOMATED THEOREM PROVING IN FIRST-ORDER LOGIC
: 439 2025-05-14
Tableau calculi develop a formula in a tree-shaped arrangement that represents a case analysis
on when a formula can be made true (or false). Therefore the formulae are decorated with upper
indices that hold the intended truth value.
On the left we have a refutation tableau that analyzes a negated formula (it is decorated with
the intended truth value F). Both branches contain an elementary contradiction ⊥.
On the right we have a model generation tableau, which analyzes a positive formula (it is
decorated with the intended truth value T). This tableau uses the same rules as the refutation
tableau, but makes a case analysis of when this formula can be satisfied. In this case we have a
closed branch and an open one. The latter corresponds a model.
Now that we have seen the examples, we can write down the tableau rules formally.
Aα
T F α ̸= β
(A ∧ B) (A ∧ B) ¬A T
¬A F
Aβ
T0 ∧ T0 ∨ T0 ¬T T0 ¬F T0 ⊥
AT AF BF AF AT ⊥
BT
Definition 15.1.3. We call any tree ( introduces branches) produced by the T0 inference
rules from a set Φ of labeled formulae a tableau for Φ.
Definition 15.1.4. Call a tableau saturated, iff no rule adds new material and a branch
closed, iff it ends in ⊥, else open. A tableau is closed, iff all of its branches are.
In analogy to the ⊥ at the end of closed branches, we sometimes decorate open branches with
a 2 symbol.
: 440 2025-05-14
These inference rules act on tableaux have to be read as follows: if the formulae over the line
appear in a tableau branch, then the branch can be extended by the formulae or branches below
the line. There are two rules for each primary connective, and a branch closing rule that adds the
special symbol ⊥ (for unsatisfiability) to a branch.
We use the tableau rules with the convention that they are only applied, if they contribute new
material to the branch. This ensures termination of the tableau procedure for propositional logic
(every rule eliminates one primary connective).
Definition 15.1.5. We will call a closed tableau with the labeled formula Aα at the root a
tableau refutation for Aα .
15.1. FIRST-ORDER INFERENCE WITH TABLEAUX 295
The saturated tableau represents a full case analysis of what is necessary to give A the truth
value α; since all branches are closed (contain contradictions) this is impossible.
: 441 2025-05-14
Definition 15.1.7. We will call a tableau refutation for AF a tableau proof for A, since it refutes
the possibility of finding a model where A evaluates to F. Thus A must evaluate to T in all
models, which is just our definition of validity.
Thus the tableau procedure can be used as a calculus for propositional logic. In contrast to the
propositional Hilbert calculus it does not prove a theorem A by deriving it from a set of axioms,
but it proves it by refuting its negation – here in form of a F label. Such calculi are called negative
or test calculi. Generally test calculi have computational advantages over positive ones, since they
have a built-in sense of direction.
We have rules for all the necessary connectives (we restrict ourselves to ∧ and ¬, since the others
can be expressed in terms of these two via the propositional identities above. For instance, we can
write A ∨ B as ¬(¬A ∧ ¬B), and A ⇒ B as ¬A ∨ B,. . . .)
We will now extend the propositional tableau techniques to first-order logic. We only have to add
two new rules for the universal quantifier (in positive and negative polarity).
Problem: The rule T1 ∀ displays a case of “don’t know indeterminism”: to find a refutation
we have to guess a formula C from the (usually infinite) set cwff ι (Σι ).
For proof search, this means that we have to systematically try all, so T1 ∀ is infinitely branching
in general.
: 442 2025-05-14
The rule T1 ∀ operationalizes the intuition that a universally quantified formula is true, iff all
of the instances of the scope are. To understand the T1 ∃ rule, we have to keep in mind that
F T
∃X.A abbreviates ¬(∀X.¬A), so that we have to read (∀X.A) existentially — i.e. as (∃X.¬A) ,
stating that there is an object with property ¬A. In this situation, we can simply give this
object a name: c, which we take from our (infinite) set of witness constants Σsk 0 , which we have
given ourselves expressly for this purpose when we defined first-order syntax. In other words
T F
([c/X](¬A)) = ([c/X](A)) holds, and this is just the conclusion of the T1 ∃ rule.
Note that the T1 ∀ rule is computationally extremely inefficient: we have to guess an (i.e. in a
search setting to systematically consider all) instance C ∈ wff ι (Σι , Vι ) for X. This makes the rule
infinitely branching.
296 CHAPTER 15. AUTOMATED THEOREM PROVING IN FIRST-ORDER LOGIC
In the next calculus we will try to remedy the computational inefficiency of the T1 ∀ rule. We do
this by delaying the choice in the universal rule.
Definition 15.1.9. The free variable tableau calculus (T1f ) extends T0 (propositional tableau
calculus) with the quantifier rules:
Aα
α ̸= β σ(A) = σ(B)
Bβ
T1f⊥
⊥:σ
: 443 2025-05-14
Metavariables: Instead of guessing a concrete instance for the universally quantified variable
as in the T1 ∀ rule, T1f ∀ instantiates it with a new metavariable Y , which will be instantiated by
need in the course of the derivation.
Skolem terms as witnesses: The introduction of metavariables makes is necessary to extend
the treatment of witnesses in the existential rule. Intuitively, we cannot simply invent a new name,
since the meaning of the body A may contain metavariables introduced by the T1f ∀ rule. As we
do not know their values yet, the witness for the existential statement in the antecedent of the
T1f ∃ rule needs to depend on that. So witness it using a witness term, concretely by applying a
Skolem function to the metavariables in A.
Instantiating Metavariables: Finally, the T1f⊥ rule completes the treatment of metavariables,
it allows to instantiate the whole tableau in a way that the current branch closes. This leaves us
with the problem of finding substitutions that make two terms equal.
: 444 2025-05-14
15.1. FIRST-ORDER INFERENCE WITH TABLEAUX 297
Let’s Talk
Tableau About
Reasons Blocks,
about BlocksBaby . . .
Example 15.1.11 (Reasoning about Blocks). Returing to slide 409
I Question: What do you see here?
A D B E C
I You
Can say: “Allred(A)
we prove blocksfrom
are ∀[Link](x)
red”; “All blocks areand
⇒ red(x) on block(A)?
the table”; “A is a block”.
I And now: Say it in propositional logic!
T
(∀[Link](X) ⇒ red(X))
T
block(A)
F
red(A)
T
(block(Y ) ⇒ red(Y ))
F T
block(Y ) red(A)
⊥ : [A/Y ] ⊥
: 445 2025-05-14
Unification (Definitions)
Definition 15.1.12. For given terms A1 , . . ., An , unification is the problem of finding a
substitution σ (called unifier), such that σ(A1 ) = . . . = σ(An ).
Notation: We write pairs as A1 =? . . . =? An e.g. f (X) =? f (g(Y )).
Definition 15.1.13. Solutions (e.g. [g(a)/X], [a/Y ], [g(g(a))/X], [g(a)/Y ], or [g(Z)/X], [Z/Y ])
298 CHAPTER 15. AUTOMATED THEOREM PROVING IN FIRST-ORDER LOGIC
: 446 2025-05-14
The idea behind a most general unifier is that all other unifiers can be obtained from it by (further)
instantiation. In an automated theorem proving setting, this means that using most general
unifiers is the least committed choice — any other choice of unifiers (that would be necessary for
completeness) can later be obtained by other substitutions.
Note that there is a subtlety in the definition of the ordering on substitutions: we only compare
on a subset of the variables. The reason for this is that we have defined substitutions to be total
on (the infinite set of) variables for flexibility, but in the applications (see the definition of most
general unifiers), we are only interested in a subset of variables: the ones that occur in the initial
problem formulation. Intuitively, we do not care what the unifiers do off that set. If we did
not have the restriction to the set W of variables, the ordering relation on substitutions would
become much too fine-grained to be useful (i.e. to guarantee unique most general unifiers in our
case).
Now that we have defined the problem, we can turn to the unification algorithm itself. We
will define it in a way that is very similar to logic programming: we first define a calculus that
generates “solved forms” (formulae from which we can read off the solution) and reason about
control later. In this case we will reason that control does not matter.
Unification Problems (=
b Equational Systems)
Idea: Unification is equation solving.
Definition 15.1.16. We call a formula A1 =? B1 ∧ . . . ∧ An =? Bn an unification problem
iff Ai , Bi ∈ wff ι (Σι , Vι ).
Note: We consider unification problems as sets of equations (∧ is ACI), and equations as
two-element multisets (=? is C).
Definition 15.1.17. A substitution is called a unifier for a unification problem E (and thus
E unifiable), iff it is a (simultaneous) unifier for all pairs in E.
: 447 2025-05-14
In principle, unification problems are sets of equations, which we write as conjunctions, since all of
them have to be solved for finding a unifier. Note that it is not a problem for the “logical view” that
the representation as conjunctions induces an order, since we know that conjunction is associative,
commutative and idempotent, i.e. that conjuncts do not have an intrinsic order or multiplicity,
if we consider two equational problems as equal, if they are equivalent as propositional formulae.
In the same way, we will abstract from the order in equations, since we know that the equality
relation is symmetric. Of course we would have to deal with this somehow in the implementation
(typically, we would implement equational problems as lists of pairs), but that belongs into the
“control” aspect of the algorithm, which we are abstracting from at the moment.
15.1. FIRST-ORDER INFERENCE WITH TABLEAUX 299
: 448 2025-05-14
It is essential to our “logical” analysis of the unification algorithm that we arrive at unification prob-
lems whose unifiers we can read off easily. Solved forms serve that need perfectly as Lemma 15.1.21
shows.
Given the idea that unification problems can be expressed as formulae, we can express the algo-
rithm in three simple rules that transform unification problems into solved forms (or unsolvable
ones).
Unification Algorithm
Definition 15.1.22. The inference system U consists of the following rules:
E ∧ f (A1 , . . ., An ) =? f (B1 , . . ., Bn ) E ∧ A =? A
Udec Utriv
E ∧ A1 =? B1 ∧ . . . ∧ An =? Bn E
E ∧ X =? bA ∧ X ̸∈ free(A) ∧ X ∈ free(E)
Uelim
[A/X](E) ∧ X =? A
Corollary 15.1.26. First-order unification is unitary: i.e. most general unifiers are unique up
to renaming of introduced variables.
Proof sketch: U is trivially branching.
: 449 2025-05-14
300 CHAPTER 15. AUTOMATED THEOREM PROVING IN FIRST-ORDER LOGIC
The decomposition rule U dec is completely straightforward, but note that it transforms one unifi-
cation pair into multiple argument pairs; this is the reason, why we have to directly use unification
problems with multiple pairs in U.
Note furthermore, that we could have restricted the Utriv rule to variable-variable pairs, since
for any other pair, we can decompose until only variables are left. Here we observe, that constant-
constant pairs can be decomposed with the Udec rule in the somewhat degenerate case without
arguments.
Finally, we observe that the first of the two variable conditions in U elim (the “occurs-in-check”)
makes sure that we only apply the transformation to unifiable unification problems, whereas the
second one is a termination condition that prevents the rule to be applied twice.
The notion of completeness and correctness is a bit different than that for calculi that we compare
to the entailment relation. We can think of the “logical system of unifiability” with the model class
of sets of substitutions, where a set satisfies an equational problem E, iff all of its members are
unifiers. This view induces the soundness and completeness notions presented above.
The three meta-properties above are relatively trivial, but somewhat tedious to prove, so we leave
the proofs as an exercise to the reader.
We now fortify our intuition about the unification calculus by two examples. Note that we only
need to pursue one possible U derivation since we have confluence.
Unification Examples
Example 15.1.27. Two similar unification problems:
: 450 2025-05-14
We will now convince ourselves that there cannot be any infinite sequences of transformations in
U. Termination is an important property for an algorithm.
The proof we present here is very typical for termination proofs. We map unification problems
into a partially ordered set ⟨S, ≺⟩ where we know that there cannot be any infinitely descending
sequences (we think of this as measuring the unification problems). Then we show that all trans-
formations in U strictly decrease the measure of the unification problems and argue that if there
were an infinite transformation in U, then there would be an infinite descending chain in S, which
contradicts our choice of ⟨S, ≺⟩.
The crucial step in coming up with such proofs is finding the right partially ordered set.
Fortunately, there are some tools we can make use of. We know that ⟨N, <⟩ is terminating, and
there are some ways of lifting component orderings to complex structures. For instance it is well-
known that the lexicographic ordering lifts a terminating ordering to a terminating ordering on
finite dimensional Cartesian spaces. We show a similar, but less known construction with multisets
for our proof.
15.1. FIRST-ORDER INFERENCE WITH TABLEAUX 301
Unification (Termination)
Definition 15.1.28. Let S and T be multisets and ≤ a partial ordering on S ∪ T . Then we
define S ≺m S, iff S = C ⊎ T ′ and T = C ⊎ {t}, where s≤t for all s ∈ S ′ . We call ≤m the
multiset ordering induced by ≤.
Definition 15.1.29. We call a variable X solved in an unification problem E, iff E contains
a solved pair X =? A.
: 451 2025-05-14
But it is very simple to create terminating calculi, e.g. by having no inference rules. So there
is one more step to go to turn the termination result into a decidability result: we must make sure
that we have enough inference rules so that any unification problem is transformed into solved
form if it is unifiable.
2. A, B ̸∈ Vι
2.1. then A = f (A1 . . . An ) and B = f (B1 . . . Bn ), and thus Udec is applicable
4. A = X ∈ free(E)
4.1. then U elim (if B ̸= X) or Utriv (if B = X) is applicable.
□
Proof:
1. U-irreducible unification problems can be reached in finite time by Lemma 15.1.31.
2. They are either solved or unsolvable by Lemma 15.1.33, so they provide the answer.
□
: 452 2025-05-14
Complexity of Unification
Observation: Naive implementations of unification are exponential in time and space.
Example 15.1.35. Consider the terms
: 453 2025-05-14
Indeed, the only way to escape this combinatorial explosion is to find representations of substi-
tutions that are more space efficient.
s3 t3 σ3 (t3 )
f f f
f
f f f f
f
x0 f f f
x1 x2 x3 x0
: 454 2025-05-14
If we look at the unification algorithm from ??? and the considerations in the termination proof
(???) with a particular focus on the role of copying, we easily find the culprit for the exponential
blowup: Uelim, which applies solved pairs as substitutions.
E ∧ X =? A ∧ X =? B A, B ̸∈ Vι |A| ≤ |B|
DUmerge
E ∧ X =? A ∧ A = ? B
E ∧ X =? Y X ̸= Y X, Y ∈ free(E)
DUevar
[Y /X](E) ∧ X =? Y
where |A| is the number of symbols in A.
: 455 2025-05-14
We will now turn the ideas we have developed in the last couple of slides into a usable func-
tional algorithm. The starting point is treating terms as DAGs. Then we try to conduct the
transformation into solved form without adding new nodes.
Unification by DAG-chase
Idea: Extend the Input-DAGs by edges that represent unifiers.
Definition 15.1.40. Write n.a, if a is the symbol of node n.
: 456 2025-05-14
Algorithm dag−unify
Input: symmetric pairs of nodes in DAGs
fun dag−unify(n,n) = true
| dag−unify(n.x,m) = if occur(n,m) then true else union(n,m)
| dag−unify(n.f ,m.g) =
if g!=f then false
else
forall (i,j) => dag−unify(find(i),find(j)) (chld m,chld n)
end
Observation 15.1.41. dag−unify uses linear space, since no new nodes are created, and at
most one link per variable.
Problem: dag−unify still uses exponential time.
Example 15.1.42. Consider terms f (sn , f (t′ n , xn )), f (tn , f (s′ n , y n ))), where s′ n = [y i /xi ](sn )
und t′ n = [y i /xi ](tn ).
dag−unify needs exponentially many recursive calls to unify the nodes xn and y n . (they are
unified after n calls, but checking needs the time)
: 457 2025-05-14
Algorithm uf−unify
Recall: dag−unify still uses exponential time.
Idea: Also bind the function nodes, if the arguments are unified.
uf−unify(n.f ,m.g) =
if g!=f then false
else union(n,m);
forall (i,j) => uf−unify(find(i),find(j)) (chld m,chld n)
end
This only needs linearly many recursive calls as it directly returns with true or makes a node
inaccessible for find.
: 458 2025-05-14
15.1. FIRST-ORDER INFERENCE WITH TABLEAUX 305
Observation 15.1.43. All T1f rules except T1f ∀ only need to be applied once.
Example 15.1.44. A tableau proof for (p(a) ∨ p(b)) ⇒ (∃x.p(x)).
⊥ : [b/z]
After we have used up p(y) by applying [a/y] in T1f⊥, we have to get a new instance p(z)
F F
via T1f ∀.
Definition 15.1.45. Let T be a tableau for A, and a positive occurrence of ∀x.B in A,
then we call the number of applications of T1f ∀ to ∀x.B its multiplicity.
Observation 15.1.46. Given a prescribed multiplicity for each positive ∀, saturation with
T1f terminates.
Proof sketch: All T1f rules reduce the number of connectives and negative ∀ or the multiplicity
of positive ∀.
Theorem 15.1.47. T1f is only complete with unbounded multiplicities.
Proof sketch: Replace p(a) ∨ p(b) with p(a1 ) ∨ . . . ∨ p(an ) in Example 15.1.44.
: 459 2025-05-14
The other thing we need to realize is that there may be multiple ways we can use T1f⊥ to close a
branch in a tableau, and – as T1f⊥ instantiates the whole tableau and not just the branch itself –
this choice matters.
306 CHAPTER 15. AUTOMATED THEOREM PROVING IN FIRST-ORDER LOGIC
Treating T1f⊥
Example 15.1.48. Choosing which matters – this tableau does not close!
F
(∃x.(p(a) ∧ p(b) ⇒ p(x)) ∧ (q(b) ⇒ q(x)))
F
((p(a) ∧ p(b) ⇒ p(y)) ∧ (q(b) ⇒ q(y)))
F F
(p(a) ∧ p(b) ⇒ p(y)) (q(b) ⇒ q(y))
T T
p(a) q(b)
T F
p(b) q(y)
F
p(y)
⊥ : [a/y]
: 460 2025-05-14
The method of spanning matings follows the intuition that if we do not have good information
on how to decide for a pair of opposite literals on a branch to use in T1f⊥, we delay the choice by
initially disregarding the rule altogether during saturation and then – in a later phase– looking
for a configuration of cuts that have a joint overall unifier. The big advantage of this is that we
only need to know that one exists, we do not need to compute or apply it, which would lead to
exponential blow-up as we have seen above.
Observation 15.1.49. T1f without T1f⊥ is terminating and confluent for given multiplicities.
Idea: Saturate without T1f⊥ and treat all cuts at the same time (later).
Definition 15.1.50.
Let T be a T1f tableau, then we call a unification problem E := A1 =? B1 ∧ . . . ∧ An =? Bn
a mating for T , iff Ai T and Bi F occur in the same branch in T .
We say that E is a spanning mating, if E is unifiable and every branch B of T contains Ai T
and Bi F for some i.
Theorem 15.1.51. A T1f -tableau with a spanning mating induces a closed T1 tableau.
: 461 2025-05-14
Excursion: Now that we understand basic unification theory, we can come to the meta-theoretical
properties of the tableau calculus. We delegate this discussion tosection C.3.
: 462 2025-05-14
: 463 2025-05-14
Excursion: Again, we relegate the meta-theoretical properties of the first-order resolution calculus
tosection C.4.
: 464 2025-05-14
: 465 2025-05-14
[c/Y1 ]
missile(X2 )F ∨ own(NoNo, X2 )F ∨ sell(West, X2 , NoNo)T
: 466 2025-05-14
: 467 2025-05-14
: 468 2025-05-14
love(g(jack), jack)T
: 469 2025-05-14
Excursion: A full analysis of any calculus needs a completeness proof. We will not cover this in
the course, but provide one for the calculi introduced so far inAppendix C.
PT ∨ A PF ∨ B
A∨B
positive, unit-resulting hyperresolution (PURR)
: 470 2025-05-14
This observation helps us understand Prolog better, and use implementation techniques from
automated theorem proving.
Definition 15.3.6. Horn logic is the formal system whose language is the set of Horn clauses
together with the calculus H given by MP, ∧I, and Subst.
Definition 15.3.7. A logic program P entails a query Q with answer substitution σ, iff there
is a H derivation D of Q from P and σ is the combined substitution of the Subst instances
in D.
: 471 2025-05-14
: 472 2025-05-14
To gain an intuition for this quite abstract definition let us consider a concrete knowledge base
about cars. Instead of writing down everything we know about cars, we only write down that cars
are motor vehicles with four wheels and that a particular object c has a motor and four wheels. We
312 CHAPTER 15. AUTOMATED THEOREM PROVING IN FIRST-ORDER LOGIC
can see that the fact that c is a car can be derived from this. Given our definition of a knowledge
base as the deductive closure of the facts and rule explicitly written down, the assertion that c is
a car is in the induced knowledge base, which is what we are after.
: 473 2025-05-14
In this very simple example car(c) is about the only fact we can derive, but in general, knowledge
bases can be infinite (we will see examples below).
e.g. greek(sokrates),greek(perikles)
Question: Are there fallible greeks?
Indefinite answer: Yes, Perikles or Sokrates
Warning: how about Sokrates and Perikles?
e.g. greek(sokrates),roman(sokrates):−.
Query: Are there fallible greeks?
Answer: Yes, Sokrates, if he is not a roman
Is this abduction?????
: 474 2025-05-14
: 475 2025-05-14
The rule for the universal quantifier can be made efficient by introducing metavariables
that postpone the decision for instances.
We have to extend the witness constants in the rules for existential quantifiers to Skolem
functions.
The cut rules can used to instantiate the metavariables by unification.
These ideas are enough to build a tableau calculus for first-order logic.
Unification is an efficient decision procdure for finding substitutions that make first-order
terms (syntactically) equal.
In prenex normal form, all quantifiers are up front. In Skolem normal form, additionally there
are no existential quantifiers. In claus normal form, additionally the formula is in CNF.
Any PL1 formula can efficiently be brought into a satisfiability-equivalent clause normal form.
This allows first-order resolution.
: 476 2025-05-14
314 CHAPTER 15. AUTOMATED THEOREM PROVING IN FIRST-ORDER LOGIC
Chapter 16
315
316 CHAPTER 16. KNOWLEDGE REPRESENTATION AND THE SEMANTIC WEB
For the purposes of this course: Knowledge is the information necessary to support
intelligent reasoning!
: 477 2025-05-14
: 478 2025-05-14
As knowledge is such a central notion in artificial intelligence, it is not surprising that there are
multiple approaches to dealing with it. We will only deal with the first one and leave the others
to self-study.
16.1. INTRODUCTION TO KNOWLEDGE REPRESENTATION 317
: 479 2025-05-14
When assessing the relative strengths of the respective approaches, we should evaluate them with
respect to a pre-determined set of criteria.
KR Approaches/Evaluation Criteria
Definition 16.1.1. The evaluation criteria for knowledge representation approaches are:
: 480 2025-05-14
: 481 2025-05-14
Even though the network in Example 16.1.3 is very intuitive (we immediately understand the
concepts depicted), it is unclear how we (and more importantly a machine that does not asso-
ciate meaning with the labels of the nodes and edges) can draw inferences from the “knowledge”
represented.
Example 16.1.5. In the network below, we “know” that “robins have wings” and in particular,
“Jack has wings”.
Idea: Links labeled with “isa” and “inst” are special: they propagate properties encoded by
other links.
Definition 16.1.6. We call links labeled by
: 482 2025-05-14
We now make the idea of “propagating properties” rigorous by defining the notion of derived
relations, i.e. the relations that are left implicit in the network, but can be added without changing
its meaning.
isa
bird / Jack Person
isa inst
inst inst
has_part robin owner_of Mary
has_part
has_part loves
wings John
Slogan: Get out more knowledge from a semantic networks than you put in.
: 483 2025-05-14
Note that Definition 16.1.7 does not quite allow to derive that “Jack is a bird” (did you spot that
“isa” is not a relation that can be inferred?), even though we know it is true in the world. This
shows us that inference in semantic networks has be to very carefully defined and may not be
“complete”, i.e. there are things that are true in the real world that our inference procedure does
not capture.
Dually, if we are not careful, then the inference procedure might derive properties that are not
true in the real world even if all the properties explicitly put into the network are. We call such
an inference procedure unsound or incorrect.
These are two general phenomena we have to keep an eye on.
Another problem is that semantic networks (e.g. in ???) confuse two kinds of concepts: individuals
(represented by proper names like “John” and “Jack”) and concepts (nouns like “robin” and “bird”).
Even though the isa and inst link already acknowledge this distinction, the “has_part” and “loves”
relations are at different levels entirely, but not distinguished in the networks.
can
animal move
TBox isa isa
amoeba
has_part higher animal has_part
legs head
isa isa
pattern eat color
striped tiger elephant gray
eat
ABox Roy eat Rex Clyde
In particular we have objects “Rex”, “Roy”, and “Clyde”, which have (derived) relations (e.g.
“Clyde” is “gray”).
: 484 2025-05-14
But there are severe shortcomings of semantic networks: the suggestive shape and node names
give (humans) a false sense of meaning, and the inference rules are only given in the process model
(the implementation of the semantic network processing system).
This makes it very difficult to assess the strength of the inference system and make assertions
e.g. about completeness.
has_part has_part
bird wings bird wings
isa isa
robin robin cancel
inst inst
jack joe
“Cancel-links” have been proposed, but their status and process model are debatable.
: 485 2025-05-14
To alleviate the perceived drawbacks of semantic networks, we can contemplate another notation
that is more linear and thus more easily implemented: function/argument notation.
Evaluation:
+ linear notation (equivalent, but better to implement on a computer)
+ easy to give process model by deduction (e.g. in Prolog)
– worse locality properties (networks are associative)
: 486 2025-05-14
Indeed the function/argument notation is the immediate idea how one would naturally represent
semantic networks for implementation.
This notation has been also characterized as subject/predicate/object triples, alluding to simple
(English) sentences. This will play a role in the “semantic web” later.
Building on the function/argument notation from above, we can now give a formal semantics for
semantic network: we translate them into first-order logic and use the semantics of that.
: 487 2025-05-14
Indeed, the semantics induced by the translation to first-order logic, gives the intuitive meaning
to the semantic networks. Note that this only holds only for the features of semantic networks that
are representable in this way, e.g. the “cancel links” shown above are not (and that is a feature,
not a bug).
But even more importantly, the translation to first-order logic gives a first process model: we
can use first-order inference to compute the set of inferences that can be drawn from a semantic
network.
Idea: Move web content up the ladder, use inference to make connections.
Humans understand the text and combine the information to get the answer. Machines need
more than just text ; semantic web technology.
: 488 2025-05-14
The term “semantic web” was coined by Tim Berners Lee in analogy to semantic networks, only
applied to the world wide web. And as for semantic networks, where we have inference processes
that allow us the recover information that is not explicitly represented from the network (here the
world-wide-web).
To see that problems have to be solved, to arrive at the semantic web, we will now look at a
concrete example about the “semantics” in web pages. Here is one that looks typical enough.
WWW2002
The eleventh International World Wide Web Conference
Sheraton Waikiki Hotel
Honolulu, Hawaii, USA
7-11 May 2002
16.1. INTRODUCTION TO KNOWLEDGE REPRESENTATION 323
On the 7th May Honolulu will provide the backdrop of the eleventh
International World Wide Web Conference.
Speakers confirmed
Tim Berners-Lee: Tim is the well known inventor of the Web,
Ian Foster: Ian is the pioneer of the Grid, the next generation internet.
: 489 2025-05-14
But as for semantic networks, what you as a human can see (“understand” really) is deceptive, so
let us obfuscate the document to confuse your “semantic processor”. This gives an impression of
what the computer “sees”.
WWW∈′′∈
T⟨⌉⌉↕⌉⊑⌉\⊔⟨I\⊔⌉∇\⊣⊔⟩≀\⊣↕W≀∇↕⌈W⟩⌈⌉W⌉⌊C≀\{⌉∇⌉\⌋⌉
S⟨⌉∇⊣⊔≀\W⊣⟩∥⟩∥⟩H≀⊔⌉↕
H≀\≀↕⊓↕⊓⇔H⊣⊒⊣⟩⟩⇔USA
7↖∞∞M⊣†∈′′∈
R⌉}⟩∫⊔⌉∇⌉⌈√⊣∇⊔⟩⌋⟩√⊣\⊔∫⌋≀⇕⟩\}{∇≀⇕
A⊓∫⊔∇⊣↕⟩⊣⇔C⊣\⊣⌈⊣⇔C⟨⟩↕⌉D⌉\⇕⊣∇∥⇔F∇⊣\⌋⌉⇔G⌉∇⇕⊣\†⇔G⟨⊣\⊣⇔H≀\}K≀\}⇔I\⌈⟩⊣⇔
I∇⌉↕⊣\⌈⇔I⊔⊣↕†⇔J⊣√⊣\⇔M⊣↕⊔⊣⇔N⌉⊒Z⌉⊣↕⊣\⌈⇔T⟨⌉N⌉⊔⟨⌉∇↕⊣\⌈∫⇔N≀∇⊒⊣†⇔
S⟩\}⊣√≀∇⌉⇔S⊒⟩⊔‡⌉∇↕⊣\⌈⇔⊔⟨⌉U\⟩⊔⌉⌈K⟩\}⌈≀⇕⇔⊔⟨⌉U\⟩⊔⌉⌈S⊔⊣⊔⌉∫⇔V⟩⌉⊔\⊣⇕⇔Z⊣⟩∇⌉
O\⊔⟨⌉7⊔⟨M⊣†H≀\≀↕⊓↕⊓⊒⟩↕↕√∇≀⊑⟩⌈⌉⊔⟨⌉⌊⊣⌋∥⌈∇≀√≀{⊔⟨⌉⌉↕⌉⊑⌉\⊔⟨
I\⊔⌉∇\⊣⊔⟩≀\⊣↕W≀∇↕⌈W⟩⌈⌉W⌉⌊C≀\{⌉∇⌉\⌋⌉↙
S√⌉⊣∥⌉∇∫⌋≀\{⟩∇⇕⌉⌈
T⟩⇕B⌉∇\⌉∇∫↖L⌉⌉¬T⟩⇕⟩∫⊔⟨⌉⊒⌉↕↕∥\≀⊒\⟩\⊑⌉\⊔≀∇≀{⊔⟨⌉W⌉⌊⇔
I⊣\F≀∫⊔⌉∇¬I⊣\⟩∫⊔⟨⌉√⟩≀\⌉⌉∇≀{⊔⟨⌉G∇⟩⌈⇔⊔⟨⌉\⌉§⊔}⌉\⌉∇⊣⊔⟩≀\⟩\⊔⌉∇\⌉⊔↙
: 490 2025-05-14
Obviously, there is not much the computer understands, and as a consequence, there is not a lot
the computer can support the reader with. So we have to “help” the computer by providing some
meaning. Conventional wisdom is that we add some semantic/functional markup. Here we pick
XML without loss of generality, and characterize some fragments of text e.g. as dates.
324 CHAPTER 16. KNOWLEDGE REPRESENTATION AND THE SEMANTIC WEB
: 491 2025-05-14
: 492 2025-05-14
To understand what a machine can understand we have to obfuscate the markup as well, since it
does not carry any intrinsic meaning to the machine either.
<√↕⊣⌋⌉>S⟨⌉∇⊣⊔≀\W⊣⟩∥⟩∥⟩H≀⊔⌉↕H≀\≀↕⊓↕⊓⇔H⊣⊒⊣⟩⟩⇔USA</√↕⊣⌋⌉>
<⌈⊣⊔⌉>7↖∞∞M⊣†∈′′∈</⌈⊣⊔⌉>
<√⊣∇⊔⟩⌋⟩√⊣\⊔∫ >R⌉}⟩∫⊔⌉∇⌉⌈√⊣∇⊔⟩⌋⟩√⊣\⊔∫⌋≀⇕⟩\}{∇≀⇕
A⊓∫⊔∇⊣↕⟩⊣⇔C⊣\⊣⌈⊣⇔C⟨⟩↕⌉D⌉\⇕⊣∇∥⇔F∇⊣\⌋⌉⇔G⌉∇⇕⊣\†⇔G⟨⊣\⊣⇔H≀\}K≀\}⇔I\⌈⟩⊣⇔
I∇⌉↕⊣\⌈⇔I⊔⊣↕†⇔J⊣√⊣\⇔M⊣↕⊔⊣⇔N⌉⊒Z⌉⊣↕⊣\⌈⇔T⟨⌉N⌉⊔⟨⌉∇↕⊣\⌈∫⇔N≀∇⊒⊣†⇔
S⟩\}⊣√≀∇⌉⇔S⊒⟩⊔‡⌉∇↕⊣\⌈⇔⊔⟨⌉U\⟩⊔⌉⌈K⟩\}⌈≀⇕⇔⊔⟨⌉U\⟩⊔⌉⌈S⊔⊣⊔⌉∫⇔V⟩⌉⊔\⊣⇕⇔Z⊣⟩∇⌉
</√⊣∇⊔⟩⌋⟩√⊣\⊔∫ >
<⟩\⊔∇≀⌈⊓⌋⊔⟩≀\>O\⊔⟨⌉7⊔⟨M⊣†H≀\≀↕⊓↕⊓⊒⟩↕↕√∇≀⊑⟩⌈⌉⊔⟨⌉⌊⊣⌋∥⌈∇≀√≀{⊔⟨⌉⌉↕⌉⊑⌉\⊔⟨I\⊔⌉∇\⊣⊔⟩≀\⊣↕W≀∇↕⌈
W⟩⌈⌉W⌉⌊C≀\{⌉∇⌉\⌋⌉↙</⟩\⊔∇≀⌈⊓⌋⊔⟩≀\>
<√∇≀}∇⊣⇕>S√⌉⊣∥⌉∇∫⌋≀\{⟩∇⇕⌉⌈
<∫√⌉⊣∥⌉∇>T⟩⇕B⌉∇\⌉∇∫↖L⌉⌉¬T⟩⇕⟩∫⊔⟨⌉⊒⌉↕↕∥\≀⊒\⟩\⊑⌉\⊔≀∇≀{⊔⟨⌉W⌉⌊</∫√⌉⊣∥⌉∇>
<∫√⌉⊣∥⌉∇>I⊣\F≀∫⊔⌉∇¬I⊣\⟩∫⊔⟨⌉√⟩≀\⌉⌉∇≀{⊔⟨⌉G∇⟩⌈⇔⊔⟨⌉\⌉§⊔}⌉\⌉∇⊣⊔⟩≀\⟩\⊔⌉∇\⌉⊔<∫√⌉⊣∥⌉∇>
</√∇≀}∇⊣⇕>
: 493 2025-05-14
So we have not really gained much either with the markup, we really have to give meaning to the
markup as well, this is where techniques from semenatic web come into play.
To understand how we can make the web more semantic, let us first take stock of the current status
of (markup on) the web. It is well-known that world-wide-web is a hypertext, where multimedia
documents (text, images, videos, etc. and their fragments) are connected by hyperlinks. As we
have seen, all of these are largely opaque (non-understandable), so we end up with the following
situation (from the viewpoint of a machine).
: 494 2025-05-14
: 495 2025-05-14
Essentially, to make the web more machine-processable, we need to classify the resources by the
concepts they represent and give the links a meaning in a way, that we can do inference with that.
The ideas presented here gave rise to a set of technologies jointly called the “semantic web”, which
we will now summarize before we return to our logical investigations of knowledge representation
techniques.
: 496 2025-05-14
16.1. INTRODUCTION TO KNOWLEDGE REPRESENTATION 327
: 497 2025-05-14
Example 16.1.24. getting your hair cut (at tell receptionist you’re here
a beauty parlor)
Beautician cuts hair
props, actors as “script variables”
pay
events in a (generalized) sequence
happy unhappy
use script material for
big tip small tip
anaphora, bridging references
default common ground
to fill in missing material into situations
: 498 2025-05-14
: 499 2025-05-14
: 500 2025-05-14
But of course logic-based approaches have big drawbacks as well. The first is that we have to obtain
the symbolic representations of knowledge to do anything – a non-trivial challenge, since most
knowledge does not exist in this form in the wild, to obtain it, some agent has to experience the
word, pass it through its cognitive apparatus, conceptualize the phenomena involved, systematize
them sufficiently to form symbols, and then represent those in the respective formalism at hand.
The second drawback is that the process models induced by logic-based approaches (inference
with calculi) are quite intractable. We will see that all inferences can be played back to satisfiability
tests in the underlying logical system, which are exponential at best, and undecidable or even
incomplete at worst.
Therefore a major thrust in logic-based knowledge representation is to investigate logical sys-
tems that are expressive enough to be able to represent most knowledge, but still have a decidable
– and maybe even tractable in practice – satisfiability problem. Such logics are called “description
logics”. We will study the basics of such logical systems and their inference procedures in the
following.
language by giving a new, non-standard semantics. This allows us to already preview most of
the inference procedures and knowledge services of knowledge representation systems in the next
subsection.
To establish propositional logic as a set description language, we use a different interpretation than
usual. We interpret propositional variables as names of sets and the connectives as set operations,
which is why we give them a different – more suggestive – syntax.
Definition 16.2.1. Let PL0DL be given by the following grammar for the PL0DL concepts.
(formulae)
L::=C | ⊤ | ⊥ | L | L ⊓ L | L ⊔ L | L ⊑ L | L ≡ L
i.e. PL0DL formed from
atomic formulae (=
b propositional variables)
concept intersection (⊓) (=
b conjunction ∧)
concept complement (·) (=
b negation ¬)
concept union (⊔), subsumption (⊑), and equivalence (≡) defined from these. (=
b ∨, ⇒,
and ⇔)
Definition 16.2.2 (Formal Semantics). Let D be a given set (called the domain of dis-
course) and φ : V0 → P(D), then we define
[ P ] :=φ(P ), (remember φ(P ) ⊆ D).
[ A ⊓ B]] := [ A]] ∩ [ B]] and A :=D\ [ A]] . . .
: 501 2025-05-14
The main use of the set-theoretic semantics for PL0 is that we can use it to give meaning to concept
axioms, which we use to describe the “world”.
Concept Axioms
Observation: Set-theoretic semantics of ‘true’ and ‘false’ (⊤ := φ ⊔ φ ⊥ := φ ⊓ φ)
Idea: Use logical axioms to describe the world (Axioms restrict the class of admissible
domain structures)
Definition 16.2.3. A concept axiom is a PL0DL formula A that is assumed to be true in the
world.
Definition 16.2.4 (Set-Theoretic Semantics of Axioms). A is true in domain of discourse
D iff [ A]] = D.
Example 16.2.5. A world with three concepts and no concept axioms
330 CHAPTER 16. KNOWLEDGE REPRESENTATION AND THE SEMANTIC WEB
sons daughters
child
daughter
son
children
: 502 2025-05-14
Concept axioms are used to restrict the set of admissible domains to the intended ones. In our
situation, we require them to be true – as usual – which here means that they denote the whole
domain D.
Let us fortify our intuition about concept axioms with a simple example about the sibling relation.
We give four concept axioms and study their effect on the admissible models by looking at the
respective Venn diagrams. In the end we see that in all admissible models, the denotations of the
concepts son and daughter are disjointq, and child is the union of the two – just as intended.
Axioms Semantics
son ⊑ child
iff [ son]] ∪ [ child]] = D
iff [ son]] ⊆ [ child]]
sons daughters
daughter
⊑child
iff daughter ∪ [ child]] = D
iff [ daughter]] ⊆ [ child]] children
: 503 2025-05-14
The set-theoretic semantics introduced above is compatible with the regular semantics of proposi-
tional logic, therefore we have the same propositional identities. Their validity can be established
directly from the settings in ???.
Propositional Identities
16.2. LOGIC-BASED KNOWLEDGE REPRESENTATION 331
: 504 2025-05-14
There is another way we can approach the set description interpretation of propositional logic: by
translation into a logic that can express knowledge about sets – first-order logic.
Definition Comment
pfo(x) := p(x)
fo(x) fo(x)
A := ¬A
fo(x) fo(x) fo(x)
A⊓B := A ∧B ∧ vs. ⊓
fo(x) fo(x) fo(x)
A⊔B := A ∨B ∨ vs. ⊔
fo(x) fo(x) fo(x)
A⊑B := A ⇒B ⇒ vs. ⊑
fo(x) fo(x) fo(x)
A=B := A ⇔B ⇔ vs. =
fo fo(x)
A := (∀x.A ) for formulae
: 505 2025-05-14
Translation Examples
332 CHAPTER 16. KNOWLEDGE REPRESENTATION AND THE SEMANTIC WEB
Example 16.2.8. We translate the concept axioms from ??? to fortify our intuition:
fo
son ⊑ child = ∀[Link](x) ⇒ child(x)
fo
daughter ⊑ child = ∀[Link](x) ⇒ child(x)
fo
son ⊓ daughter = ∀[Link](x) ∧ daughter(x)
fo
child ⊑ son ⊔ daughter = ∀[Link](x) ⇒ (son(x) ∨ daughter(x))
: 506 2025-05-14
: 507 2025-05-14
As we will see, the situation for PL0DL is typical for formal ontologies (even though it only offers
concepts), so we state the general description logic paradigm for ontologies. The important idea
16.2. LOGIC-BASED KNOWLEDGE REPRESENTATION 333
is that having a formal system as an ontology format allows us to capture, study, and implement
ontological inference.
Idea: Build a whole family of logics for describing sets and their relations. (tailor their
expressivity and computational properties)
Definition 16.2.14. A description logic is a formal system for talking about collections of
objects and their relations that is at least as expressive as PL0 with set-theoretic semantics
and offers individuals and relations.
A description logic has the following four components:
a formal language L with logical con-
stants ⊓, ·, ⊔, ⊑, and ≡, PL1 undecideable
ψ decideable
a set-theoretic semantics ⟨D, [ ·]]⟩,
C 7→ p ∈ Σp 1
DL
a translation into first-order logic that is ψ := ⊓ 7→ ∩
· 7→ D\·
compatible with ⟨D, [ ·]]⟩, and φ
X ∈ V0 7→ C
a calculus for L that induces a decision φ := ∧ 7→ ⊓
PL0 ¬ 7→ ·
procedure for L-satisfiability.
a terminology (or TBox): concepts and roles and a set of concept axioms that describe
them, and
assertions (or ABox): a set of individuals and statements about concept membership and
role relationships for them.
: 508 2025-05-14
For convenience we add concept definitions as a mechanism for defining new concepts from old
ones. The so-defined concepts inherit the properties from the concepts they are defined from.
Definition 16.2.16. A concept definition is a pair c=C, where c is a new concept name and
C ∈ C is a D-formula.
Example 16.2.17. We can define mother=woman ⊓ has_child.
Definition 16.2.18. A concept definition c=C is called recursive, iff c occurs in C.
Definition 16.2.19. An TBox is a finite set of concept definitions and concept axioms. It is
called acyclic, iff it does not contain recursive definitions.
Definition 16.2.20. A formula A is called normalized wrt. an TBox T , iff it does not
contain concepts defined in T . (convenient)
: 509 2025-05-14
As PL0DL does not offer any guidance on this, we will leave the discussion of ABoxes to subsec-
tion 16.3.3 when we have introduced our first proper description logic ALC.
Now that we have established the description logic paradigm, we will have a look at the
inference services that can be offered on this basis.
Before we go into details of particular description logics, we must ask ourselves what kind of in-
ference support we would want for building systems that support knowledge workers in building,
maintaining and using ontologies. An example of such a system is the Protégé system [protege:url],
which can serve for guiding our intuition.
: 510 2025-05-14
Consistency Test
Definition 16.2.24. We call a concept C consistent, iff there is no concept A, with both
C ⊑ A and C ⊑ A.
Or equivalently:
Definition 16.2.25. A concept C is called inconsistent, iff [ C]] = ∅ for all D.
Example 16.2.26 (T-Box in PL0DL ).
: 511 2025-05-14
Even though consistency in our example seems trivial, large ontologies can make machine support
necessary. This is even more true for ontologies that change over time. Say that an ontology
initially has the concept definitions woman=person⊓long_hair and man=person⊓bearded, and then
is modernized to a more biologically correct state. In the initial version the concept hermaphrodite
is consistent, but becomes inconsistent after the renovation; the authors of the renovation should
be made aware of this by the system.
The subsumption test determines whether the sets denoted by two concepts are in a subset relation.
The main justification for this is that humans tend to be aware of concept subsumption, and tend
to think in taxonomic hierarchies. To cater to this, the subsumption test is useful.
Subsumption Test
Example 16.2.27. In this case trivial
Definition 16.2.28. A subsumes B (modulo a set A of concept axioms), iff [ B]] ⊆ [ A]] for
all interpretations D that satisfy A.
Observation: Or equivalently, iff A ⊑ B ⊑ A = ⊤
Reduction to consistency test: (need to implement only one)
0
In PL , A ⇒ (A ⇒ B) is valid iff A ∧ A ∧ ¬B is inconsistent.
: 512 2025-05-14
The good news is that we can reduce the subsumption test to the consistency test, so we can
re-use our existing implementation.
The main user-visible service of the subsumption test is to compute the actual taxonomy induced
by an ontology.
Classification
The subsumption relation among all concepts (subsumption graph)
Visualization of the subsumption graph for inspection (plausibility)
Definition 16.2.29. Classification is the computation of the subsumption graph.
Example 16.2.30. (not always so trivial)
336 CHAPTER 16. KNOWLEDGE REPRESENTATION AND THE SEMANTIC WEB
object
person
: 513 2025-05-14
Remark: This only works in the presence of concept definitions, not in a purely descriptive
framework like semantic networks:
can
animal move
TBox isa isa
amoeba
has_part higher animal has_part
legs head
isa isa
pattern eat color
striped tiger elephant gray
eat
ABox Roy eat Rex Clyde
: 514 2025-05-14
If we take stock of what we have developed so far, then we can see PL0DL as a rational recon-
struction of semantic networks restricted to the “isa” relation. We relegate the “instance” relation
to subsection 16.3.3.
This reconstruction can now be used as a basis on which we can extend the expressivity and
inference procedures without running into problems.
In this subsection, we instantiate the description-logic paradigm with the prototypical logic
ALC, which we will develop now.
Reason: There are no quantifiers in PL0 (existential (∃) and universal (∀))
Idea: Use first-order predicate logic (PL1 )
: 515 2025-05-14
ALC extends the concept operators of PL0DL with binary relations (called “roles” in ALC). This
gives ALC the expressive power we had for the basic semantic networks from ???.
Syntax of ALC
Definition 16.3.2 (Concepts). (aka. “predicates” in PL1 or “propositional variables” in
PL0DL )
Concepts in DLs represent collections of objects.
Definition 16.3.7 (Grammar). The formulae of ALC are given by the following grammar:
FALC ::=C | ⊤ | ⊥ | FALC | FALC ⊓ FALC | FALC ⊔ FALC | ∃[Link] | ∀[Link]
: 516 2025-05-14
ALC restricts the quantification to range all individuals reachable as role successor. The distinction
338 CHAPTER 16. KNOWLEDGE REPRESENTATION AND THE SEMANTIC WEB
between universal and existential quantifiers clarifies an implicit ambiguity in semantic networks.
: 517 2025-05-14
: 518 2025-05-14
As before we allow concept definitions so that we can express new concepts from old ones, and
obtain more concise descriptions.
Definition 16.3.17. A concept definition is a pair consisting of a new concept name (the
definiendum) and an ALC formula (the definiens). Concepts that are not definienda are called
primitive.
16.3. A SIMPLE DESCRIPTION LOGIC: ALC 339
Example 16.3.18.
Definition rec?
man = person ⊓ ∃has_chrom.Y_chrom -
woman = person ⊓ ∀has_chrom.Y_chrom -
mother = woman ⊓ ∃has_child.person -
father = man ⊓ ∃has_child.person -
grandparent = person ⊓ ∃has_child.(mother ⊔ father) -
german = person ⊓ ∃has_parents.german +
number_list = empty_list ⊔ ∃is_first.number ⊓ ∃is_rest.number_list +
: 519 2025-05-14
As before, we can normalize a TBox by definition expansion if it is acyclic. With the introduction
of roles and quantification, concept definitions in ALC have a more “interesting” way to be cyclic
as Observation 16.3.23 shows.
: 520 2025-05-14
Now that we have motivated and fixed the syntax of ALC, we will give it a formal semantics.
The semantics of ALC is an extension of the set-theoretic semantics for PL0 , thus the interpretation
[[·]] assigns subsets of the domain of discourse to concepts and binary relations over the domain
of discourse to roles.
Semantics of ALC
340 CHAPTER 16. KNOWLEDGE REPRESENTATION AND THE SEMANTIC WEB
Definition 16.3.26. The translation of ALC into PL1 extends the one from ??? by the
following quantifier rules:
fo(x) fo(x)
∀R.φ := (∀y.R(x, y) ⇒ φfo(y) ) ∃R.φ := (∃y.R(x, y) ∧ φfo(y) )
Observation 16.3.27. The set-theoretic semantics from Definition 16.3.25 and the “semantics-
by-translation” from Definition 16.3.26 induce the same notion of satisfiability.
: 521 2025-05-14
We can now use the ALC identities above to establish a useful normal form for ALC. This will
play a role in the inference procedures we study next.
The following identitieswill be useful later on. They can be proven directly with the settings from
???; we carry this out for one of them below.
ALC Identities
1 ∃R.φ = ∀R.φ 3 ∀R.φ = ∃R.φ
2 ∀R.(φ ⊓ ψ) = ∀R.φ ⊓ ∀R.ψ 4 ∃R.(φ ⊔ ψ) = ∃R.φ ⊔ ∃R.ψ
Proof of 1
∃R.φ = D\ [ ∃R.φ]] = D\{x ∈ D | ∃y.(⟨x, y⟩ ∈ [ R]]) and (y ∈ [ φ]])}
= {x ∈ D | not ∃y.(⟨x, y⟩ ∈ [ R]]) and (y ∈ [ φ]])}
= {x ∈ D | ∀[Link] (⟨x, y⟩ ∈ [ R]]) then (y ̸∈ [ φ]])}
= {x ∈ D | ∀[Link] (⟨x, y⟩ ∈ [ R]]) then (y ∈ (D\ [ φ]]))}
= {x ∈ D | ∀[Link] (⟨x, y⟩ ∈ [ R]]) then (y ∈ [ φ]])}
= [ ∀R.φ]]
: 522 2025-05-14
The form of the identities (interchanging quantification with connectives) is reminiscient of iden-
tities in PL1 ; this is no coincidence as the “semantics by translation” of ??? shows.
Definition 16.3.28 (NNF). An ALC formula is in negation normal form (NNF), iff comple-
ment (·) is only applied to primitive concept.
Use the ALC identities as rules to compute it. (in linear time)
Example 16.3.29.
example by rule
∃R.(∀S.e ⊓ ∀S.d)
7→ ∀R.∀S.e ⊓ ∀S.d ∃R.φ 7→ ∀R.φ
7→ ∀R.(∀S.e ⊔ ∀S.d) φ ⊓ ψ 7→ φ ⊔ ψ
7→ ∀R.(∃S.e ⊔ ∀S.d) ∀R.φ 7→ ∃R.φ
7→ ∀R.(∃S.e ⊔ ∀S.d) φ 7→ φ
: 523 2025-05-14
Finally, we extend ALC with an ABox component. This mainly means that we define two new
assertions in ALC and specify their semantics and PL1 translation.
: 524 2025-05-14
If we take stock of what we have developed so far, then we see that ALC as a rational recon-
struction of semantic networks restricted to the “isa” and “instance” relations – which are the only
ones that can really be given a denotational and operational semantics.
x:c x:∀R.φ
x:c x:φ ⊓ ψ x:φ ⊔ ψ xRy x:∃R.φ
T⊥ T⊓ T⊔ T∀ T∃
⊥ x:φ x:φ x:ψ y:φ xRy
x:ψ y:φ
To test consistency of a concept φ, normalize φ to ψ, initialize the tableau with x:ψ, saturate.
Open branches ; consistent. (x arbitrary)
: 525 2025-05-14
In contrast to the tableau tableau calculi for theorem proving we have studied earlier, TALC is run
in “model generation mode”. Instead of initializing the tableau with the axioms and the negated
conjecture and hope that all branches will close, we initialize the TALC tableau with axioms and
the “membership-conjecture” that a given concept φ is satisfiable – i.e. φ h as a member x, and
hope for branches that are open, i.e. that make the conjecture true (and at the same time give a
model).
Let us now work through two very simple examples; one unsatisfiable, and a satisfiable one.
TALC Examples
Example 16.3.34 (Tableau Proofs). We have two similar conjectures about children.
This tableau shows a model: there are two persons, x and y. y is the only child of x, y
is a man.
: 526 2025-05-14
Another example: this one is more complex, but the concept is satisfiable.
7 y:ugrad y:grad T⊔
8 ⊥ open
The left branch is closed, the right one represents a model: y is a child of x, y is a graduate
student, x hat exactly one child: y.
: 527 2025-05-14
After we got an intuition about TALC , we can now study the properties of the calculus to determine
that it is a decision procedure for ALC.
: 528 2025-05-14
The soundness result for TALC is as usual: we start with a model of x:φ and show that an TALC
tableau must have an open branch.
Correctness
Lemma 16.3.36. If φ satisfiable, then TALC terminates on x:φ with open branch.
Proof: Let M := ⟨D, [ ·]]⟩ be a model for φ and w ∈ [ φ]].
344 CHAPTER 16. KNOWLEDGE REPRESENTATION AND THE SEMANTIC WEB
: 529 2025-05-14
We complete the proof by looking at all the TALC inference rules in turn.
: 530 2025-05-14
For the completeness result for TALC we have to start with an open tableau branch and construct a
model that satisfies all judgments in the branch. We proceed by building a Herbrand model, whose
domain consists of all the individuals mentioned in the branch and which interprets all concepts
and roles as specified in the branch. Not surprisingly, the model thus constructed satisfies (all
judgments on) the branch.
D : = {x | x:ψ ∈ B or z R x ∈ B}
[ c]] : = {x | x:c ∈ B}
[ R]] : = {⟨x, y⟩ | x R y ∈ B}
: 531 2025-05-14
We complete the proof by looking at all the TALC inference rules in turn.
: 532 2025-05-14
Termination
Theorem 16.3.38. TALC terminates.
To prove termination of a tableau algorithm, find a well-founded measure (function) that is
decreased by all rules
x:c x:∀R.φ
x:c x:φ ⊓ ψ x:φ ⊔ ψ xRy x:∃R.φ
ALCT cutRule T⊓ ALCT unionRule T∀ T∃
⊥ x:φ x:φ x:ψ y:φ xRy
x:ψ y:φ
: 533 2025-05-14
We can turn the termination result into a worst-case complexity result by examining the sizes of
branches.
Complexity of TALC
Idea: Work off tableau branches one after the other. (Branch size =
b space complexity)
Observation 16.3.39. The size of the branches is polynomial in the size of the input formula:
Proof sketch: Re-examine the termination proof and count: the first summand comes from
???, the second one from ??? and ???
Proof sketch: There can be exponentially many branches (already for PL0 )
: 534 2025-05-14
In summary, the theoretical complexity of ALC is the same as that for PL0 , but in practice ALC is
much more expressive. So this is a clear win.
But the description of the tableau algorithm TALC is still quite abstract, so we look at an exemplary
implementation in a functional programming language.
: 535 2025-05-14
Note that we have (so far) only considered an empty TBox: we have initialized the tableau
with a normalized concept; so we did not need to include the concept definitions. To cover “real”
ontologies, we need to consider the case of concept axioms as well.
We now extend TALC with concept axioms. The key idea here is to realize that the concept axioms
apply to all individuals. As the individuals are generated by the T∃ rule, we can simply extend
that rule to apply all the concept axioms to the newly introduced individual.
: 536 2025-05-14
The problem of this approach is that it spoils termination, since we cannot control the number of
rule applications by (fixed) properties of the input formulae. The example shows this very nicely.
We only sketch a path towards a solution.
x:d start
x:∃R.c in CA Solution: Loop-Check:
x R y1 T∃
Instead of a new variable y take an old
y 1 :c T∃
variable z, if we can guarantee that what-
y 1 :∃R.c TC∃A
ever holds for y already holds for z.
y1 R y2 T∃
y 2 :c T∃ We can only do this, iff the T∀ -rule has
y 2 :∃R.c TC∃A been exhaustively applied.
...
Theorem 16.3.44. The consistency problem of ALC with concept axioms is decidable.
348 CHAPTER 16. KNOWLEDGE REPRESENTATION AND THE SEMANTIC WEB
: 537 2025-05-14
: 538 2025-05-14
If we combine classification with the instance test, then we get the full picture of how concepts
and individuals relate to each other. We see that we get the full expressivity of semantic networks
in ALC.
Realization
Definition 16.3.47. Realization is the computation of all instance relations between ABox
objects and TBox concepts.
object
person
: 539 2025-05-14
Let us now get an intuition on what kinds of interactions between the various parts of an ontology.
property example
internally inconsistent tony:student, tony:student
TBox: student ⊓ prof
inconsistent with a TBox
ABox: tony:student, tony:prof
ABox: tony:∀has_grad.genius
implicit info that is not explicit tony has_grad mary
|= mary:genius
TBox: happy_prof = prof ⊓ ∀has_grad.genius
ABox: tony:happy_prof,
information that can be com-
tony has_grad mary
bined with TBox info
|= mary:genius
: 540 2025-05-14
Idea: Extend to more complex ABox queries. (e.g. give me all instances of φ)
: 541 2025-05-14
This completes our investigation of inference for ALC. We summarize that ALC is a logic-based on-
350 CHAPTER 16. KNOWLEDGE REPRESENTATION AND THE SEMANTIC WEB
tology language where the inference problems are all decidable/computable via TALC . But of course,
while we have reached the expressivity of basic semantic networks, there are still things that we
cannot express in ALC, so we will try to extend ALC without losing decidability/computability.
: 542 2025-05-14
Note that all these examples have in common that they are about “objects on the Web”, which is
an aspect we will come to now.
“Objects on the Web” are traditionally called “resources”, rather than defining them by their
intrinsic properties – which would be ambitious and prone to change – we take an external property
to define them: everything that has a URI is a web resource. This has repercussions on the design
of RDF.
and a property value is the value of a property, such as “Michael Kohlhase” or [Link]
info/kohlhase. (a property value can be another resource)
Definition 16.4.5. A RDF statement s (also known as a triple) consists of a resource (the
subject of s), a property (the predicate of s), and a property value (the object of s). A set of
RDF triples is called an RDF graph.
Example 16.4.6. Statements: “[This slide]subj has been [author]pred ed by [Michael Kohlhase]obj ”
: 543 2025-05-14
The crucial observation here is that if we map “subjects” and “objects” to “individuals”, and
“predicates” to “relations”, the RDF triples are just relational ABox statements of description
logics. As a consequence, the techniques we developed apply.
Note: Actually, a RDF graph is technically a labeled multigraph, which allows multiple edges
between any two nodes (the resources) and where nodes and edges are labeled by URIs.
We now come to the concrete syntax of RDF. This is a relatively conventional XML syntax that
combines RDF statements with a common subject into a single “description” of that resource.
: 544 2025-05-14
Note that XML namespaces play a crucial role in using element to encode the predicate URIs.
Recall that an element name is a qualified name that consists of a namespace URI and a proper
element name (without a colon character). Concatenating them gives a URI in our example the
predicate URI induced by the dc:creator element is [Link]
Note that as URIs go RDF URIs do not have to be URLs, but this one is and it references (is redi-
rected to) the relevant part of the Dublin Core elements specification [DCMI:dcmi-terms:tr].
RDF was deliberately designed as a standoff markup format, where URIs are used to annotate
web resources by pointing to them, so that it can be used to give information about web resources
without having to change them. But this also creates maintenance problems, since web resources
may change or be deleted without warning.
RDFa gives authors a way to embed RDF triples into web resources and make keeping RDF
statements about them more in sync.
352 CHAPTER 16. KNOWLEDGE REPRESENTATION AND THE SEMANTIC WEB
Problem: RDF is a standoff markup format (annotate by URIs pointing into other files)
Definition 16.4.8. RDFa (RDF annotations) is a markup scheme for inline annotation (as
XML attributes) of RDF triples.
Example 16.4.9.
<div xmlns:dc="[Link] id="address">
<h2 about="#address" property="dc:title">RDF as an Inline RDF Markup Format</h2>
<h3 about="#address" property="dc:creator">Michael Kohlhase</h3>
<em about="#address" property="dc:date" datatype="xsd:date"
content="2009−11−11">November 11., 2009</em>
</div>
[Link]
[Link]
[Link]
[Link]
RDFa as an Inline RDF Markup Format
2009−11−11 (xsd:date)
Michael Kohlhase
: 545 2025-05-14
In the example above, the about and property attributes are reserved by RDFa and specify the
subject and predicate of the RDF statement. The object consists of the body of the element,
unless otherwise specified e.g. by the content and datatype attributes for literals content.
Let us now come back to the fact that RDF is just an XML syntax for ABox statements.
Example 16.4.10. h is the resource for Ian Horrocks, s is the resource for Ulrike Sattler, R
is the relation “hasColleague”, and φ is the class foaf:Person
<rdf:Description about="[Link]/person/ian_horrocks">
<rdf:type rdf:resource="[Link]
<hasColleague resource="[Link]/person/uli_sattler"/>
</rdf:Description>
Idea: Now, we need an similar language for TBoxes (based on ALC)
: 546 2025-05-14
In this situation, we want a standardized representation language for TBox information; OWL
does just that: it standardizes a set of knowledge representation primitives and specifies a variety
of concrete syntaxes for them. OWL is designed to be compatible with RDF, so that the two
together can form an ontology language for the web.
Idea: Make use of resources that are values in rdf:type. (called Classes)
Definition 16.4.11. OWL (the ontology web language) is a language for encoding TBox
information about RDF classes.
: 547 2025-05-14
But there are also other syntaxes in regular use. We show the functional syntax which is inspired
by the mathematical notation of relations.
: 548 2025-05-14
We have introduced the ideas behind using description logics as the basis of a “machine-oriented
web of data”. While the first OWL specification (2004) had three sublanguages “OWL Lite”, “OWL
DL” and “OWL Full”, of which only the middle was based on description logics, with the OWL2
354 CHAPTER 16. KNOWLEDGE REPRESENTATION AND THE SEMANTIC WEB
Recommendation from 2009, the foundation in description logics was nearly universally accepted.
The semantic web hype is by now nearly over, the technology has reached the “plateau of
productivity” with many applications being pursued in academia and industry. We will not go
into these, but briefly instroduce one of the tools that make this work.
: 549 2025-05-14
SPARQL end-points can be used to build interesting applications, if fed with the appropriate data.
An interesting – and by now paradigmatic – example is the DBPedia project, which builds a large
ontology by analyzing Wikipedia fact boxes. These are in a standard HTML form which can be
analyzed e.g. by regular expressions, and their entries are essentially already in triple form: The
subject is the Wikipedia page they are on, the predicate is the key, and the object is either the
URI on the object value (if it carries a link) or the value itself.
: 550 2025-05-14
: 551 2025-05-14
We conclude our survey of the semantic web technology stack with the notion of a triplestore,
which refers to the database component, which stores vast collections of ABox triples.
FACT++: [Link]
HermiT: [Link]
Intuition: Triplestores concentrate on querying very large ABoxes with partial consideration
of the TBox, while DL reasoners concentrate on the full set of ontology inference services,
but fail on large ABoxes.
: 552 2025-05-14
Part IV
357
359
This part covers the AI subfield of “planning”, i.e. search-based problem solving with a
structured representation language for environments, states, and actions — in planning, the focus
is on the latter.
We first introduce the framework of planning (structured representation languages for problems
and actions) and then present algorithms and complexity results. Finally, we lift some of the
simplifying assumptions – deterministic, fully observable environments – we made in the previous
parts of the course.
360
Chapter 17
Planning I: Framework
: 553 2025-05-14
Planning
Ambition: Write one program that can solve all classical search problems.
Idea: For CSP, going from “state/action-level search” to “problem-description level search”
did the trick.
Definition 17.0.2. Let Π be a search problem (see chapter 6)
The blackbox description of Π is an API providing functionality allowing to construct the
state space: InitialState(), GoalTest(s), . . .
361
362 CHAPTER 17. PLANNING I: FRAMEWORK
: 554 2025-05-14
: 555 2025-05-14
Let us recall the agent-based setting we were using for the inference procedures from Part III. We
will elaborate this further in this section.
Sensors
State
How the world evolves What the world
is like now
Environment
What my actions do
Agent Actuators
Figure 2.12 A model-based reflex agent. It keeps track of the current state of the world,
Still Unspecified: using an internal model. It then chooses an action in the same way as the reflex agent. (up next)
MAKE−PERCEPT−SENTENCE:
is responsible for creating the new the effects
internal of percepts.
state description. The details of how models and
states are represented vary widely depending on the type of environment and the particular
MAKE−ACTION−QUERY: what
technology used in the agent is the
design. best
Detailed nextofaction?
examples models and updating algorithms
appear in Chapters 4, 12, 11, 15, 17, and 25.
MAKE−ACTION−SENTENCE:
Regardless of the kind ofthe effectsused,
representation of that action.
it is seldom possible for the agent to
determine the current state of a partially observable environment exactly. Instead, the box
In particular, we labeled
will look at world
“what the the effect of (Figure
is like now” time/change. (neglected so far)
2.11) represents the agent’s “best guess” (or
sometimes best guesses). For example, an automated taxi may not be able to see around the
large truck that has stopped in front of it and can only guess about what may be causing the
hold-up. Thus, uncertainty about the current state may be unavoidable, but the agent still has
: to make a decision. 556 2025-05-14
A perhaps less obvious point about the internal “state” maintained by a model-based
Now that we have theagent
notion ofdoes
is that it fluents
not have to represent
to describe the
“what the percepts
world is like now” at
in a a given
literal [Link]
For point, let us try
to model how they influence the agent’s world model.
Example 17.1.5. E.g., if the agent perceives a draft at at time t, when it is in cell [x, y],
then there must be a breeze there:
Axioms like these model the agent’s sensors – here that they are totally reliable: there is
a breeze, iff the agent feels a draft at.
Definition 17.1.6. We call fluents that describe the agent’s sensors sensor axioms.
Problem: Where do fluents like Ag@(t, x, y) come from?
: 557 2025-05-14
You may have noticed that for the sensor axioms we have only used first-order logic. There is a
general story to tell here: If we have finite domains (as we do in the Wumpus cave) we can always
364 CHAPTER 17. PLANNING I: FRAMEWORK
“compile first-order logic into propositional logic”; if domains are infinite, we usually cannot.
We will develop this here before we go on with the Wumpus models.
Problem: Unless we restrict ourselves to finite domains and an end time tend we have
infinitely many axioms. Even then, formalization in PL0 and PLnq is very tedious.
Solution: Formalize in first-order logic and then compile down:
1. enumerate ranges of bound variables, instantiate body, (; PLnq )
2. translate PLnq atoms to propositional variables. (; PL0 )
In Practice: The choice of domain, end time, and logic is up to agent designer, weighing
expressivity vs. efficiency of inference.
WLOG: We will use PL1 in the following. (easier to read)
: 558 2025-05-14
We now continue to our logic-based agent models: Now we focus on effect axioms to model the
effects of an agent’s actions.
Example 17.1.9. If the agent is in cell [1, 1] facing east at time 0 and goes forward, she
is in cell [2, 1] and no longer in [1, 1]:
: 559 2025-05-14
Unfortunately, the percept fluents, sensor axioms, and effect axioms are not enough, as we will
show in Example 17.1.10. We will see that this is a more general problem – the famous frame
problem that needs to be considered whenever we deal with change in environments.
17.1. LOGIC-BASED PLANNING 365
Problem: For an agent with n actions and an environment with m fluents, we need O(nm)
frame axioms.
Representing and reasoning with them easily drowns out the sensor and transition models.
: 560 2025-05-14
then some special code for action selection, and then (up next)
action := POP(plan)
TELL(KB, MAKE−ACTION−SENTENCE(action,t))
t := t + 1
return action
: 561 2025-05-14
Note that OK wumpus, and glitter are fluents, since the Wumpus might have died or the
gold might have been grabbed.
: 562 2025-05-14
And finally the route planning part of the code. This is essentially just A∗ search.
Evaluation: Even though this works for the Wumpus world, it is not the “universal, logic-
based problem solver” we dreamed of!
Planning tries to solve this with another representation of actions. (up next)
: 563 2025-05-14
: 564 2025-05-14
: 565 2025-05-14
{rabbit(r1)} {white(r1)}
rabbit
: 566 2025-05-14
Approval:
Approval:
Necessary
Necessary
Approval: Decide CQ
Approval:
not Decide CQ
not
Necessary Approval
Create CQ Necessary Approval
Create CQ
Submit CQ
Submit CQ
Check CQ Check CQ
Check CQ Check CQ
Completeness Consistency
Completeness Consistency
Mark CQ as
Mark CQ as
Accepted
Accepted
Create Follow-
Create Follow-
Up for CQ
Up for CQ
Check CQ
Check CQ
Approval
Approval
Status
Status Archive CQ
Archive CQ
Input:
I model of behavior of activities on business objects, process endpoint.
I Input:
Input: SAP-scale
SAP-scale model
model of
of behavior
behavior of
of activities
activities on
on Business
Business Objects,
Objects, process
process
endpoint.
Output:
endpoint.
Process template leading to this point.
I
I Output:
Output: Process
Process template
template leading
leading to
to this
this point.
point.
: 567 2025-05-14
DMZ
Web Server Application Server
Internet
Router
Firewall
Attacker
Workstation
DB Server
SENSITIVE USERS
DMZ
Web Server Application Server
Internet
Router
Firewall
Attacker
Workstation
DB Server
SENSITIVE USERS
17.2. PLANNING: INTRODUCTION 369
DMZ
Web Server Application Server
Internet
Router
Firewall
Attacker
Workstation
DB Server
SENSITIVE USERS
DMZ
Web Server Application Server
Internet
Router
Firewall
Attacker
Workstation
DB Server
SENSITIVE USERS
: 568 2025-05-14
Quick: Rapid prototyping: 10s lines of problem description vs. 1000s lines of C++ code.
(E.g. language generation)
Flexible: Adapt/maintain the description. (E.g. network security)
Intelligent: Determines automatically how to solve a complex problem efficiently! (The
ultimate goal, no?!)
Efficiency loss: Without any domain-specific knowledge about chess, you don’t beat Kas-
parov . . .
Trade-off between “automatic and general” vs. “manual work but efficient”.
: 569 2025-05-14
370 CHAPTER 17. PLANNING I: FRAMEWORK
: 570 2025-05-14
Search Planning
States Lisp data structures Logical sentences
Actions Lisp code Preconditions/outcomes
Goal Lisp code Logical sentence (conjunction)
Plan Sequence from S0 Constraints on actions
: 571 2025-05-14
For A∗
order f rontier by g + h instead of h (line 4)
insert g(n′ ) + h(n′ ) instead of h(n′ ) to f rontier (last line)
Is greedy best-first search optimal? No ; satisficing planning.
Is A∗ optimal? Yes, but only if h is admissible ; optimal planning, with such h.
: 572 2025-05-14
n blocks, 1 hand.
A single action either takes a block with the hand or puts a block
we’re holding onto some other block/the table.
Observation 17.2.4. State spaces typically are huge even for simple problems.
In other words: Even solving “simple problems” automatically (without help from a human)
requires a form of intelligence.
With blind search, even the largest super computer in the world won’t scale beyond 20
blocks!
: 573 2025-05-14
: 574 2025-05-14
Focussing on heuristic search as the solution method, this is the main question that needs
to be answered.
: 575 2025-05-14
Gives you some background, and motivates our choice to focus on heuristic search.
2. The STRIPS Planning Formalism: Which concrete planning formalism will we be using?
Lays the framework we’ll be looking at.
3. The PDDL Language: What do the input files for off-the-shelf planning software look like?
: 576 2025-05-14
: 577 2025-05-14
: 578 2025-05-14
which pairs of action can achieve which pairs of facts; in a backward phase, search this
graph starting at goals and excluding options proved to not be feasible.
Keywords/cites: [blum:furst:ijcai-95; blum:furst:ai-97; koehler:etal:ecp-97],
action/fact mutexes, step-optimal plan, . . .
Planning as SAT:
SAT variables at(A)0 , at(B)0 , move(A, B)0 , move(A, C)0 , at(A)1 , at(B)1 ; clauses to
F T
encode transition behavior e.g. at(B)1 ∨ move(A, B)0 ; unit clauses to encode initial
T T T
state at(A)0 , at(B)0 ; unit clauses to encode goal at(B)1 .
Popular when: 1996 – today.
Approach: From planning task description, generate propositional CNF formula φk that
is satisfiable iff there exists a plan with k steps; use a SAT solver on φk , for different
values of k.
Keywords/cites: [kautz:selman:ecai-92; kautz:selman:aaai-96; rintanen:etal:ai-06;
rintanen:cp-10], SAT encoding schemes, BlackBox, . . .
: 579 2025-05-14
: 580 2025-05-14
: 581 2025-05-14
: 582 2025-05-14
A
C B
A B C
Simple planners that split the goal into subgoals on(A, B) and on(B, C) fail:
: 583 2025-05-14
STRIPS Planning
376 CHAPTER 17. PLANNING I: FRAMEWORK
I’ll outline some extensions beyond STRIPS later on, when we discuss PDDL.
Historical note: STRIPS [fikes:nilsson:ai-71] was originally a planner (cf. Shakey), whose
language actually wasn’t quite that simple.
: 584 2025-05-14
Let us now do the math for the ideas above. Luckily, we can already build on the notion of a search
problem, which does the heavy lifting. We only need to specialize the abstract/atomic notions of
searchprob/states and searchprob/actions to structured ones and adapt the searchprob/transition
model accordingly; then all the notions from search transfer to the planning setting.
: 585 2025-05-14
To build some intutions on the notion of a STRIPS task, let us look at a simple concrete example,
which can already show some of the issues involved.
“TSP” in Australia
17.4. STRIPS PLANNING 377
Strictly speaking, this is not actually a TSP problem instance; simplified/adapted for illustra-
tion.
: 586 2025-05-14
Note: This “TSP” allows moving through same city more than once; however an optimal plan
won’t do that – in case we have connections between all cities as in original TSP – provided the
triangle equation holds on the specified distances. That is, given an arbitrary map, just insert the
shortest road distance between any pair of cities as the direct edge, and we get a TSP instance
that’s equivalent to a shortest visit of the map when dropping the “each city only once” constraint.
Plan: ⟨drv(Sy, Br), drv(Br, Sy), drv(Sy, Ad), drv(Ad, Pe), drv(Pe, Ad), . . .
. . . , drv(Ad, Da), drv(Da, Ad), drv(Ad, Sy)⟩
: 587 2025-05-14
To have a look at the state spaces in planning, we simplify the TSP above further – so that the
diagrams fit onto the slides.
Let TSP− be the STRIPS task, ⟨pre, add, del, S , A, T , I , G , successorfunction, successorstate, apply⟩,
where
Facts F: {at(x), vis(x) | x ∈ {Sy, Ad, Br}}.
Searchprob/initial state searchprob/state I: {at(Sy), vis(Sy)}.
Searchprob/goal state G: {vis(x) | x ∈ {Sy, Ad, Br}} (note: noat(Sy))
Searchprob/actions A: a ∈ A: drv(x, y) where x y have a road.
preconditions prea : {at(x)}.
add list adda : {at(y), vis(y)}.
delete list dela : {at(x)}.
: 588 2025-05-14
With this simplification, we can visualize the whole state space and look for plans.
at(Ad)
at(Br) drv(Br, Sy) at(Sy) drv(Sy, Ad) vis(Sy)
vis(Sy) vis(Sy)
vis(Br)
vis(Br) vis(Br)
vis(Ad)
drv(Ad, Sy)
drv(Sy, Br)
at(Sy)
at(Sy) vis(Sy)
vis(Sy) vis(Ad)
vis(Br)
drv(Sy, Ad)
drv(Br, Sy)
at(Br)
at(Ad) at(Sy)
vis(Sy)
vis(Sy) vis(Sy)
drv(Ad, Sy) drv(Sy, Br) vis(Ad)
vis(Ad) vis(Ad)
vis(Br)
: 589 2025-05-14
We now look at a different, more complex example: the famous blocks world.
The Blocksworld
Definition 17.4.6. The blocks world is a simple planning domain: a set of wooden blocks
of various shapes and colors sit on a table. The goal is to build one or more vertical stacks
of blocks. Only one block may be moved at a time: it may either be placed on the table or
placed atop another block.
Example 17.4.7.
E
D C B
E A B C A D
: 590 2025-05-14
380 CHAPTER 17. PLANNING I: FRAMEWORK
: 591 2025-05-14
The next example for a planning task is not obvious at first sight, but has been quite influential,
showing that many industry problems can be specified declaratively by formalizing the domain
and the particular planning tasks in PDDL and then using off-the-shelf planners to solve them.
[KoeSch:ecpp00] reports that this has significantly reduced labor costs and increased maintain-
ability of the implementation.
VIP D
NA: Never-alone
AT: Attendant.
AT
P: Normal passenger
: 592 2025-05-14
17.5. PARTIAL ORDER PLANNING 381
A
C B
A B C
Simple planners that split the goal into subgoals on(A, B) and on(B, C) fail:
: 593 2025-05-14
Before we go into the details, let us try to understand the main ideas of partial order planning.
Organize the planning steps in a DAG that supports multiple paths from initial to goal
state
nodes (steps) are labeled with searchprob/actions (searchprob/actions can occur
multiply)
edges with propositions added by source and presupposed by target
: 594 2025-05-14
We now make the ideas discussed above concrete by giving a mathematical formulation. It is
advantageous to cast a partially ordered plan as a labeled DAG rather than a partial ordering
since it draws the attention to the difference between searchprob/actions and steps.
Definition 17.5.7. Partial order planning is the process of computing complete and acyclic
partially ordered plans for a given planning task.
: 595 2025-05-14
p
Notation: A causal link S −→ T can also be denoted by a direct arrow between the effects
p of S and the preconditions p of T in the STRIPS action notation above.
Show temporal constraints as dashed arrows.
: 596 2025-05-14
Planning Process
Definition 17.5.10. Partial order planning is search in the space of partial plans via the
following operations:
: 597 2025-05-14
Start
Sell(SM, M ilk)At(Home) Sell(HW S, Drill)Sell(SM, B
Start
Sell(SM, M ilk)At(Home) Sell(HW S, Drill)Sell(SM, B
Start
Sell(SM, M ilk)At(Home) Sell(HW S, Drill)Sell(SM, B
At(Home)
Go(HW S)
Start
Sell(SM, M ilk)At(Home) Sell(HW S, Drill)Sell(SM, B
At(Home)
Go(HW S)
At(X)
Go(SM )
Start
Sell(SM, M ilk)At(Home) Sell(HW S, Drill)Sell(SM, B
At(Home)
Go(HW S)
At(X)
Go(SM )
Start
Sell(SM, M ilk)At(Home) Sell(HW S, Drill)Sell(SM, B
At(Home)
Go(HW S)
At(X)
Go(SM )
At(SM )
Go(Home)
Start
Sell(SM, M ilk)At(Home) Sell(HW S, Drill)Sell(SM, B
At(Home)
Go(HW S)
At(HW S)
Go(SM )
At(SM )
Go(Home)
Here we show a successful search for a partially ordered plan. We start out by initializing the plan
by with the respective start and finish steps. Then we consecutively add steps to fulfill the open
preconditions – marked in red – starting with those of the finish step.
In the end we add three temporal constraints that complete the partially ordered plan.
The search process for the links and steps is relatively plausible and standard in this example, but
we do not have any idea where the temporal constraints should systematically come from. We
look at this next.
17.5. PARTIAL ORDER PLANNING 391
Go(SM )
At(SM )
demotion =
b put before
Go(Home)
At(Home)
At(SM ) promotion =
b put after
Buy(M ilk)
: 599 2025-05-14
: 600 2025-05-14
: 601 2025-05-14
Properties of POP
Nondeterministic algorithm: backtracks at choice points on failure:
choice of Sadd to achieve Sneed ,
choice of demotion or promotion for clobberer,
selection of Sneed is irrevocable.
: 602 2025-05-14
: 603 2025-05-14
Start
On(C, A) On(A, T ) Cl(B) On(B, T ) Cl(C)
Initializing the partial order plan with with Start and Finish.
Start
On(C, A) On(A, T ) Cl(B) On(B, T ) Cl(C)
Cl(B) Cl(C)
M ove(B, C)
¬Cl(C), On(B, C)
Start
On(C, A) On(A, T ) Cl(B) On(B, T ) Cl(C)
Cl(B) Cl(C)
M ove(B, C)
¬Cl(C), On(B, C)
Cl(A)Cl(A) Cl(B)
M ove(A, B)
¬Cl(B) On(A, B)
Start
On(C, A) On(A, T ) Cl(B) On(B, T ) Cl(C)
Start
On(C, A) On(A, T ) Cl(B) On(B, T ) Cl(C)
Start
On(C, A) On(A, T ) Cl(B) On(B, T ) Cl(C)
Start
On(C, A) On(A, T ) Cl(B) On(B, T ) Cl(C)
: 604 2025-05-14
: 605 2025-05-14
E
D C B
E A B C A D
: 606 2025-05-14
E
D C B
E A B C A D
: 607 2025-05-14
: 608 2025-05-14
: 609 2025-05-14
17.7 Conclusion
17.7. CONCLUSION 399
Summary
General problem solving attempts to develop solvers that perform well across a large class of
problems.
Planning, as considered here, is a form of general problem solving dedicated to the class
of classical search problems. (Actually, we also address inaccessible, stochastic, dynamic,
continuous, and multi-agent settings.)
Heuristic search planning has dominated the International Planning Competition (IPC). We
focus on it here.
STRIPS is the simplest possible, while reasonably expressive, language for our purposes. It
uses Boolean variables (facts), and defines searchprob/actions in terms of precondition, add
list, and delete list.
PDDL is the de-facto standard language for describing planning problems.
: 610 2025-05-14
Suggested Reading:
• Chapters 10: Classical Planning and 11: Planning and Acting in the Real World in [RusNor:AIMA09].
– Although the book is named “A Modern Approach”, the planning section was written long
before the IPC was even dreamt of, before PDDL was conceived, and several years before
heuristic search hit the scene. As such, what we have right now is the attempt of two outsiders
trying in vain to catch up with the dramatic changes in planning since 1995.
– Chapter 10 is Ok as a background read. Some issues are, imho, misrepresented, and it’s far
from being an up-to-date account. But it’s Ok to get some additional intuitions in words
different from my own.
– Chapter 11 is useful in our context here because we don’t cover any of it. If you’re interested
in extended/alternative planning paradigms, do read it.
• A good source for modern information (some of which we covered in the course) is Jörg Hoff-
mann’s Everything You Always Wanted to Know About Planning (But Were Afraid to Ask)
[hoffmann:ki-11] which is available online at [Link]
papers/[Link]
400 CHAPTER 17. PLANNING I: FRAMEWORK
Chapter 18
18.1 Introduction
Reminder: Our Agenda for This Topic
chapter 17: Background, planning languages, complexity.
Sets up the framework. computational complexity is essential to distinguish different
algorithmic problems, and for the design of heuristic functions.
This Chapter: How to automatically generate a heuristic function, given planning language
input?
Focussing on heuristic search as the solution method, this is the main question that needs
to be answered.
: 611 2025-05-14
(3,3,1)
03/23
In planning, this is referred to as forward search, or forward state-space search.
401
Kohlhase: Künstliche Intelligenz 1 532 July 5, 2018
402 CHAPTER 18. PLANNING II: ALGORITHMS
: 612 2025-05-14
cos
t est
ateim
h
cost esti
mate h goal
init
mate h
cost esti
h
ate
t e stim
cos
Heuristic function h estimates the cost of an optimal path from a state s to the goal state;
search prefers to expand states s with small h(s).
Live Demo vs. Breadth-First Search:
[Link]
: 614 2025-05-14
18.2. HOW TO RELAX 403
Exactly like our definition from chapter 6. Except, because we assume unit costs here, we
use N instead of R+ .
Definition 18.1.2. Let Π be a STRIPS task with states S. The perfect heuristic h∗ assigns
every s ∈ S the length of a shortest path from s to a goal state, or ∞ if no such path exists.
A heuristic h for Π is admissible if, for all s ∈ S, we have h(s) ≤ h∗ (s).
Exactly like our definition from chapter 6, except for path length instead of path cost (cf.
above).
In all cases, we attempt to approximate h∗ (s), the length of an optimal plan for s. Some
algorithms guarantee to lower bound h∗ (s).
: 615 2025-05-14
: 616 2025-05-14
How to Relax
Recall: We introduced the concept of a relaxed search problem (allow cheating) to derive
heuristics from them.
404 CHAPTER 18. PLANNING II: ALGORITHMS
P N ∪ {∞}
h∗P
P′ h∗P ′
R
1. You have a class P of problems, whose perfect heuristic h∗P you wish to estimate.
2. You define a class P ′ of simpler problems, whose perfect heuristic h∗P ′ can be used to
estimate h∗P .
3. You define a transformation – the relaxation mapping R – that maps instances Π ∈ P into
instances Π′ ∈ P ′ .
4. Given Π ∈ P, you let Π′ := R(Π), and estimate h∗ P (Π) by h∗ P ′ (Π′ ).
: 617 2025-05-14
: 618 2025-05-14
: 619 2025-05-14
: 620 2025-05-14
Relaxation in Route-Finding
406 CHAPTER 18. PLANNING II: ALGORITHMS
: 621 2025-05-14
: 622 2025-05-14
We will start with a very simple relaxation, which could be termed “positive thinking”: we do not
18.2. HOW TO RELAX 407
consider preconditions of searchprob/actions and leave out the delete lists as well.
R h∗P ′
R(Πs )
Here, Πs is Π with initial state replaced by s, i.e., Π := ⟨pre, add, del, S , A, T , I , G , successorfunction, successorstat
changed to Πs := ⟨F, A, {s}, G⟩: The task of finding a plan for search state s.
A common student error is to instead apply the relaxation once to the whole problem,
then doing the whole search “within the relaxation”.
The next slide illustrates the correct search process in detail.
: 623 2025-05-14
We are here
AC
Relaxed problem:
State s: AC; goal G: AD.
Searchprob/actions A: add.
hR (s) =1: [ulD].
Greedy best-first search: (tie-breaking: alphabetic)
408 CHAPTER 18. PLANNING II: ALGORITHMS
We are here
1
AC
Relaxed problem:
State s: AC; goal G: AD.
Searchprob/actions A: add.
hR (s) =1: [ulD].
Greedy best-first search: (tie-breaking: alphabetic)
We are here
1
AC
Real problem:
State s: BC; goal G: AD.
Searchprob/actions A:
pre, add, del.
drAB
AC −−−−→ BC.
Greedy best-first search: (tie-breaking: alphabetic)
We are here
1 drAB
AC BC
Relaxed problem:
State s: BC; goal G: AD.
Searchprob/actions A: add.
hR (s) =2: [drBA, ulD].
Greedy best-first search: (tie-breaking: alphabetic)
We are here
1 drAB
AC BC
Relaxed problem:
State s: BC; goal G: AD.
Searchprob/actions A: add.
hR (s) =2: [drBA, ulD].
Greedy best-first search: (tie-breaking: alphabetic)
18.2. HOW TO RELAX 409
We are here
1 drAB 2
AC BC
Real problem:
State s: CC; goal G: AD.
Searchprob/actions A:
pre, add, del.
drBC
BC −−−−→ CC.
Greedy best-first search: (tie-breaking: alphabetic)
We are here
1 drAB 2 drBC
AC BC CC
Relaxed problem:
State s: CC; goal G: AD.
Searchprob/actions A: add.
hR (s) =2: [drBA, ulD].
Greedy best-first search: (tie-breaking: alphabetic)
We are here
1 drAB 2 drBC
AC BC CC
Relaxed problem:
State s: CC; goal G: AD.
Searchprob/actions A: add.
hR (s) =2: [drBA, ulD].
Greedy best-first search: (tie-breaking: alphabetic)
We are here
1 drAB 2 drBC 2
AC BC CC
Real problem:
State s: AC; goal G: AD.
Searchprob/actions A:
pre, add, del.
drBA
BC −−−−→ AC.
Greedy best-first search: (tie-breaking: alphabetic)
410 CHAPTER 18. PLANNING II: ALGORITHMS
We are here
1 drAB 2 drBC 2
dr
AC BC B ACC
AC
Real problem:
State s: AC; goal G: AD.
Searchprob/actions A:
pre, add, del.
Duplicate state, prune.
Greedy best-first search: (tie-breaking: alphabetic)
We are here
1 drAB 2 drBC 2
dr
AC BC B ACC
D
AC
Real problem:
State s: DC; goal G: AD.
Searchprob/actions A:
pre, add, del.
drCD
CC −−−−→ DC.
Greedy best-first search: (tie-breaking: alphabetic)
We are here
D DC
C
1 drAB 2 drBC 2 dr
dr
AC BC B ACC
D
AC
Relaxed problem:
State s: DC; goal G: AD.
Searchprob/actions A: add.
hR (s) =2: [drBA, ulD].
Greedy best-first search: (tie-breaking: alphabetic)
18.2. HOW TO RELAX 411
We are here
D DC
C
1 drAB 2 drBC 2 dr
dr
AC BC B ACC
D
AC
Relaxed problem:
State s: DC; goal G: AD.
Searchprob/actions A: add.
hR (s) =2: [drBA, ulD].
Greedy best-first search: (tie-breaking: alphabetic)
We are here
2
D DC
rC
1 drAB 2 drBC 2 d
dr
AC BC B ACC
D
AC
Real problem:
State s: CT ; goal G: AD.
Searchprob/actions A:
pre, add, del.
loC
CC −−→ CT .
Greedy best-first search: (tie-breaking: alphabetic)
We are here
2
D DC
rC
1 drAB 2 drBC 2 dloC
dr
AC BC B ACC CT
D
AC
Relaxed problem:
State s: CT ; goal G: AD.
Searchprob/actions A: add.
hR (s) =2: [drBA, ulD].
Greedy best-first search: (tie-breaking: alphabetic)
412 CHAPTER 18. PLANNING II: ALGORITHMS
We are here
2
D DC
rC
1 drAB 2 drBC 2 dloC
dr
AC BC B ACC CT
D
AC
Relaxed problem:
State s: CT ; goal G: AD.
Searchprob/actions A: add.
hR (s) =2: [drBA, ulD].
Greedy best-first search: (tie-breaking: alphabetic)
We are here
2
D
rC DC
1 drAB 2 drBC 2 dloC 2
dr
AC BC B ACC CT
D
AC
Real problem:
State s: BC; goal G: AD.
Searchprob/actions A:
pre, add, del.
drCB
CC −−−−→ BC.
Greedy best-first search: (tie-breaking: alphabetic)
We are here
2
D DC
rC
1 drAB 2 drBC 2 dloC 2
dr dr
AC BC B ACC C BCT
D
AC BC
Real problem:
State s: BC; goal G: AD.
Searchprob/actions A:
pre, add, del.
Duplicate state, prune.
Greedy best-first search: (tie-breaking: alphabetic)
18.2. HOW TO RELAX 413
We are here
2
D DC
rC
1 drAB 2 drBC 2 dloC 2
dr dr
AC BC B ACC C BCT
D D
AC BC
Real problem:
State s: CT ; goal G: AD.
Searchprob/actions A:
pre, add, del.
Successors: BT , DT , CC.
Greedy best-first search: (tie-breaking: alphabetic)
We are here
2 2
D B
rC DCdrC BT
1 drAB 2 drBC 2 dloC 2 drCD 2
dr dr u
AC BC B ACC C BCT lC DT
D D D
AC BC CC
Real problem:
State s: BT ; goal G: AD.
Searchprob/actions A:
pre, add, del.
Successors: AT , BB, CT .
Greedy best-first search: (tie-breaking: alphabetic)
1
AT
2
A
drB
We are here B BB
2 ul
2 drBC D
D B
r C DC rC BT CT
d
1 drAB 2 drBC 2 dloC 2 drCD 2
dr dr u
AC BC B ACC C BCT lC DT
D D D
AC BC CC
Real problem:
State s: AT ; goal G: AD.
Searchprob/actions A:
pre, add, del.
Successors: AA, BT .
Greedy best-first search: (tie-breaking: alphabetic)
414 CHAPTER 18. PLANNING II: ALGORITHMS
1 ulA 1
dr
AT ABAA
2 D
A
drB
We are here B BB BT
2 ul
2 drBC D
D B
d rC DCdrC BT CT
1 drAB 2 drBC 2 loC 2 drCD 2
dr dr u
AC BC B ACC C BCT lC DT
D D D
AC BC CC
Real problem:
State s: AA; goal G: AD.
Searchprob/actions A:
pre, add, del.
Successors: BA, AT .
Greedy best-first search: (tie-breaking: alphabetic)
1 ulA 1 drAB 2
dr l
AT ABAA oA BA
2 D D
A
drB
We are here B BB BT AT
2 ul
2 drBC D
D B
d rC DCdrC BT CT
1 drAB 2 drBC 2 loC 2 drCD 2
dr dr u
AC BC B ACC C BCT lC DT
D D D
AC BC CC
Real problem:
State s: BA; goal G: AD.
Searchprob/actions A:
pre, add, del.
Successors: CA, AA.
Greedy best-first search: (tie-breaking: alphabetic)
We are here B BB BT AT AA
2 ul
2 drBC D
D B
rC DCdrC BT CT
1 drAB 2 drBC 2 dloC 2 drCD 2
dr dr u
AC BC B ACC C BCT lC DT
D D D
AC BC CC
18.3. DELETE RELAXATION 415
Real problem:
State s: BA; goal G: AD.
Searchprob/actions A:
pre, add, del.
Successors: CA, AA.
Greedy best-first search: (tie-breaking: alphabetic)
A
drB
We are here B BB BT AT AA
2 ul
2 drBC D
D B
r C DC rC BT CT
d
1 drAB 2 drBC 2 dloC 2 drCD 2
dr dr u
AC BC B ACC C BCT lC DT
D D D
AC BC CC
: 624 2025-05-14
P N ∪ {∞}
h∗P
P′ ⊆ P h∗P ′
R
: 625 2025-05-14
“When the world changes, its previous state remains true as well.”
Real world: (before)
Relaxed world:
(before)
Relaxed world:
(after)
: 626 2025-05-14
: 627 2025-05-14
Real world:
Relaxed world:
418 CHAPTER 18. PLANNING II: ALGORITHMS
: 628 2025-05-14
In other words, the class of simpler problems P ′ is the set of all STRIPS tasks with empty
delete lists, and the relaxation mapping R drops the delete lists.
Definition 18.3.2 (Relaxed Plan). Let Π := ⟨pre, add, del, S , A, T , I , G , successorfunction, successorstate, apply⟩
be a STRIPS task, and let s be a searchprob/state. A relaxed plan for s is a plan for
+
⟨F, A, s, G⟩ . A relaxed plan for I is called a relaxed plan for Π.
A relaxed plan for s is an searchprob/action sequence that solves s when pretending that all
delete lists are empty.
Also called delete-relaxed plans: “relaxation” is often used to mean delete relaxation by
default.
: 629 2025-05-14
+
5. drv(Ad, Da) : {at(Da), vis(Da), at(Pe), vis(Pe), at(Ad), vis(Ad), at(Br), vis(Br), at(Sy), vis(Sy)}.
: 630 2025-05-14
Relaxed plan:
+ + + + +
[drive(A, B) , drive(B, C) , load(C) , drive(C, D) , unload(D) ]
We don’t need to drive the truck back, because “it is still at A”.
: 631 2025-05-14
PlanEx+
Definition 18.3.3 (Relaxed Plan Existence Problem). By PlanEx+ , we denote the prob-
lem of deciding, given a STRIPS task Π := ⟨pre, add, del, S , A, T , I , G , successorfunction, successorstate, apply⟩,
whether or not there exists a relaxed plan for Π.
2. The algorithm terminates after at most |F | iterations, and thus runs in polynomial time.
3. Correctness: See slide 635
□
: 632 2025-05-14
Iterations on F :
1. {at(Sy), vis(Sy)}
2. ∪ {at(Ad), vis(Ad), at(Br), vis(Br)}
3. ∪ {at(Da), vis(Da), at(Pe), vis(Pe)}
: 633 2025-05-14
1. {truck(A), pack(C)}
2. ∪{truck(B)}
3. ∪{truck(C)}
4. ∪{truck(D), pack(T )}
5. ∪{pack(A), pack(B), pack(D)}
Iterations on F :
1. {truck(A), pack(C)}
2. ∪{truck(B)}
3. ∪{truck(C)}
4. ∪{pack(T )}
5. ∪{pack(A), pack(B)}
6. ∪∅
: 634 2025-05-14
: 635 2025-05-14
P′ ⊆ P h∗P ′
R
: 636 2025-05-14
: 637 2025-05-14
h+ is Admissible
Lemma 18.4.3. Let Π := ⟨pre, add, del, S , A, T , I , G , successorfunction, successorstate, apply⟩
be a STRIPS task, and let s be a state. If [a1 , . . ., an ] is a plan for Πs := ⟨F, A, {s}, G⟩, then
[a+ + +
1 , . . ., an ] is a plan for Π .
If we ignore deletes, the states along the plan can only get bigger.
3. With the lemma above, any plan for Π also constitutes a plan for Π+
s .
□
18.4. THE h+ HEURISTIC 423
: 638 2025-05-14
We are here
AC
Relaxed problem:
We are here
AC
Relaxed problem:
We are here
5
AC
Real problem:
We are here
5 drAB
AC BC
Relaxed problem:
We are here
5 drAB
AC BC
Relaxed problem:
State s: BC; goal G: AD.
Searchprob/actions A:
pre, add.
h+ (s) =5: e.g.
[drBA, drBC, drCD, loC, ulD].
Greedy best-first search: (tie-breaking: alphabetic)
18.4. THE h+ HEURISTIC 425
We are here
5 drAB 5
AC BC
Real problem:
We are here
5 drAB 5 drBC
AC BC CC
Relaxed problem:
We are here
5 drAB 5 drBC
AC BC CC
Relaxed problem:
State s: CC; goal G: AD.
Searchprob/actions A:
pre, add.
h+ (s) =5: e.g.
[drCB, drBA, drCD, loC, ulD].
Greedy best-first search: (tie-breaking: alphabetic)
426 CHAPTER 18. PLANNING II: ALGORITHMS
We are here
drAB 5 drBC 5
AC BC CC
Real problem:
We are here
5 drAB 5 drBC 5
dr
AC BC B ACC
AC
Real problem:
State s: AC; goal G: AD.
Searchprob/actions A:
pre, add, del.
Duplicate search-
prob/state, prune.
We are here
5 drAB 5 drBC 5
dr
AC BC B ACC
D
AC
18.4. THE h+ HEURISTIC 427
Real problem:
State s: DC; goal G: AD.
Searchprob/actions A:
pre, add, del.
drCD
CC −−−−→ DC.
We are here
D DC
r C
5 drAB 5 drBC 5 d
dr
AC BC B ACC
D
AC
Relaxed problem:
State s: DC; goal G: AD.
Searchprob/actions A:
pre, add.
h+ (s) =5: e.g.
[drDC, drCB, drBA, loC, ulD].
Greedy best-first search: (tie-breaking: alphabetic)
We are here
D DC
rC
5 drAB 5 drBC 5 d
dr
AC BC B ACC
D
AC
Relaxed problem:
State s: DC; goal G: AD.
Searchprob/actions A:
pre, add.
We are here
5
D DC
rC
5 drAB 5 drBC 5 d
dr
AC BC B ACC
D
AC
Real problem:
State s: CT ; goal G: AD.
Searchprob/actions A:
pre, add, del.
loC
CC −−→ CT .
We are here
5
D
rC DC
5 drAB 5 drBC 5 dloC
dr
AC BC B ACC CT
D
AC
Relaxed problem:
We are here
5
D DC
rC
5 drAB 5 drBC 5 dloC
dr
AC BC B ACC CT
D
AC
18.4. THE h+ HEURISTIC 429
Relaxed problem:
State s: CT ; goal G: AD.
Searchprob/actions A:
pre, add.
h+ (s) =4: e.g.
[drCB, drBA, drCD, ulD].
Greedy best-first search: (tie-breaking: alphabetic)
We are here
5
D DC
rC
5 drAB 5 drBC 5 dloC 4
dr
AC BC B ACC CT
D
AC
Real problem:
State s: BC; goal G: AD.
Searchprob/actions A:
pre, add, del.
drCB
CC −−−−→ BC.
We are here
5
D
rC DC
5 drAB 5 drBC 5 dloC 4
dr dr
AC BC B ACC C BCT
D
AC BC
Real problem:
State s: BC; goal G: AD.
Searchprob/actions A:
pre, add, del.
We are here
5
D DC
rC
5 drAB 5 drBC 5 dloC 4
dr dr
AC BC B ACC C BCT
D D
AC BC
Real problem:
State s: CT ; goal G: AD.
Searchprob/actions A:
pre, add, del.
Successors: BT , DT , CC.
We are here
5 4
D DC B BT
rC C
5 drAB 5 drBC 5 dloC 4 drCD dr 4
dr dr ul
AC BC B C C DT
ACC BCT
D D D
AC BC CC
Real problem:
4
AT
5
A
drB
We are here B BB
5 ul
4 drBC D
D B
drC DCdrC BT CT
5 drAB 5 drBC 5 loC 4 drCD 4
dr dr u
AC BC B ACC C BCT lC DT
D D D
AC BC CC
18.4. THE h+ HEURISTIC 431
Real problem:
State s: AT ; goal G: AD.
Searchprob/actions A:
pre, add, del.
Successors: AA, BT .
4 ulA 5
dr
AT ABAA
5 D
A
dr B
We are here B BB BT
5 ul
4 drBC D
D B
d rC DCdrC BT CT
5 drAB 5 drBC 5 loC 4 drCD 4
dr dr u
AC BC B ACC C BCT lC DT
D D D
AC BC CC
Real problem:
State s: DT ; goal G: AD.
Searchprob/actions A:
pre, add, del.
Successors: DD, CT .
4 ulA 5
dr
AT ABAA
5 D
A
dr B
We are here B BB BT
5 ul
4 drBC D
D B
d rC DCdrC BT CT
5 drAB 5 drBC 5 loC 4 drCD 4 ulD 3
dr dr u dr
AC BC B ACC C BCT lC DT DCDD
D D D D
AC BC CC CT
Real problem:
State s: DD; goal G: AD.
Searchprob/actions A:
pre, add, del.
Successors: CD, DT .
432 CHAPTER 18. PLANNING II: ALGORITHMS
4 ulA 5
dr
AT ABAA
5 D
A
drB
We are here B BB BT
5 ul
4 drBC D
D B
rC DCdrC BT CT
5 drAB 5 drBC 5 dloC 4 drCD 4 ulD 3 drDC 2
dr dr u dr l
AC BC B ACC C BCT lC DT DCDD oD CD
D D D D D
AC BC CC CT DT
Real problem:
4 ulA 5
dr
AT ABAA
5 D
A
drB
We are here B BB BT
5 ul
4 drBC D
D B
drC DCdrC BT CT
5 drAB 5 drBC 5 loC 4 drCD 4 ulD 3 drDC 2 drCB 1
dr dr u dr l dr
AC BC B ACC C BCT lC DT DCDD oD CD C DBD
D D D D D D
AC BC CC CT DT DD
Real problem:
State s: BD; goal G: AD.
Searchprob/actions A:
pre, add, del.
4 ulA 5
dr
AT ABAA
5 D
A
drB
We are here B BB BT
5 ul
4 drBC D
D B
drC DCdrC BT CT
5 drAB 5 drBC 5 loC 4 drCD 4 ulD 3 drDC 2 drCB 1 drBA 0
dr dr u dr l dr dr
AC BC B ACC C BCT lC DT DCDD oD CD C DBD B CAD
D D D D D D D
AC BC CC CT DT DD CD
Real problem:
State s: AD; goal G: AD.
Searchprob/actions A:
pre, add, del.
Goal state!
4 ulA 5
dr
AT ABAA
5 D
A
drB
We are here B BB BT
5 ul
4 drBC D
D B
r C DC rC BT CT
d
5 drAB 5 drBC 5 dloC 4 drCD 4 ulD 3 drDC 2 drCB 1 drBA 0
dr dr u dr l dr dr
AC BC B ACC C BCT lC DT DCDD oD CD C DBD B CAD
D D D D D D D
AC BC CC CT DT DD CD
: 639 2025-05-14
h+ in the Blocksworld
A
A
B B
D C C
Optimal plan: [putdown(A), unstack(B, D), stack(B, C), pickup(A), stack(A, B)].
Optimal relaxed plan: [stack(A, B), unstack(B, D), stack(B, C)].
Observation: What can we say about the “search space surface” at the initial state here?
434 CHAPTER 18. PLANNING II: ALGORITHMS
The searchprob/initial state lies on a local minimum under h+ , together with the search-
prob/successor state s where we stacked A onto B. All direct other neighbors of these two
searchprob/states have a strictly higher h+ value.
: 640 2025-05-14
18.5 Conclusion
Summary
Heuristic search on classical search problems relies on a function h mapping searchprob/states
s to an estimate h(s) of their searchprob/goal state distance. Such functions h are derived
by solving relaxed problems.
In planning, the relaxed problems are generated and solved automatically. There are four
known families of suitable relaxation methods: abstractions, landmarks, critical paths, and
ignoring deletes (aka delete relaxation).
The delete relaxation consists in dropping the deletes from STRIPS tasks. A relaxed plan is a
plan for such a relaxed task. h+ (s) is the length of an optimal relaxed plan for searchprob/state
s. h+ is NP-hard to compute.
hFF approximates h+ by computing some, not necessarily optimal, relaxed plan. That is done
by a forward pass (building a relaxed planning graph), followed by a backward pass (extracting
a relaxed plan).
: 641 2025-05-14
Planning as SAT: Compile length-k bounded plan existence into satisfiability of a CNF
formula φ. Extensive literature on how to obtain small φ, how to schedule different values of
k, how to modify the underlying SAT solver.
Compilations: Formal framework for determining whether planning formalism X is (or is
not) at least as expressive as planning formalism Y .
: 642 2025-05-14
– Although the book is named “A Modern Approach”, the planning section was written long
before the IPC was even dreamt of, before PDDL was conceived, and several years before
heuristic search hit the scene. As such, what we have right now is the attempt of two outsiders
trying in vain to catch up with the dramatic changes in planning since 1995.
– Chapter 10 is Ok as a background read. Some issues are, imho, misrepresented, and it’s far
from being an up-to-date account. But it’s Ok to get some additional intuitions in words
different from my own.
– Chapter 11 is useful in our context here because we don’t cover any of it. If you’re interested
in extended/alternative planning paradigms, do read it.
• A good source for modern information (some of which we covered in the course) is Jörg Hoff-
mann’s Everything You Always Wanted to Know About Planning (But Were Afraid to Ask)
[hoffmann:ki-11] which is available online at [Link]
papers/[Link]
436 CHAPTER 18. PLANNING II: ALGORITHMS
Chapter 19
Outline
So Far: we made idealizing/simplifying assumptions:
The environment is fully observable and deterministic.
: 643 2025-05-14
19.1 Introduction
The real world
Example 19.1.1. We have a flat tire – what to do?
437
438 CHAPTER 19. SEARCHING, PLANNING, AND ACTING IN THE REAL WORLD
: 644 2025-05-14
Definition 19.1.4. The qualification problem in planning is that we can never finish listing
all the required preconditions and possible conditional effects of actions.
Root Cause: The environment is partially observable and/or non-deterministic.
Technical Problem: We cannot know the “current state of the world”, but search/planning
algorithms are based on this assumption.
Idea: Adapt search/planning algorithms to work with “sets of possible states”.
: 645 2025-05-14
Problem: Such plans may not exist! (but they often do in practice)
Another Solution: Conditional plans:
Plan to obtain information, (observation actions)
Subplan for each contingency.
19.2. THE FURNITURE COLORING EXAMPLE 439
: 646 2025-05-14
: 647 2025-05-14
We formalize the example in PDDL for simplicity. Note that the :percept scheme is not part of
the official PDDL, but fits in well with the design.
The PDDL problem file has a “free” variable ?c for the (undetermined) joint color.
440 CHAPTER 19. SEARCHING, PLANNING, AND ACTING IN THE REAL WORLD
Two action schemata: “remove can lid to open” and “paint with open can”
(:action remove−lid
:parameters (?x)
:precondition (can ?x)
:effect (open can))
(:action paint
:parameters (?x ?y)
:precondition (and (object ?x) (can ?y) (color ?y ?c) (open ?y))
:effect (color ?x ?c))
has a universal variable ?c for the paint action ⇝ we cannot just give paint a color
argument in a partially observable environment.
Sensorless Plan: Open one can, paint chair and table in its color.
Note: Contingent planning can create better plans, but needs perception
Two percept schemata: “color of an object” and “color in a can”
(:percept color
:parameters (?x ?c)
:precondition (and (object ?x) (inview ?x)))
(:percept can−color
:parameters (?x ?c)
:precondition (and (can ?x) (inview ?x) (open ?x)))
To perceive the color of an object, it must be in view, a can must also be open.
Note: In a fully observable world, the percepts would not have preconditions.
An action schema: “look at an object” that causes it to come into view.
(:action lookat
:parameters (?x)
:precond: (and (inview ?y) and (notequal ?x ?y))
:effect (and (inview ?x) (not (inview ?y))))
Contingent Plan:
1. look at furniture to determine color, if same ; done.
2. else, look at open and look at paint in cans
3. if paint in one can is the same as an object, paint the other with this color
4. else paint both in any color
: 648 2025-05-14
Conditional Plans
Definition 19.3.1. Conditional plans extend the possible actions in plans by conditional
steps that execute sub plans conditionally whether K + P ⊨ C, where K + P is the current
19.3. SEARCHING/PLANNING WITH NON-DETERMINISTIC ACTIONS 441
: 649 2025-05-14
Suck Right
8 5
GOAL LOOP
: 650 2025-05-14
: 651 2025-05-14
: 652 2025-05-14
pi := OR−SEARCH(si ,prob,path)
if pi = fail then return fail
return [if s1 then p1 else if s2 then p2 else . . . if sn−1 then pn−1 else pn ]
: 653 2025-05-14
Suck Right
[L1 : lef t, if AtR then L1 else [if CleanL then ∅ else suck fi] fi] or
[while AtR do [lef t] done, if CleanL then ∅ else suck fi]
We have an infinite loop but plan eventually works unless action always fails.
: 654 2025-05-14
: 655 2025-05-14
That is exactly what we have been doing until now: we have been studying methods that
build on descriptions of the “actual” world, and have been concentrating on the progression from
atomic to factored and ultimately structured representations. Tellingly, we spoke of “world states”
instead of “belief states”; we have now justified this practice in the brave new belief-based world
models by the (re-) definition of “world states” above. To fortify our intuitions, let us recap from
a belief-state-model perspective.
: 656 2025-05-14
Let us now see what happens when we lift the restrictions of total observability and determin-
ism.
: 657 2025-05-14
: 658 2025-05-14
Conformant/Sensorless Planning
Definition 19.5.1. Conformant or sensorless planning tries to find plans that work without
any sensing. (not even the initial state)
Observation 19.5.3. In a sensorless world we do not know the initial state. (or any state
after)
446 CHAPTER 19. SEARCHING, PLANNING, AND ACTING IN THE REAL WORLD
Observation 19.5.4. Sensorless planning must search in the space of belief states (sets of
possible actual states).
Example 19.5.5 (Searching the Belief State Space).
Start in {1, 2, 3, 4, 5, 6, 7, 8}
Solution: [right, suck, lef t, suck] right → {2, 4, 6, 8}
suck → {4, 8}
lef t → {3, 7}
suck → {7}
: 659 2025-05-14
: 660 2025-05-14
Let us see if we can understand the options for T b (a, S) a bit better. The first question is when we
want an action a to be applicable to a belief state S ⊆ S, i.e. when should T b (a, S) be non-empty.
In the first case, ab would be applicable iff a is applicable to some s ∈ S, in the second case if a
is applicable to all s ∈ S. So we only want to choose the first case if actions are harmless.
The second question we ask ourselves is what should be the results of applying a to S ⊆ S?,
again, if actions are harmless, we can just collect the results, otherwise, we need to make sure that
all members of the result ab are reached for all possible states in S.
R
L R
L
S S
R R
L R L R
L L
S S
S S
R
L R
S S
Figure 3.3 The state space for the vacuum world. Links denote actions: L = Left, R =
Right, S = Suck.
: 661 2025-05-14
belief states; e.g. “all” for initial state or “not leftmost column” after lef t.
actions as belief state to belief state operations.
This actually works: Therefore we talk about conformant planning!
: 662 2025-05-14
448 CHAPTER 19. SEARCHING, PLANNING, AND ACTING IN THE REAL WORLD
Idea: This can systematically be used in search/planning via belief-state search, but we
need to rethink/specialize the Transition model.
: 663 2025-05-14
The prediction stage: given a belief state b and an action a we define bb := PRED(b, a)
for some function PRED : P(S)×A → P(S).
The observation prediction stage determines the set of possible percepts that could be
observed in the predicted belief state: PossPERC(bb) = {PERC(s) | s ∈ bb}.
The update stage determines, for each possible percept, the resulting belief state: UPDATE(bb, o) :=
{s | o = PERC(s) and s ∈ bb}
The functions PRED and PERC are the main parameters of this model. We define RESULT(b, a):={UPDATE(PRED(b
Observation 19.6.3. If sensing is deterministic, belief states for different possible percepts
are disjoint, forming a partition of the original predicted belief state.
: 664 2025-05-14
19.6. SEARCHING/PLANNING WITH OBSERVATION 449
[B,Dirty] 2
Right
1 2
(a)
[B,Dirty] 2
3 Right 4
1 2
(a) [B,Clean] 4
3 4
[B,Clean] 4
2
[B,Dirty]
2
[B,Dirty]
Right 2
Right 2
1 1 11 [A,Dirty]
[A,Dirty] 1 1
(b) (b)
3 3 3
3 3 3
4
4
[B,Clean]
4
[B,Clean]
4
Figure 4.14 Two examples of transitions in local-sensing vacuum worlds. (a) In the deter-
The action Right is non-deterministic, sensing disambiguates somewhat
ministic world, Right is applied in the initial belief state, resulting in a new predicted belief
Figure 4.14stateTwo
with two possible of
examples physical states; for
transitions inthose states, the possible
local-sensing vacuum percepts
worlds. are [R,(a) In the deter-
Dirty]
: 665 2025-05-14
and [R, Clean], leading to two belief states, each of which is a singleton. (b) In the slippery
ministic world, Right is applied in the initial belief state, resulting in a new predicted belief
world, Right is applied in the initial belief state, giving a new belief state with four physi-
state with cal
two possible
Belief-State
states; physical
for those Search
states, states;
thewith forpercepts
thoseare
Percepts
possible states, the possible
[L, Dirty], [R, Dirty],percepts are [R, Dirty]
and [R, Clean],
and [R, Clean], leading
leading to to two
three belief statesbelief states, each of which is a singleton. (b) In the slippery
as shown.
Observation: The belief-state transition model induces an AND-OR graph.
world, Right is applied in the initial belief state, giving a new belief state with four physi-
Idea: Use AND-OR search in non deterministic environments.
cal states; for those states, the possible percepts are [L, Dirty], [R, Dirty], and [R, Clean],
leading to three belief states
Example asAND-OR
19.6.5. [Link] for initial percept [A, Dirty].
1
3
Suck Right
Figure 4.14 Two examples of transitions in local-sensing vacuum worlds. (a) In the deter-
ministic world, Right is applied in the initial belief state, resulting in a new predicted belief
state with two possible physical states; for those states, the possible percepts are [R, Dirty]
and [R, Clean], leading to two belief states, each of which is a singleton. (b) In the slippery
world, Right is applied in the initial belief state, giving a new belief state with four physi-
cal states; for those states, the possible percepts are [L, Dirty], [R, Dirty], and [R, Clean],
leading to three belief states as shown.
450 CHAPTER 19. SEARCHING, PLANNING, AND ACTING IN THE REAL WORLD
3
Suck Right
5
2 4
7
36 Chapter 4 Search in Complex Environments
Figure 4.15 The first level of the AND – OR search tree for a problem in the local-sensing
36 Chapter 4 Search in Complex Environments
Solution:
vacuum world;
[Suck, SuckifisBstate
Right, the first action
= {6}inthen
the solution.
Suck else [] fi]
1 5 5 6 2
:
Suck [A,Clean]666 Right 2 [B,Dirty]
2025-05-14
3 7 7 4 6
1 5 5 6 2
8
Figure 4.16 Two prediction–update cycles of belief-state maintenance in the kindergarten
Example 19.6.6. An agent inhabits a maze of which it has an accurate map. It
vacuum world with local sensing.
has four
sensors that can (reliably) detect walls. The M ove action is non-deterministic, moving the
Figure 4.16 Two prediction–update cycles of belief-state maintenance in the kindergarten
agent randomly into one of the adjacent squares.
vacuum world with local sensing.
1. Initial belief state ; bb1 all possible locations.
2. Initial percept: N W S (walls north, west, and south) ; bb2 = UPDATE(bb1 , N W S)
Figure 4.17 Possible positions of the robot, !, (a) after one observation, E1 = 1011, and
(b) Possible locations of robot after E1 = 1011, E2 = 1010
All in all, bb4 (b)
= UPDATE(PRED(UPDATE( bb1 , Nobservation,
after moving one square and making a second W S), M ove), N S)When
E2 = 1010. sensorsthe
localizes are agent.
noiseless and the transition model is accurate, there is only one possible location for the robot
Figure 4.17 Possible positions of the robot, !, (a) after one observation, E1 = 1011, and
consistent
Observation: withenlarges
this sequence of two observations.
PRED
(b) after moving one squaretheandbelief
makingstate,
a secondwhile UPDATE
observation, shrinks
E2 = 1010. Whenit again.
sensors are
noiseless and the transition model is accurate, there is only one possible location for the robot
consistent with this sequence of two observations.
: 667 2025-05-14
19.6. SEARCHING/PLANNING WITH OBSERVATION 451
Contingent Planning
Definition 19.6.7. The generation of plan with conditional branching based on percepts is
called contingent planning, solutions are called contingent plans.
Appropriate for partially observable or non-deterministic environments.
Example 19.6.8. Continuing Example 19.2.1.
One of the possible contingent plan is
((lookat table) (lookat chair)
(if (and (color table c) (color chair c)) (noop)
((removelid c1) (lookat c1) (removelid c2) (lookat c2)
(if (and (color table c) (color can c)) ((paint chair can))
(if (and (color chair c) (color can c)) ((paint table can))
((paint chair c1) (paint table c1)))))))
Note: Variables in this plan are existential; e.g. in
line 2: If there is come joint color c of the table and chair ; done.
line 4/5: Condition can be satisfied by [c1 /can] or [c2 /can] ; instantiate accordingly.
Definition 19.6.9. During plan execution the agent maintains the belief state b, chooses
the branch depending on whether b ⊨ c for the condition c.
Note: The planner must make sure b ⊨ c can always be decided.
: 668 2025-05-14
: 669 2025-05-14
452 CHAPTER 19. SEARCHING, PLANNING, AND ACTING IN THE REAL WORLD
: 670 2025-05-14
[Link]
This URL will also be posted on the forum tonight.
: 671 2025-05-14
Note: So far we have concentrated on offline problem solving, where the agent only acts
(plan execution) after search/planning terminates.
Recall: In online problem solving an agent interleaves computation and action: it computes
one action at a time based on incoming perceptions.
: 672 2025-05-14
: 673 2025-05-14
Figure 4.18 A simple maze problem. The agent starts at S and must reach G but knows
nothing of the environment.
: 674 2025-05-14
S A
S G
1 2 3
FigureG
3
4.18 A simple maze problem. The agent starts at S and must reac
nothing of the environment.
2
454 S
CHAPTER 19. SEARCHING, PLANNING,
1
AND ACTING IN THE REAL WORLD
1 2 3 37
Example 19.7.6. Two state spaces that1 leadS an online agent into dead ends:
S
1 2 3
Figure 4.18 A simple mazeGproblem. The agent starts at S and must reach G but knows
nothing of the environment.
S A S A
G
S (a)
G (b)
Any agent will fail in at least one of the spaces.
Figure 4.19 (a) Two state spaces that might lead an online search agent i
Definition 19.7.7. We call Example 19.7.6 Any givenargument.
G an adversary agent will fail in at least one of these spaces. (b) A two-dimensio
that can cause an online search agent to follow an arbitrarily inefficient ro
S 19.7.8.
Example A
S Forcing
A an online agent into anWhichever
arbitrarilychoice
inefficient route:
the agent makes, the adversary blocks that route with an
wall, so that the path followed is much longer than the best possible path.
G
S G
(a) (b)
Whichever choice the agent makes
the (a)
Figure 4.19 adversary
Two state can block
spaces thatwith
mighta lead an online search agent into a dead end.
Any givenlong, thin
agent willwall
fail in at least one of these spaces. (b) A two-dimensional environment
S an online
that can cause A search agent to follow an arbitrarily inefficient route to the goal.
Whichever choice the agent makes, the adversary blocks that route with another long, thin
wall, so that the path followed is muchGlonger than the best possible path.
(a) (b)
Observation: Figure
Dead 4.19
ends(a)are
Twoa state
real spaces that might
problem lead an online
for robots: ramps,search agent cliffs,
stairs, into a dead
. . . end.
Any given agent will fail in at least one of these spaces. (b) A two-dimensional environment
that can
Definition 19.7.9. A cause
stateanspace
onlineissearch agent
called to follow
safely an arbitrarily
explorable, iff ainefficient
goal staterouteisto reachable
the goal. from
Whichever choice the agent makes, the adversary blocks that route with another long, thin
every reachable state.
wall, so that the path followed is much longer than the best possible path.
: 675 2025-05-14
Intuition: It seems best to expand nodes in “local order” to avoid spurious travel.
Idea: Depth first search seems a good fit. (must only travel for backtracking)
: 676 2025-05-14
: 677 2025-05-14
Replanning (Ideas)
Idea: We can turn a planner P into an online problem solver by adding an action RePlan(g)
without preconditions that re-starts P in the current state with goal g.
Example 19.8.3. But when a tire blows while driving into the desert, we want to have water
pre-planned. (due diligence against catastrophies)
Observation: In stochastic or partially observable environments we also need some form of
execution monitoring to determine the need for replanning (plan repair).
function D ECOMPOSE(hierarchy , s0 , plan, sf ) returns a solution
solution ← an empty plan
while plan is not empty do
action ← R EMOVE -L AST(plan)
si ← a state in R EACH − (s0 , plan) such that sf ∈R EACH − (si , action )
456 problem ←
CHAPTER 19.a problem with I NITIAL
SEARCHING, = si and GAND
PLANNING, OAL =ACTING
sf IN THE REAL WORLD
solution ← A PPEND(A NGELIC -S EARCH (problem, hierarchy , action ), solution)
sf ← si
return: solution 678 2025-05-14
Figure 11.11 A hierarchical planning algorithm that uses angelic semantics to identify and
Replanning
commit tofor Planplans
high-level Repair
that work while avoiding high-level plans that don’t. The predi-
cate M AKING -P ROGRESS checks to make sure that we aren’t stuck in an infinite regression
Generally: Replanning
of refinements. whencall
At top level, theAagent’s
NGELICmodel of the
-S EARCH withworld
[Act]isasincorrect.
the initialPlan .
Figure 11.12executes
The agent At first,wholeplan
the sequence “whole
step plan”monitoring
by step, is expectedthe
to get
restthe agent from S to G.
(plan).
The agent executes steps of the plan until it expects to be in state E, but observes that it is
After a few steps the agent expects to be in E, but observes state O.
actually in O. The agent then replans for the minimal repair plus continuation to reach G.
Replanning: by calling the planner recursively
: 679 2025-05-14
: 680 2025-05-14
19.8. REPLANNING AND EXECUTION MONITORING 457
: 681 2025-05-14
: 682 2025-05-14
460 CHAPTER 19. SEARCHING, PLANNING, AND ACTING IN THE REAL WORLD
Chapter 20
Semester Change-Over
Planning Frameworks
Planning Algorithms
Planning and Acting in the real world
: 683 2025-05-14
461
462 CHAPTER 20. SEMESTER CHANGE-OVER
Agent Sensors
Percepts
Environment
?
Actions
Actuators
there is to say about the agent. Mathematically speaking, we say that an agent’s behavior is
Agent Sensors
AGENT FUNCTION described by the agent function that maps any given percept sequence to an action.
We can imagine tabulating the agent function that describes any given agent; for most
What the world
agents, this would be a very large table—infinite,is like in now
fact, unless we place a bound on the
length of percept sequences we want to consider. Given an agent to experiment with, we can,
Environment
in principle, construct this table by trying out all possible percept sequences and recording
which actions the agent does in response.1 The table is, of course, an external characterization
of the agent. Internally, the agent function for an artificial agent will be implemented by an
AGENT PROGRAM agent program. It is important to keep these two ideas distinct. The agent function is an
What action I
abstract mathematical Condition-action
description; rules
the agent program isnow
should do a concrete implementation, running
within some physical system.
To illustrate these ideas, we use a very simple example—the vacuum-cleaner world
Actuators
shown in Figure 2.2. This world is so simple that we can describe everything that happens;
it’s also a made-up world, so we can invent many variations. This particular world has just two
Figure 2.9 Schematic diagram of a simple reflex agent.
locations:
Reflex Agentssquares A and B. The vacuum agent perceives which square it is in and whether
with State
there is dirt in the square. It can choose to move left, move right, suck up the dirt, or do
nothing. One very simple agent function is the following: if the current square is dirty, then
function
suck; S IMPLE
otherwise, -R EFLEX
move to the-Aother
GENTsquare. ) returns
( perceptA an action of this agent function is shown
partial tabulation
persistent: rules, a set of condition–action rules
in Figure 2.3 and an agent program that implements it appears in Figure 2.8 on page 48.
Looking
state at Figure-I2.3,
← I NTERPRET NPUT we see that
( percept ) various vacuum-world agents can be defined simply
rule ← R ULE -M ATCH (state,
by filling in the right-hand column in various ways. The obvious question, then, is this: What
rules)
right ←
is theaction rule.A
way CTION
to fill out the table? In other words, what makes an agent good or bad,
return action
intelligent or stupid? We answer these questions in the next section.
Section20.1.
2.4. WHAT
The Structure of Agents
DID WE LEARN IN AI 1?
51 463
Sensors
State
How the world evolves What the world
is like now
Environment
What my actions do
Agent Actuators
Environment
What it will be like
What my actions do
state ← U PDATE -S TATE(state, action , percept ,ifmodel ) A
I do action
rule ← RULE -M ATCH(state, rules)
action ← [Link]
return action
What action I
Goals should do now
Figure 2.12 A model-based reflex agent. It keeps track of the current state of the world,
using an internal model. It then chooses an actionActuators
Agent in the same way as the reflex agent.
54 is responsible
Figure 2.13 for creating the newgoal-based
A model-based, internal state description.
agent. It keepsChapter The
track details
of [Link]
howasmodels
state as and
wellAgents
Utility-Based
statesa are
set of Agent
goals it is trying
represented to achieve,
vary widely and chooses
depending on thean action
type ofthat will (eventually)
environment and lead to the
the particular
achievement
technology used ofin its
thegoals.
agent design. Detailed examples of models and updating algorithms
appear in Chapters 4, 12, 11, 15, 17, and 25. Sensors
Regardless
example, the taxi of maythebekind of representation
driving
State back home, and used,it may it ishaveseldom
a rule possible fortothe
telling it fill agent
up with to
determine the current
gas on the way homeHow state
unless of a partially observable
it has at least half What a istank. environment exactly. Instead,
Although “driving back home” may
the world the box
the world evolves like now
labeled
seem to “what
an aspectthe of
world is likestate,
the world now”the(Figure
fact of2.11)
the taxi’srepresents the agent’s
destination “bestanguess”
is actually aspect (orof
Environment
sometimes
the agent’s best guesses).
internal state. Foryou
If example,
find thisanpuzzling,
automated willtaxi
What itconsider may
be like thatnot
the betaxi
able to see
could be around
in the
exactly
What my actions do
large truckplace
the same that at
hasthestopped
same time,in front
but of it and can
intending
if Ionly
do action
to reach guess
A about what may be causing the
a different destination.
hold-up. Thus, uncertainty about the current state may be unavoidable, but the agent still has
Utility How happy I will be
to make Goal-based
2.4.4 a decision. agents in such a state
A perhaps less obvious point about the internal “state” maintained by a model-based
What action I
Knowing
agent something
is that it does not about thetocurrent
have describe state of thethe
“what environment
should world
do nowis like is not
now” always
in a enough to decide
literal sense. For
what to do. For example, at a road junction, the taxi can turn left, turn right, or go straight
on. The correct decisionAgent depends on where the taxiActuators is trying to get to. In other words, as well
GOAL as a current state description, the agent needs some sort of goal information that describes
situations
Figurethat2.14are desirable—for
A model-based, example,utility-basedbeing
agent. at Ittheusespassenger’s
a model of destination.
the world, along Thewith
agent
Learning
program Agents
canfunction
a utility combine thatthis with the
measures model (theamong
its preferences same information
states of the [Link] wasThenused in the model-
it chooses the
basedaction
reflex agent)
that leads to
to choose
the best actions
expectedthat achieve
utility, wherethe goal. Figure
expected 2.13
utility is shows by
computed theaveraging
goal-based
overstructure.
agent’s all possible outcome states, weighted by the probability of the outcome.
Sometimes goal-based action selection is straightforward—for example, when goal sat-
isfaction results immediately from a single action. Sometimes it will be more tricky—for
outcome. (Appendix A defines expectation more precisely.) In Chapter 16, we show that any
example, when the agent has to consider long sequences of twists and turns in order to find a
rational
way to achievemust
agent behave
the goal. it possesses
as if (Chapters
Search 3 toa 5)
utility
and function
planningwhose (Chaptersexpected
10 andvalue it tries
11) are the
to maximize. An agent that possesses an explicit utility
subfields of AI devoted to finding action sequences that achieve the agent’s goals. function can make rational decisions
with aNotice
general-purpose
that decision algorithm
making that does
of this notisdepend
kind fundamentally on the specific
differentutility
from thefunction being
condition–
Section 2.4. The Structure of Agents 55
464 CHAPTER 20. SEMESTER CHANGE-OVER
Performance standard
Critic Sensors
feedback
Environment
changes
Learning Performance
element element
knowledge
learning
goals
Problem
generator
Actuators
Agent
He estimates how much work this might take and concludes “Some more expeditious method
Rational Agent
seems desirable.” The method he proposes is to build learning machines and then to teach
them. In many areas of AI, this is now the preferred method for creating state-of-the-art
systems.
Idea: TryLearning
to designhas another
agents thatadvantage, as we noted earlier: it allows the
are successful (doagent to operate
the right thing)
in initially unknown environments and to become more competent than its initial knowledge
Definition
alone might 20.1.1.
allow. An In agent is called
this section, werational, if it chooses
briefly introduce the whichever
main ideasaction maximizes
of learning agents. the
expected valuethe
Throughout of book,
the performance
we comment measure given the percept
on opportunities sequence
and methods to date. inThis
for learning is called
particular
thekinds
MEU of principle.
agents. Part V goes into much more depth on the learning algorithms themselves.
A learning agent can be divided into four conceptual components, as shown in Fig-
Note: A rational agent need not be perfect
LEARNING ELEMENT ure 2.15. The most important distinction is between the learning element, which is re-
PERFORMANCE
ELEMENT sponsible
for making
only needs improvements,
to maximize expected andvaluethe performance element, which is responsible
(rational ̸= omniscient)for
selecting external actions. The performance element is what we
need not predict e.g. very unlikely but catastrophic events in the future
have previously considered
to be the entire agent: it takes in percepts and decides on actions. The learning element uses
percepts may not supply all relevant information
CRITIC feedback from the critic on how the agent is doing and determines(Rational how the ̸= clairvoyant)
performance
if we
element cannot
should perceive to
be modified things we do
do better in not need to react to them.
the future.
The we
but design
mayofneed
the learning
to try toelement depends
find out about very
hiddenmuch on the design of the performance
dangers (exploration)
element. When trying to design
action outcomes may not be as expected
an agent that learns a certain capability,
(rational ̸=question
the first is
successful)
not “How am I going to get it to learn this?” but “What kind of performance element will my
but we may need to take action to ensure that they do (more often) (learning)
agent need to do this once it has learned how?” Given an agent design, learning mechanisms
can be constructed
Rational ; exploration,to improve every
learning, part of the agent.
autonomy
The critic tells the learning element how well the agent is doing with respect to a fixed
performance standard. The critic is necessary because the percepts themselves provide no
indication: of the agent’s success. For example, 685
a chess program could receive2025-05-14
a percept
indicating that it has checkmated its opponent, but it needs a performance standard to know
Symbolic
that this AI: Adding
is a good Knowledge
thing; the to Algorithms
percept itself does not say so. It is important that the performance
: 686 2025-05-14
Uncertainty
Probabilistic reasoning
Making Decisions in Episodic Environments
Problem Solving in Sequential Environments
Foundations of machine learning
: 687 2025-05-14
466 CHAPTER 20. SEMESTER CHANGE-OVER
Prerequisites
Remember: AI-1 dealt with situations with “complete information” and strictly computable,
“perfect” solutions to problems. (i.e. tree search, logical inference, planning, etc.)
AI-2 will focus on probabilistic scenarios by introducing uncertain situations, and approximate
solutions to problems. (Bayesian networks, Markov models, machine learning, etc.)
Weak Prerequisites for AI-2: (if you do not have them, study up as needed)
AI-1 (in particular: PEAS, propositional logic/first-order logic (mostly the syntax), some
logic programming)
(very) elementary complexity theory. (big Oh and friends)
rudimentary probability theory (e.g. from stochastics)
basic linear algebra (vectors, matrices,...)
basic real analysis (aka. calculus) (primarily: (partial) derivatives)
Meaning: I will assume you know these things, but some of them we will recap, and what
you don’t know will make things slightly harder for you, but by no means prohibitively difficult.
: 688 2025-05-14
“Strict” Prerequisites
Most crucially – Mathematical Literacy: Mathematics is the language that computer
scientists express their ideas in! (“A search problem is a tuple (N, S, G, ...) such that...”)
Note: This is a skill that can be learned, and more importantly, practiced! Not having/hon-
ing this skill will make things more difficult for you. Be aware of this and, if necessary, work
on it – it will pay off, not only in this course.
But also: Motivation, interest, curiosity, hard work. (AI-2 is non-trivial)
Note: Grades correlate significantly with invested effort; including, but not limited to:
time spent on exercises, (learning is 80% perspiration, only 20% inspiration)
being here in presence, (humans are social animals ⇝ mirror neurons)
asking questions, (Q/A dialogues activate brains)
talking to your peers, (pool your insights, share your triumphs/frustrations). . .
All of these we try to support with the ALeA system.(which also gives us the data to prove
this)
: 689 2025-05-14
Now we come to a topic that is always interesting to the students: the grading scheme.
468 CHAPTER 20. SEMESTER CHANGE-OVER
Assessment, Grades
Overall (Module) Grade:
Grade via the exam (Klausur) ; 100% of the grade.
Up to 10% bonus on-top for an exam with ≥ 50% points. (< 50% ; no bonus)
Bonus points =
b percentage sum of the best 10 prepquizzes divided by 100.
Exam: exam conducted in presence on paper! (∼ Oct. 10. 2025)
Retake Exam: 90 minutes exam six months later. (∼ April 10. 2026)
You have to register for exams in [Link] in the first month of classes.
Note: You can de-register from an exam on [Link] up to three working
days before exam. (do not miss that if you are not prepared)
: 690 2025-05-14
Preparedness Quizzes
PrepQuizzes: Before every lecture we offer a 10 min online quiz – the PrepQuiz – about
the material from the previous week. (16:15-16:25; starts in week 2)
Motivations: We do this to
keep you prepared and working continuously. (primary)
bonus points if the exam has ≥ 50% points (potential part of your grade)
update the ALeA learner model. (fringe benefit)
The prepquizes will be given in the ALeA system
[Link]
: 691 2025-05-14
Due to the current AI hype, the course Artificial Intelligence is very popular and thus many
degree programs at FAU have adopted it for their curricula. Sometimes the course setup that fits
for the CS program does not fit the other’s very well, therefore there are some special conditions.
I want to state here.
: 692 2025-05-14
I can only warn of what I am aware, so if your degree program lets you jump through extra hoops,
please tell me and then I can mention them here.
Maybe we can get around the problems of defining “what artificial intelligence is”, by just describ-
ing the necessary components of AI (and how they interact). Let’s have a try to see whether that
is more informative.
Inference
Perception
20.3. OVERVIEW OVER AI AND TOPICS OF AI-II 471
Language understanding
Emotion
: 694 2025-05-14
Note that list of components is controversial as well. Some say that it lumps together cognitive
capacities that should be distinguished or forgets others, . . . . We state it here much more to get
AI-2 students to think about the issues than to make it normative.
in outer space
in outer space systems
need autonomous con-
trol:
remote control impos-
sible due to time lag
in artificial limbs
the user controls the
prosthesis via existing
nerves, can e.g. grip
a sheet of paper.
in household appliances
The iRobot Roomba
vacuums, mops, and
sweeps in corners, . . . ,
parks, charges, and
discharges.
general robotic house-
hold help is on the
horizon.
in hospitals
in the USA 90% of the
prostate operations are
carried out by Ro-
boDoc
Paro is a cuddly robot
that eases solitude in
nursing homes.
474 CHAPTER 20. SEMESTER CHANGE-OVER
: 695 2025-05-14
The AI Conundrum
Observation: Reserving the term “artificial intelligence” has been quite a land grab!
But: researchers at the Dartmouth Conference (1956) really thought they would solve/reach
AI in two/three decades.
Consequence: AI still asks the big questions. (and still promises answers soon)
Another Consequence: AI as a field is an incubator for many innovative technologies.
AI Conundrum: Once AI solves a subfield it is called “CS”.(becomes a separate subfield of
CS)
: 696 2025-05-14
All of these phenomena can be seen in the growth of AI as an academic discipline over the course
of its now over 70 year long history.
Definition 20.3.5. An AI winter is a time period of low public perception and funding for
AI,
mostly because AI has failed to deliver on its – sometimes overblown – promises
An AI summer is a time period of high public perception and funding for AI
AI becomes
scarily effective,
ubiquitous
Excitement fades;
some applications
AI-conse- profit a lot
quences,
Biases, AI-bubble bursts,
Regulation the next AI winter
Lighthill report WWW ; comes
Dartmouth Conference Data/-
Turing Test Computing
AI Winter 2
AI Winter 1 Explosion
1987-1994
1974-1980
: 697 2025-05-14
Of course, the future of AI is still unclear, we are currently in a massive hype caused by the advent
of deep neural networks being trained on all the data of the Internet, using the computational
power of huge compute farms owned by an oligopoly of massive technology companies – we are
definitely in an AI summer.
But AI as a academic community and the tech industry also make outrageous promises, and
the media pick it up and distort it out of proportion, . . . So public opinion could flip again, sending
AI into the next winter.
: 698 2025-05-14
As a consequence, the field of artificial intelligence (AI) is an engineering field at the intersection of
CS (logic, programming, applied statistics), Cognitive Science (psychology, neuroscience), philos-
ophy (can machines think, what does that mean?), linguistics (natural language understanding),
and mechatronics (robot hardware, sensors).
Subsymbolic AI and in particular machine learning is currently hyped to such an extent, that
many people take it to be synonymous with “Artificial Intelligence”. It is one of the goals of this
course to show students that this is a very impoverished view.
We can classify the AI approaches by their coverage and the analysis depth (they are
complementary)
: 699 2025-05-14
We combine the topics in this way in this course, not only because this reproduces the histor-
ical development but also as the methods of statistical and subsymbolic AI share a common
basis.
It is important to notice that all approaches to AI have their application domains and strong points.
We will now see that exactly the two areas, where symbolic AI and statistical/subsymbolic AI
have their respective fortes correspond to natural application areas.
Consumer tasks: consumer grade applications have tasks that must be fully generic and
wide coverage. ( e.g. machine translation like Google Translate)
Producer tasks: producer grade applications must be high-precision, but can be domain-
specific (e.g. multilingual documentation, machinery-control, program verification,
medical technology)
Precision
100% Producer Tasks
General Rule: Subsymbolic AI is well suited for consumer tasks, while symbolic AI is better
suited for producer tasks.
A domain of producer tasks I am interested in: mathematical/technical documents.
20.3. OVERVIEW OVER AI AND TOPICS OF AI-II 477
: 700 2025-05-14
An example of a producer task – indeed this is where the name comes from – is the case of a
machine tool manufacturer T , which produces digitally programmed machine tools worth multiple
million Euro and sells them into dozens of countries. Thus T must also provide comprehensive
machine operation manuals, a non-trivial undertaking, since no two machines are identical and
they must be translated into many languages, leading to hundreds of documents. As those manual
share a lot of semantic content, their management should be supported by AI techniques. It is
critical that these methods maintain a high precision, operation errors can easily lead to very
costly machine damage and loss of production. On the other hand, the domain of these manuals is
quite restricted. A machine tool has a couple of hundred components only that can be described
by a couple of thousand attributes only.
Indeed companies like T employ high-precision AI techniques like the ones we will cover in this
course successfully; they are just not so much in the public eye as the consumer tasks.
: 701 2025-05-14
: 702 2025-05-14
: 703 2025-05-14
: 704 2025-05-14
One possible objection to this is that the agent and the environment are conceptualized as separate
entities; in particular, that the image suggests that the agent itself is not part of the environment.
Indeed that is intended, since it makes thinking about agents and environments easier and is of
little consequence in practice. In particular, the offending separation is relatively easily fixed if
needed.
Agent Sensors
Percepts
Environment
Actions
Actuators
Figure 2.1 Agents interact with environments through sensors and actuators.
Different agents differ on the contents of the white box in the center.
there is to say about the agent. Mathematically speaking, we say that an agent’s behavior is
AGENT FUNCTION described
:
by the agent function that maps 705
any given percept sequence to an action.
2025-05-14
We can imagine tabulating the agent function that describes any given agent; for most
agents, this would be a very large table—infinite, in fact, unless we place a bound on the
length of percept sequences we want to consider. Given an agent to experiment with, we can,
in principle, construct this table by trying out all possible percept sequences and recording
which actions the agent does in response.1 The table is, of course, an external characterization
of the agent. Internally, the agent function for an artificial agent will be implemented by an
480 CHAPTER 20. SEMESTER CHANGE-OVER
Rationality
Idea: Try to design agents that are successful! (aka. “do the right thing”)
Problem: What do we mean by “successful”, how do we measure “success”?
Definition 20.3.12. A performance measure is a function that evaluates a sequence of
environments.
Example 20.3.13. A performance measure for a vacuum cleaner could
award one point per “square” cleaned up in time T ?
award one point per clean “square” per time step, minus one per move?
penalize for > k dirty squares?
Definition 20.3.14. An agent is called rational, if it chooses whichever action maximizes
the expected value of the performance measure given the percept sequence to date.
Critical Observation: We only need to maximize the expected value, not the actual value
of the performance measure!
: 706 2025-05-14
Let us see how the observation that we only need to maximize the expected value, not the actual
value of the performance measure affects the consequences.
Definition 20.3.15. An agent is called autonomous, if it does not rely on the prior knowledge
about the environment of the designer.
Autonomy avoids fixed behaviors that can become unsuccessful in a changing environment.
(anything else would be irrational)
The agent may have to learn all relevant traits, invariants, properties of the environment and
actions.
: 707 2025-05-14
20.3. OVERVIEW OVER AI AND TOPICS OF AI-II 481
For the design of agent for a specific task – i.e. choose an agent architecture and design an
agent program, we have to take into account the performance measure, the environment, and the
characteristics of the agent itself; in particular its actions and sensors.
: 708 2025-05-14
The PEAS criteria are essentially a laundry list of what an agent design task description should
include.
Environment types
Observation 20.3.18. Agent design is largely determined by the type of environment it is
intended for.
Problem: There is a vast number of possible kinds of environments in AI.
Solution: Classify along a few “dimensions”. (independent characteristics)
Definition 20.3.19. For an agent a we classify the environment e of a by its type, which is
one of the following. We call e
1. fully observable, iff the a’s sensors give it access to the complete state of the environment
at any point in time, else partially observable.
2. deterministic, iff the next state of the environment is completely determined by the current
state and a’s action, else stochastic.
3. episodic, iff a’s experience is divided into atomic episodes, where it perceives and then
performs a single action. Crucially, the next episode does not depend on previous ones.
Non-episodic environments are called sequential.
4. dynamic, iff the environment can change without an action performed by a, else static. If
the environment does not change but a’s performance measure does, we call e semidynamic.
5. discrete, iff the sets of e’s state and a’s actions are countable, else continuous.
482 CHAPTER 20. SEMESTER CHANGE-OVER
6. single-agent, iff only a acts on e; else multi-agent (when must we count parts of e as
agents?)
: 709 2025-05-14
Reflex Agents
Definition 20.3.20. An agent ⟨P , A, f ⟩ is called a reflex agent, iff it only takes the last
percept into account when choosing an action, i .e. f (p1 , . . ., pk ) = f (pk ) for all p1 , . . ., pk ∈
P.
Section
Agent 2.4. The Structure of Agents
Schema: 49
Agent Sensors
Environment
Condition-action rules What action I
should do now
Actuators
Model-basedFigure
Reflex2.10 Agents:
A simple reflexIdea
agent. It acts according to a rule whose condition matches
the current state, as defined by the percept.
Idea: Keep track of the state of the world we cannot see in an internal model.
trivial; it gets more interesting shortly.) We use rectangles to denote the current internal state
of the agent’s decision process, and ovals to represent the background information used in
Agent Schema:
the process. The agent program, which is also very simple, is shown in Figure 2.10. The
I NTERPRET-I NPUT function generates an abstracted description of the current state from the
percept, and the RULE -M ATCH function returns the first rule in the set of rules that matches
the given state description. Note that the description in terms of “rules” and “matching” is
purely conceptual; actual implementations can be as simple as a collection of logic gates
implementing a Boolean circuit.
Simple reflex agents have the admirable property of being simple, but they turn out to be
of limited intelligence. The agent in Figure 2.10 will work only if the correct decision can be
made on the basis of only the current percept—that is, only if the environment is fully observ-
able. Even a little bit of unobservability can cause serious trouble. For example, the braking
rule given earlier assumes that the condition car-in-front-is-braking can be determined from
the current percept—a single frame of video. This works if the car in front has a centrally
mounted brake light. Unfortunately, older models have different configurations of taillights,
Section20.3.
2.4. OVERVIEW
The Structure of Agents
OVER AI AND TOPICS OF AI-II
51 483
Sensors
State
How the world evolves What the world
is like now
Environment
What my actions do
Agent Actuators
Non-deterministic actions:
“When I try to go forward in this dark cave, I might actually go forward-left or forward-
right.”
Partial observability with unreliable sensors:
“Did I feel a breeze right now?”;
“I think I might smell a Wumpus here, but I got a cold and my nose is blocked.”
“According to the heat scanner, the Wumpus is probably in cell [2,3].”
Uncertainty about the domain behavior:
“Are you sure the Wumpus never moves?”
: 713 2025-05-14
Unreliable Sensors
Robot Localization: Suppose we want to support localization using landmarks to narrow
down the area.
Example 20.3.24. “If you see the Eiffel tower, then you’re in Paris.”
Difficulty: Sensors can be imprecise.
Even if a landmark is perceived, we cannot conclude with certainty that the robot is at
that location.
“This is the half-scale Las Vegas copy, you dummy.”
Even if a landmark is not perceived, we cannot conclude with certainty that the robot is
not at that location.
“Top of Eiffel tower hidden in the clouds.”
: 714 2025-05-14
We are now ready to proceed to environments which can only partially observed and where
actions are non deterministic. Both sources of uncertainty conspire to allow us only partial knowl-
edge about the world, so that we can only optimize “expected utility” instead of “actual utility”
of our actions.
20.3. OVERVIEW OVER AI AND TOPICS OF AI-II 485
a belief state that has information about the possible states the world may be in,
a sensor model that updates the belief state based on sensor information, and
a transition model that updates the belief state based on actions.
Idea: The agent environment determines what the world model can be.
: 715 2025-05-14
That is exactly what we have been doing until now: we have been studying methods that
build on descriptions of the “actual” world, and have been concentrating on the progression from
atomic to factored and ultimately structured representations. Tellingly, we spoke of “world states”
instead of “belief states”; we have now justified this practice in the brave new belief-based world
models by the (re-) definition of “world states” above. To fortify our intuitions, let us recap from
a belief-state-model perspective.
: 716 2025-05-14
Let us now see what happens when we lift the restrictions of total observability and determin-
486 CHAPTER 20. SEMESTER CHANGE-OVER
ism.
Note: This even applies to online problem solving, where we can just perceive the state.
(e.g. when we want to optimize utility)
In a deterministic, but partially observable environment,
the belief state must deal with a set of possible states.
we can use transition functions.
We need a sensor model, which predicts the influence of percepts on the belief state –
during update.
In a stochastic, partially observable environment,
mix the ideas from the last two. (sensor model + transition relation)
: 717 2025-05-14
belief state =
b Bayesian networks,
inference =
b probabilistic inference.
Decision-Theoretic Agents: In a partially observable, stochastic environment
belief state + transition model =
b decision networks,
inference =
b maximizing expected utility.
We will study them in detail this semester.
: 718 2025-05-14
Overview: AI2
Basics of probability theory (probability spaces, random variables, conditional probabilities,
independence,...)
Probabilistic reasoning: Computing the a posteriori probabilities of events given evidence,
causal reasoning (Representing distributions efficiently, Bayesian networks,...)
Machine learning: Learning from data (Decision Trees, Classifiers, Neural Networks,...)
: 719 2025-05-14
488 CHAPTER 20. SEMESTER CHANGE-OVER
Part V
489
491
This part of the lecture notes addresses inference and agent decision making in partially
observable environments, i.e. where we only know probabilities instead of certainties whether
propositions are true/false. We cover basic probability theory and – based on that – Bayesian
Networks and simple decision making in such environments. Finally we extend this to probabilistic
temporal models and their decision theory.
492
Chapter 21
Quantifying Uncertainty
In this chapter we develop a machinery for dealing with uncertainty: Instead of thinking about
what we know to be true, we must think about what is likely to be true.
: 720 2025-05-14
The definition is simplified in two places: Firstly, we assume that P is defined on the full power
set. This is not always possible, especially if Ω is uncountable. In that case we need an additional
set of “events” instead, and lots of mathematical machinery to make sure that we can safely take
unions, intersections, complements etc. of these events.
493
494 CHAPTER 21. QUANTIFYING UNCERTAINTY
Secondly, we would technically only demand that P is additive on countably many disjoint
sets.
In this course we will assume that our sample space is at most countable anyway; usually even
finite.
Random Variables
In practice, we are rarely interested in the specific outcome of an experiment, but rather in
some property of the outcome. This is especially true in the very common situation where
we don’t even know the precise probabilities of the individual outcomes.
Example 21.1.3. The probability that the sum of our two dice throws is 7 is P ({(i, j) ∈
6
Ω | i + j = 7}) = P ({(6, 1), (1, 6), (5, 2), (2, 5), (4, 3), (3, 4)}) = 36 = 16 .
: 721 2025-05-14
Note that a random variable, according to the formal definition, is neither random nor a variable:
It is a function with clearly defined domain and codomain – and what we call the domain of the
“variable” is actually its codomain... are you confused yet? ,
This confusion is a side-effect of the mathematical formalism. In practice, a random variable is
some indeterminate value that results from some statistical experiment – i.e. it is random, because
the result is not predetermined, and it is a variable, because it can take on different values.
It just so happens that if we want to model this scenario mathematically, a function is the most
natural way to do so.
Some Examples
Example 21.1.6. Summing up our two dice throws is a random variable S : Ω → [2,12] with
S((i, j)) = i + j. The probability that they sum up to 7 is written as P (S = 7) = 16 .
Example 21.1.7. The first and second of our two dice throws are random variables First, Second : Ω→
[1,6] with First((i, j)) = i and Second((i, j)) = j.
Remark 21.1.8. Note, that the identity Ω → Ω is a random variable as well.
Example 21.1.9. We can model toothache, cavity and gingivitis as Boolean random
variables, with the underlying probability space being...??
Example 21.1.10. We can model tomorrow’s weather as a random variable with domain
{sunny, rainy, foggy, warm, cloudy, humid, ...}, with the underlying probability space be-
ing...??
⇒ This is why probabilistic reasoning is necessary: We can rarely reduce probabilistic scenarios
down to clearly defined, fully known probability spaces and derive all the interesting things
from there.
21.1. PROBABILITY THEORY 495
But: The definitions here allow us to reason about probabilities and random variables in a
mathematically rigorous way, e.g. to make our intuitions and assumptions precise, and prove
our methods to be sound.
: 722 2025-05-14
Propositions
This is nice and all, but in practice we are interested in “compound” probabilities like:
“What is the probability that the sum of our two dice throws is 7, but neither of the two dice
is a 3?”
Idea: Reuse the syntax of propositional logic and define the logical connectives for random
variables!
Example 21.1.11. We can express the above as: P (¬(First = 3)∧¬(Second = 3)∧(S = 7))
Example 21.1.13. P ((First ̸= 3)∧(Second ̸= 3)∧(S = 7)) = P ({(1, 6), (6, 1), (2, 5), (5, 2)}) =
1
9
: 723 2025-05-14
Events
Definition 21.1.14 (Again slightly simplified). Let ⟨Ω, P ⟩ be a probability space. An
event is a subset of Ω.
Definition 21.1.15 (Convention). We call an event (by extension) anything that represents
a subset of Ω: any statement formed from the logical connectives and values of random
variables, on which P (·) is defined.
Problem 1.1
Remember: We can define A ∨ B := ¬(¬A ∧ ¬B), T := A ∨ ¬A and F := ¬T – is
this compatible with the definition of probabilities on propositional formulae? And why is
P (X1 ̸= x1 ) = 1 − P (X1 = x1 )?
Problem 1.3
Show that P (A) = P (A ∧ B) + P (A ∧ ¬B)
: 724 2025-05-14
Conditional Probabilities
Observation: As we gather new information, our beliefs (should ) change, and thus our
probabilities!
Example 21.1.16. Your “probability of missing the connection train” increases when you are
informed that your current train has 30 minutes delay.
Example 21.1.17. The “probability of cavity” increases when the doctor is informed that
the patient has a toothache.
Example 21.1.18. The probability that S = 3 is clearly higher if I know that First = 1 than
otherwise – or if I know that First = 6!
Definition 21.1.19. Let A and B be events where P (B) ̸= 0. The conditional probability
of A given B is defined as:
P (A ∧ B)
P (A | B):=
P (B)
We also call P (A) the prior probability of A, and P (A | B) the posterior probability.
Intuition: If we assume B to hold, then we are only interested in the “part” of Ω where A
is true relative to B.
Alternatively: We restrict our sample space Ω to the subset of outcomes where B holds.
We then define a new probability space on this subset by scaling the probability measure so
that it sums to 1 – which we do by dividing by P (B). (We “update our beliefs based on
new evidence”)
: 725 2025-05-14
Examples
Example 21.1.20. If we assume First = 1, then P (S = 3 | (First = 1)) should be precisely
P (Second = 2) = 61 . We check:
Example 21.1.21. Assume the prior probability P (cavity) is 0.122. The probability that a
patient has both a cavity and a toothache is P (cavity ∧ toothache) = 0.067. The probability
that a patient has a toothache is P (toothache) = 0.15.
21.1. PROBABILITY THEORY 497
If the patient complains about a toothache, we can update our estimation by computing the
posterior probability:
Note: We just computed the probability of some underlying disease based on the presence
of a symptom!
More Generally: We computed the probability of a cause from observing its effect.
: 726 2025-05-14
Some Rules
Equations on unconditional probabilities have direct analogues for conditional probabilities.
Problem 1.4
Convince yourself of the following:
P (A | C) = 1 − P (¬A | C).
P (A | C) = P (A ∧ B | C) + P (A ∧ ¬B | C).
P (A ∨ B | C) = P (A | C) + P (B | C) − P (A ∧ B | C).
: 727 2025-05-14
Bayes’ Rule
Theorem 21.1.22 (Bayes’ Theorem). Given propositions A and B where P (A) ̸= 0 and
P (B) ̸= 0, we have:
P (B | A) · P (A)
P (A | B) =
P (B)
498 CHAPTER 21. QUANTIFYING UNCERTAINTY
Proof:
P (A∧B) P (B | A)·P (A)
1. P (A | B) = P (B) = P (B)
□
...okay, that was straightforward... what’s the big deal?
(Somewhat Dubious) Claim: Bayes’ Rule is the entire scientific method condensed into a
single equation!
: 728 2025-05-14
likelihood prior
z }| { z }| {
P (E | H) · P (H) P (E | H) · P (H)
P (H | E) = =
| {z } P (E) P (E | H) P (H) + P (E | ¬H)P (¬H)
posterior | {z } | {z } | {z }
likelihood prior competition
. . . if I keep gathering evidence and update, ultimately the impact of the prior belief will
diminish.
“You’re entitled to your own priors, but not your own likelihoods”
: 729 2025-05-14
21.1.2 Independence
Independence
Question: What is the probability that S = 7 and the patient has a toothache?
Or less contrived: What is the probability that the patient has a gingivitis and a cavity?
Definition 21.1.23. Two events A and B are called independent, iff P (A ∧ B) = P (A) ·
P (B).
Two random variables X1 , X2 are called independent, iff for all x1 ∈ dom(X1 ) and x2 ∈
dom(X2 ), the events X1 = x1 and X2 = x2 are independent. We write A ⊥ B or X1 ⊥ X2 ,
21.1. PROBABILITY THEORY 499
respectively.
Theorem 21.1.24. Equivalently: Given events A and B with P (B) ̸= 0, then A and B are
independent iff P (A | B) = P (A) (equivalently: P (B | A) = P (B)).
Proof:
1. ⇒
P (A∧B) P (A)·P (B)
By definition, P (A | B) = P (B) = P (B) = P (A),
3. ⇐
Assume P (A | B) = P (A).
Then P (A ∧ B) = P (A | B) · P (B) = P (A) · P (B).
□
Note: Independence asserts that two events are “not related” – the probability of one does
not depend on the other.
Mathematically, we can determine independence by checking whether P (A ∧ B) = P (A) ·
P (B).
In practice, this is impossible to check. Instead, we assume independence based on domain
knowledge, and then exploit this to compute P (A ∧ B).
: 730 2025-05-14
Independence (Examples)
Example 21.1.25.
First = 2 and Second = 3 are independent – more generally, First and Second are
independent (The outcome of the first die does not affect the outcome of the second die)
Quick check: P ((First = a) ∧ (Second = b)) = 1
36 = P (First = a) · P (Second = b) ✓
First and S are not independent. (The outcome of the first die affects the sum of
1
the two dice.) Counterexample: P ((First = 1) ∧ (S = 4)) = 36 ̸= P (First = 1) · P (S =
1 1 1
4) = 6 · 2 = 72
But: P ((First = a) ∧ (S = 7)) = 36
1
= 1
6 · 1
6 = P (First = a) · P (S = 7) – so the events
First = a and S = 7 are independent. (Why?)
Example 21.1.26.
: 731 2025-05-14
g
500 CHAPTER 21. QUANTIFYING UNCERTAINTY
Assume the patient complains about a toothache, and our probe indeed catches in the aching
tooth. What is the likelihood of having a cavity P (cavity | (toothache ∧ catch))?
: 732 2025-05-14
Definition 21.1.27. Given events A, B, C with P (C) ̸= 0, then A and B are called condi-
tionally independent given C, iff P (A ∧ B | C) = P (A | C) · P (B | C).
Equivalently: iff P (A | (B ∧ C)) = P (A | C), or P (B | (A ∧ C)) = P (B | C).
Example 21.1.28. Let’s assume toothache and catch are conditionally independent given
cavity/¬cavity. Then we can finally compute:
P (toothache∧catch | cavity)·P (cavity)
P (cavity | (toothache ∧ catch)) = P (toothache∧catch)
P (toothache | cavity)·P (catch | cavity)·P (cavity) 0.6·0.9·0.2
= P (toothache | cavity)·P (catch | cavity)·P (cavity)+P (toothache | ¬cavity)·P (catch | ¬cavity)·P (¬cavity) = 0.6·0.9·0.2+0.1·v0.2·0.8 =0.8
: 733 2025-05-14
21.1. PROBABILITY THEORY 501
Conditional Independence
Lemma 21.1.29. If A and B are conditionally independent given C, then P (A | (B ∧ C)) =
P (A | C)
Proof:
P (A∧B∧C) P (A∧B | C)·P (C) P (A | C)·P (B | C)·P (C) P (A | C)·P (B∧C)
P (A | (B∧C)) = P (B∧C) = P (B∧C) = P (B∧C) = P (B∧C) =
P (A | C)
□
Question: If A and B are conditionally independent given C, does this imply that A and
B are independent? No. See previous slides for a counterexample.
Question: If A and B are independent, does this imply that A and B are also condition-
ally independent given C? No. For example: First and Second are independent, but not
conditionally independent given S = 4.
Question: Okay, so what if A, B and C are all pairwise independent? Are A and B
conditionally independent given C now ? Still no. Remember: First = a, Second = b and
S = 7 are all independent, but First and Second are not conditionally independent given
S = 7.
Question: When can we infer conditional independence from a “more general” notion of
independence?
We need mutual independence. Roughly: A set of events is called mutually independent, if
every event is independent from any conjunction of the others. (Not really relevant for this
course though)
: 734 2025-05-14
21.1.3 Conclusion
Summary
Probability spaces serve as a mathematical model (and hence justification) for everything
related to probabilities.
The “atoms” of any statement of probability are the random variables. (Important special
cases: Boolean and finite domain)
: 735 2025-05-14
502 CHAPTER 21. QUANTIFYING UNCERTAINTY
Assume we can mathematically derive this to be the case: the probability of rain tomorrow
is 0.3. What does this even mean?
Frequentist Answer: The probability of an event is the limit of its relative frequency in a
large number of trials.
In other words: “In 30% of the cases where we have similar weather conditions, it rained the
next day.”
Objection: Okay, but what about unique events? “The probability of me passing the exam
is 80%” – does this mean anything, if I only take the exam once? Am I comparable to “similar
students”? What counts as sufficiently “similar”?
Bayesian Answer: Probabilities are degrees of belief. It means you should be 30% confident
that it will rain tomorrow.
Objection: And why should I? Is this not purely subjective then?
: 736 2025-05-14
Pragmatics
Pragmatically both interpretations amount to the same thing: I should act as if I’m 30%
confident that it will rain tomorrow. (Whether by fiat, or because in 30% of comparable
cases, it rained.)
Objection: Still: why should I? And why should my beliefs follow the seemingly arbitrary
Kolmogorov axioms?
[deFinetti:sssdp31]: If an agent has a belief that violates the Kolmogorov axioms, then
there exists a combination of “bets” on propositions so that the agent always loses money.
In other words: If your beliefs are not consistent with the mathematics, and you act in
accordance with your beliefs, there is a way to exploit this inconsistency to your disadvantage.
. . . and, more importantly, the AI agents you design! ,
I (and my agents) do not bet: That is not true, in a partially observable or non-
deterministic world, every action choice is a necessarily bet: The outcome is not sure.
: 737 2025-05-14
Do we... implement random variables as functions? Is a probability space a... class maybe?
No: As mentioned, we rarely know the probability space entirely. Instead we will use
probability distributions, which are just arrays (of arrays of...) of probabilities.
And then we represent those as sparsely as possible, by exploiting independence, conditional
independence, . . .
: 738 2025-05-14
Probability Distributions
Definition 21.2.1. The probability distribution for a random variable X, written P(X), is
the vector of probabilities for the (ordered) domain of X.
Note: The values in a probability distribution are all positive and sum to 1. (Why?)
: 739 2025-05-14
toothache ¬toothache
gingivitis ¬gingivitis gingivitis ¬gingivitis
cavity 0.007 0.06 0.005 0.05
¬cavity 0.08 0.003 0.045 0.75
504 CHAPTER 21. QUANTIFYING UNCERTAINTY
First \ S 2 3 4 5 6 7 8 9 10 11 12
1 1 1 1 1 1
1 36 36 36 36 36 36
0 0 0 0 0
1 1 1 1 1 1
2 0 36 36 36 36 36 36
0 0 0 0
1 1 1 1 1 1
3 0 0 36 36 36 36 36 36
0 0 0
1 1 1 1 1 1
4 0 0 0 36 36 36 36 36 36
0 0
1 1 1 1 1 1
5 0 0 0 0 36 36 36 36 36 36
0
1 1 1 1 1 1
6 0 0 0 0 0 36 36 36 36 36 36
Note that if we know the value of First, the value of S is completely determined by the value
of Second.
: 740 2025-05-14
toothache ¬toothache
cavity P (cavity | toothache) = 0.45 P (cavity | ¬toothache) = 0.065
¬cavity P (¬cavity | toothache) = 0.55 P (¬cavity | ¬toothache) = 0.935
First \ S 2 3 4 5 6 7 8 9 10 11 12
1 1 1 1 1
1 1 2 3 4 5 6
0 0 0 0 0
1 1 1 1 1 1
2 0 2 3 4 5 6 5
0 0 0 0
1 1 1 1 1 1
3 0 0 3 4 5 6 5 4
0 0 0
1 1 1 1 1 1
4 0 0 0 4 5 6 5 4 3
0 0
1 1 1 1 1 1
5 0 0 0 0 5 6 5 4 3 2
0
1 1 1 1 1
6 0 0 0 0 0 6 5 4 3 2
1
: 741 2025-05-14
Convention
We now “lift” multiplication and division to the level of whole probability distributions:
Definition 21.2.12. Whenever we use P in an equation, we take this to mean a system of
equations, for each value in the domains of the random variables involved.
Example 21.2.13.
21.2. PROBABILISTIC REASONING TECHNIQUES 505
P(Y |X)·P(X)
Bayes’ Theorem: P(X|Y ) = P(Y ) represents the system of equations P (X = x | (Y =
P (Y =y | (X=x))·P (X=x)
y)) = P (Y =y)
: 742 2025-05-14
Observation: The full joint probability distribution of variables X 1 , . . ., X n contains all the
information about the random variables and their conjunctions we need.
Example 21.2.14. We can read off the probability P (toothache) from the full joint probabil-
ity distribution as 0.007+0.06+0.08+0.003=0.15, and the probability P (toothache∧cavity)
as 0.007 + 0.06 = 0.067
But: just as we often don’t have a fully specified probability space to work in, we often
don’t have a full joint probability distribution for our random variables either.
Qn
Also: Given random variables X 1 , . . ., X n , the full joint probability distribution has i=1 |dom(X i )|
entries! (P(First, S) already has 60 entries!)
So: The rest of this section deals with keeping things small, by computing probabilities
instead of storing them all.
: 743 2025-05-14
Probabilistic Reasoning
Probabilistic reasoning refers to inferring probabilities of events from the probabilities of
other events
as opposed to determining the probabilities e.g. empirically, by gathering (sufficient amounts
of representative) data and counting.
Note: In practice, we are primarily interested in, and have access to, conditional probabilities
rather than the unconditional probabilities of conjunctions of events:
We don’t reason in a vacuum: Usually, we have some evidence and want to infer the
posterior probability of some related event. (e.g. infer a plausible cause given some
symptom)
; we are interested in the conditional probability P (hypothesis | observation).
506 CHAPTER 21. QUANTIFYING UNCERTAINTY
“80% of patients with a cavity complain about a toothache” (i.e. P (toothache | cavity))
is more the kind of data people actually collect and publish than “1.2% of the general
population have both a cavity and a toothache” (i.e. P (cavity ∧ toothache)).
Consider the probe catching in a cavity. The probe is a diagnostic tool, which is usually
evaluated in terms of its sensitivity P (catch | cavity) and specificity P (¬catch | ¬cavity).
(You have probably heard these words a lot since 2020...)
: 744 2025-05-14
Cavity
Toothache Catch
We likely know the sensitivity P (catch | cavity) and specificity P (¬catch | ¬cavity), which
jointly give us P(catch|cavity), and from medical studies, we should be able to determine
P (cavity) (the prevalence of cavities in the population) and P(toothache|cavity).
: 745 2025-05-14
Toothache Catch
Definition 21.2.15. A naive Bayes model (or, less accurately, Bayesian classifier, or, deroga-
torily, idiot Bayes model) consists of:
1. random variables C, E 1 , . . ., E n such that all the E 1 , . . ., E n are conditionally independent
given C,
2. the probability distribution P(C), and
3. the conditional probability distributions P(E i |C).
We call C the cause and the E 1 , . . ., E n the effects of the model.
Convention: Whenever we draw a graph of random variables, we take the arrows to connect
causes to their direct effects, and assert that unconnected nodes are conditionally independent
given all their ancestors. We will make this more precise later.
21.2. PROBABILISTIC REASONING TECHNIQUES 507
Can we compute the full joint probability distribution P(cavity, toothache, catch) from this
information?
: 746 2025-05-14
Hence:
Theorem 21.2.18. Given a naive Bayes model with effects E 1 , . . ., E n and cause C, we
have
n
Y
P(C, E 1 , . . ., E n ) = P(C) · ( P(E i |C)).
i=1
: 747 2025-05-14
Marginalization
P(C,E 1 ,...,E n )
Great, so now we can compute P(C|E 1 , . . ., E n ) = P(E 1 ,...,E n ) ...
we can compute
: 748 2025-05-14
Unknowns
What if we don’t know catch? (I’m not a dentist, I don’t have a probe...)
We split our effects into {E 1 , . . ., E n } = {O1 , . . ., OnO } ∪ {U 1 , . . ., U nU } – the observed
and unknown random variables.
Let DU := dom(U 1 ) × . . . × dom(U nu ). Then
P(C, O1 , . . ., OnO )
P(C|O1 , . . ., OnO )=
P(O1 , . . ., OnO )
P
u∈DU P(C, O 1 , . . ., O nO , U 1 = u1 , . . ., U nu = unu )
=P P
c∈dom(C) u∈DU P(O 1 , . . ., O nO , C = c, U 1 = u1 , . . ., U nu = unu )
P QnO QnU
u∈DU P(C) · ( i=1 P(O i |C)) · ( j=1 P(U j = uj |C))
=P P QnO QnU
c∈dom(C) u∈DU P (C = c) · ( i=1 P(O i |C = c)) · ( j=1 P (U j = uj | (C = c)))
QnO P QnU
P(C) · ( i=1 P(Oi |C)) · ( u∈DU j=1 P(U j = uj |C))
=P QnO P QnU
c∈dom(C) P (C = c) · ( i=1 P(O i |C = c)) · ( u∈DU j=1 P (U j = uj | (C = c)))
...oof...
: 749 2025-05-14
Unknowns
Continuing from above:
QnO P QnU
P(C) · ( i=1 P(Oi |C)) · ( u∈DU j=1 P(U j = uj |C))
P(C|O1 , . . ., OnO ) = P QnO P Q nU
c∈dom(C) P (C = c) · ( i=1 P(O i |C = c)) · ( u∈DU j=1 P (U j = uj | (C = c)))
P QnU
First, note that u∈DU j=1 P (U j = uj | (C = c)) = 1 (We’re summing over all possible
events on the (conditionally independent) U 1 , . . ., U nU given C = c)
QnO
P(C) · ( i=1 P(Oi |C))
P(C|O1 , . . ., OnO ) = P QnO
c∈dom(C) P (C = c) · ( i=1 P(O i |C = c))
1. the same for any given observations O1 , . . ., OnO , independent of the value of C, and
2. the sum over all the numerators in the full distribution.
That is: The denominator only serves to scale what is almost already the distribution
P(C|O1 , . . ., OnO ) to sum up to 1.
: 750 2025-05-14
Normalization
Definition 21.2.21 (Normalization). Given a vector w := ⟨w1 , . . ., wk ⟩ of numbers in [0,1]
Pk
where i=1 wi ≤ 1.
Then the normalized vector α(w) is defined (component-wise) as
wi
(α(w))i := Pk .
j=1 wj
Pk
Note that i=1 α(w)i = 1, i.e. α(w) is a probability distribution.
Also, note that this is just a fancy way of saying “first, compute all the numerators, then
divide all of them by their sums”.
: 751 2025-05-14
Dentistry Example
Putting things together, we get:
Say we have P (cavity) = 0.1, P (toothache | cavity) = 0.8, and P (toothache | ¬cavity) =
0.05. Then
: 752 2025-05-14
Given a new article, we just count the occurrences ki of the words in it and compute
n
Y
P(category|word1 = k1 , . . ., wordn = kn ) = α(P(category) · ( P(wordi = ki |category)))
i=1
: 753 2025-05-14
Inference by Enumeration
The rules we established for naive Bayes models, i.e. Bayes’s theorem, the product rule
and chain rule, marginalization and normalization, are general techniques for probabilistic
reasoning, and their usefulness is not limited to the naive Bayes models.
More generally:
Theorem 21.2.23. Let Q, E 1 , . . ., E nE , U 1 , . . ., U nU be random variables and D := dom(U 1 )×
. . . × dom(U nU ). Then
X
P(Q|E 1 = e1 , . . ., E nE = ene ) = α( P(Q, E 1 = e1 , . . ., E nE = ene , U 1 = u1 , . . ., U nU = unU ))
u∈D
.
We call Q the query variable, E 1 , . . ., E nE the evidence, and U 1 , . . ., U nU the unknown
(or hidden) variables, and computing a conditional probability this way enumeration.
: 754 2025-05-14
21.2. PROBABILISTIC REASONING TECHNIQUES 511
Every cell except [1, 1] possibly contains a pit, with 20% probabil-
ity.
pits cause a breeze in neighboring cells (we forget the wumpus
and the gold for now)
Where should the agent go, if there is a breeze at [1, 2] and [2, 1]?
: 755 2025-05-14
: 756 2025-05-14
Wumpus Continued
Problem: We only know P i,j for three fields. If we want to compute e.g. P 1,3 via
2
enumeration, that leaves 24 −4 = 4096 terms to sum over!
512 CHAPTER 21. QUANTIFYING UNCERTAINTY
Let’s do better.
Let b := ¬B 1,1 ∧ B 1,2 ∧ B 2,1 (All the breezes we know about)
: 757 2025-05-14
Optimized Wumpus
In particular:
X X
P(P 1,3 |p, b)=α( P(P 1,3 , b, p, f , o))=α( P (b | P 1,3 ,p,o,f ) · P(P 1,3 , p, f , o))
o∈O,f ∈F o∈O,f ∈F
XX X X
=α( P (b | P 1,3 ,p,f ) · P(P 1,3 , p, f , o))=α( P (b | P 1,3 ,p,f ) · ( P(P 1,3 , p, f , o)))
f ∈F o∈O f ∈F o∈O
X X
=α( P (b | P 1,3 ,p,f ) · ( P(P 1,3 ) · P (p) · P (f ) · P (o)))
f ∈F o∈O
X X
=α(P(P 1,3 ) · P (p) · ( P (b | P 1,3 ,p,f ) ·P (f ) · ( P (o))))
f ∈F
| {z } o∈O
∈{0,1} | {z }
=1
: 758 2025-05-14
Cooking Recipe
In general, when you want to reason probabilistically, a good heuristic is:
1. Try to frame the full joint probability distribution in terms of the probabilities you know.
Exploit product rule/chain rule, independence, conditional independence, marginalization
and domain knowledge (as e.g. P(b|p, f ) ∈ {0, 1})
; the problem can be solved at all!
21.2. PROBABILISTIC REASONING TECHNIQUES 513
3. Substitute by the result of 1., and again, exploit all of our machinery
4. Implement the resulting (system of) equation(s)
5. ???
6. Profit
: 759 2025-05-14
Summary
Probability distributions and conditional probability distributions allow us to represent random
variables as convenient datastructures in an implementation (Assuming they are finite
domain...)
The full joint probability distribution allows us to compute all probabilities of statements
about the random variables contained (But possibly inefficient)
Marginalization and normalization are the specific techniques for extracting the specific prob-
abilities we are interested in from the full joint probability distribution.
The product and chain rule, exploiting (conditional) independence, Bayes’ Theorem, and of
course domain specific knowledge allow us to do so much more efficiently.
Naive Bayes models are one example where all these techniques come together.
: 760 2025-05-14
514 CHAPTER 21. QUANTIFYING UNCERTAINTY
Chapter 22
22.1 Introduction
John, Mary, and My Brand-New Alarm
Example 22.1.1 (From Russell/Norvig).
I got very valuable stuff at home. So I bought an alarm. Unfortunately, the alarm just
rings at home, doesn’t call me on my mobile.
I’ve got two neighbors, Mary and John, who’ll call me if they hear the alarm.
The problem is that, sometimes, the alarm is caused by an earthquake.
Also, John might confuse the alarm with his telephone, and Mary might miss the alarm
altogether because she typically listens to loud music.
; Random variables: Burglary, Earthquake, Alarm, John, Mary. Given that both John
and Mary call me, what is the probability of a burglary?
; This is almost a naive Bayes model, but with multiple causes (Burglary and Earthquake)
for the Alarm, which in turn may cause John and/or Mary.
: 761 2025-05-14
515
516 CHAPTER 22. PROBABILISTIC REASONING: BAYESIAN NETWORKS
We assume:
We (should) know P(Alarm|Burglary, Earthquake), Burglary Earthquake
P(John|Alarm), and P(Mary|Alarm).
: 762 2025-05-14
: 763 2025-05-14
X i given Parents(X i ).
Definition 22.1.3. Let ⟨X , E⟩ be a directed acyclic graph, X ∈ X , and E ∗ the reflexive
transitive closure of E. The non-descendents of X are the elements of the set NonDesc(X) :=
{Y | (X,Y ) ̸∈ E ∗ }\Parents(X).
Note that the roots of the graph are conditionally independent given the empty set; i.e. they
are independent.
Theorem 22.1.4. The full joint probability distribution of a Bayesian network ⟨X , E⟩ is
given by Y
P(X 1 , . . ., X n ) = P(X i |Parents(X i ))
X i ∈X
: 764 2025-05-14
Bayesian networks have applications anywhere we have to do some form of “diagnosis”, i.e., we
observe some data (“symptoms”) and want to infere something about the underlying phenomena
(“causes”) generating that data! Here are some examples.
Some Applications
A ubiquitous problem: Observe “symptoms”, need to infer “causes”.
Medical Diagnosis Face Recognition
: 765 2025-05-14
all over the planet, and the “causes” are either earthquakes or nuclear tests. There are 10000s of
“detections” per day, the data arrives with long time delays and distributedly (no “ID”s attached
that would allow us to synchronize which measurements from station X correspond to which
measurements from station Y), the challenge is to determine which are natural and which are
atomic tests. (US senate refused to ratify the CNTB (comprehensive nuclear test ban treaty)
in 1998 saying it’s “too hard to monitor”)
Note: size(B) =
b The total number of entries in the conditional probability distributions.
Note: Smaller BN ; need to assess less probabilities, more efficient inference.
Qn
Observation 22.2.2. Explicit full joint probability distribution has size i=1 |Di |.
Observation 22.2.3. If |Parents(X i )| ≤ k for every X i , and Dmax is the largest random
k+1
variable domain, then size(B) ≤ n|Dmax | .
Example 22.2.4. For |Dmax | = 2, n = 20, k = 4 we have 220 = 1048576 probabilities, but
a Bayesian network of size ≤ 20 · 25 = 640 . . . !
Q1
In the worst case, size(B) = n · ( ·=i n)|Di |, namely if every variable depends on all its
predecessors in the chosen variable ordering.
Intuition: BNs are compact – i.e. of small size – if each variable is directly influenced only
by few of its predecessor variables.
: 766 2025-05-14
: 767 2025-05-14
In Particular: The size of a Bayesian network is not a fixed property of the domain. It
depends on the skill of the designer.
: 768 2025-05-14
Mary
John
Alarm
Earthquake
Burglary
: 769 2025-05-14
Note: For ??? we try to determine whether – given different value assignments to potential
parents – the probability of Xi being true differs? If yes, we include these parents. In the
particular case:
Mary
John
Earthquake
Burglary
Alarm
: 770 2025-05-14
Again: Given different value assignments to potential parents, does the probability of Xi being
true differ? If yes, include these parents.
1. M to J as before.
2. M, J to E as probability of E is higher if M/J is true.
3. Same for B; E to B because, given M and J are true, if E is true as well then prob of B is
lower than if E is false.
4. M /J/B/E to A because if M /J/B/E is true (even when changing the value of just one of
these) then probability of A is higher.
Mary
Alarm
Earthquake
Alarm
: 771 2025-05-14
Example 22.2.9. The sum of two dice throws S is entirely determined by the values of the
two dice F irst and Second.
Example 22.2.10. In the Wumpus example, the breezes are entirely determined by the pits
; Deterministic nodes model direct, causal relationships.
: 772 2025-05-14
: 773 2025-05-14
If
Qwe model Fever as a noisy disjunction node, then the general rule P (X i | Parents(X i )) =
{j | X j =T} q j for the CPT gives the following table:
: 774 2025-05-14
In general, noisy logical relationships in which a variable depends on k parents can be described
by O(k) parameters instead of O(2k ) for the full conditional probability table. This can make
assessment (and learning) tractable.
Example 22.2.14. The CPCS network [PraProMid:kelbn94] uses noisy-OR and noisy-
MAX distributions to model relationships among diseases and symptoms in internal medicine.
With 448 nodes and 906 links, it requires only 8,254 values instead of 133,931,430 for a
network with full conditional probability distributions.
: 775 2025-05-14
: 776 2025-05-14
Let’s do better!
: 777 2025-05-14
Let’s “optimize”:
X X
P(b|j, m) = α(P(b)·( P (e = be ) · ( P(a = ba |e = be , b) · P (j | a = ba ) · P (m | a = ba ))))
be ∈{T,F} ba ∈{T,F}
: 778 2025-05-14
Lemma 22.3.3. Given a query P(Q1 , . . ., QnQ |E 1 = e1 , . . ., E nE = enE ), we can ignore (and
remove) all hidden variables that are not ancestors of any of the Q1 , . . ., QnQ or E 1 , . . ., E nE .
: 779 2025-05-14
General worst case Complexity: O(2n ) – better, but still not great
: 780 2025-05-14
Enumeration: Example
Variable order: b, e, a, j, m
P (a | b,e) · P (j | a) · P (m | a) · 1.0
P (e) · +
P (¬a | b,e) · P (j | ¬a) · P (m | ¬a) · 1.0
P0 := P (b) · +
P (a | b,¬e) · P (j | a) · P (m | a) · 1.0
P (¬e) · +
P (¬a | b,¬e) · P (j | ¬a) · P (m | ¬a) · 1.0
P (a | ¬b,e) · P (j | a) · P (m | a) · 1.0
P (e) · + P (¬a | ¬b,e) · P (j | ¬a) · P (m | ¬a) · 1.0
P1 := P (¬b) · +
P (a | ¬b,¬e) · P (j | a) · P (m | a) · 1.0
P (¬e) · +
P (¬a | ¬b,¬e) · P (j | ¬a) · P (m | ¬a) · 1.0
P0 P1
⇐ ⟨P , ⟩
0 +P1 P0 +P1
X X
P(b|j = T, m = T) = α(P(b)·( P (e = be ) · ( P(a = ba |e = be , b) · P (j | a = ba ) · P (m | a = ba ))))
be ∈{T,F} ba ∈{T,F}
: 781 2025-05-14
: 782 2025-05-14
Variable Elimination 2
X X
P(b|j, m) = α(P(b)·( P (e = be ) · ( P(a = ba |e = be , b) · P (j | a = ba ) · P (m | a = ba ))))
be ∈{T,F} ba ∈{T,F}
The last two factors P (j | a = ba ), P (m | a = ba ) only depend on a, but are “trapped” behind
the summation over e, hence computed twice in two distinct recursive calls to EnumAll
Idea: Instead of left-to-right (top-down DFS), operate right-to-left (bottom-up) and store
intermediate “factors” along with their “dependencies”:
X X
α(P(b) · ( P (e = be ) · ( P(a = ba |e = be , b) · P (j | a = ba ) · P (m | a = ba ))))
|{z} | {z } | {z } | {z } | {z }
be ∈{T,F} ba ∈{T,F}
f7 (b) f5 (e) f3 (a,b,e) f2 (a) f1 (a)
| {z }
f4 (b,e)
| {z }
f6 (b)
: 783 2025-05-14
We only show variable elimination by example: (implementation details get tricky, but the
idea is simple)
P P
P(b)·( be ∈{T,F} P (e = be ) · ( ba ∈{T,F} P(a = ba |e = be , b) · P (j | a = ba ) · P (m | a = ba )))
; can speed things up by a factor of 1000! (or more, depending on the order of variables!)
: 784 2025-05-14
Theorem 22.3.6 (Bad News). For multiply connected Bayesian networks, probabilistic
inference is #P-hard. (#P is harder than NP, i.e. NP ⊆ #P)
So?: Life goes on . . . In the hard cases, if need be we can throw exactitude to the winds
and approximate.
: 785 2025-05-14
22.4 Conclusion
Summary
Bayesian networks (BN) are a wide-spread tool to model uncertainty, and to reason about
it. A BN represents conditional independence relations between random variables. It consists
of a graph encoding the variable dependencies, and of conditional probability tables (CPTs).
528 CHAPTER 22. PROBABILISTIC REASONING: BAYESIAN NETWORKS
Given a variable ordering, the BN is small if every variable depends on only a few of its
predecessors.
Probabilistic inference requires to compute the probability distribution of a set of query
variables, given a set of evidence variables whose values we know. The remaining variables
are hidden.
Inference by enumeration takes a BN as input, then applies Normalization+Marginalization,
the chain rule, and exploits conditional independence. This can be viewed as a tree search
that branches over all values of the hidden variables.
Variable elimination avoids unnecessary computation. It runs in polynomial time for poly-tree
BNs. In general, exact probabilistic inference is #P-hard. Approximate probabilistic inference
methods exist.
: 786 2025-05-14
Compilation to SAT: More precisely, to “weighted model counting” in CNF formulas. Model
counting extends DPLL with the ability to determine the number of satisfying interpretations.
Weighted model counting allows to define a mass for each such interpretation (= the proba-
bility of an atomic event).
Dynamic BN: BN with one slice of variables at each “time step”, encoding probabilistic
behavior over time.
Relational BN: BN with predicates and object variables.
First-order BN: Relational BN with quantification, i.e. probabilistic logic. E.g., the BLOG
language developed by Stuart Russel and co-workers.
: 787 2025-05-14
Reading:
• Chapter 14: Probabilistic Reasoning of [RusNor:AIMA03].
– Section 14.1 roughly corresponds to my “What is a Bayesian Network?”.
– Section 14.2 roughly corresponds to my “What is the Meaning of a Bayesian Network?” and
“Constructing Bayesian Networks”.The main change I made here is to define the semantics
of the BN in terms of the conditional independence relations, which I find clearer than RN’s
definition that uses the reconstructed full joint probability distribution instead.
– Section 14.4 roughly corresponds to my “Inference in Bayesian Networks”. RN give full details
on variable elimination, which makes for nice ongoing reading.
– Section 14.3 discusses how CPTs are specified in practice.
– Section 14.5 covers approximate sampling-based inference.
– Section 14.6 briefly discusses relational and first-order BNs.
– Section 14.7 briefly discusses other approaches to reasoning about uncertainty.
All of this is nice as additional background reading.
Chapter 23
23.1 Introduction
Overview
We now know how to update our world model, represented as (a set of) random variables,
given observations. Now we need to act.
Given a world model and a set of actions, what will the likely consequences of each action
be?
How “good” are these consequences?
Idea:
Represent actions as “special random variables”:
Given disjoint actions a1 , . . ., an , introduce a random variable A with domain {a1 , . . ., an }.
Then we can model/query P(X|A = ai ).
Assign numerical values to the possible outcomes of actions (i.e. a function u : dom(X)→
R) indicating their desirability.
Choose the action that maximizes the expected value of u
Definition 23.1.1. Decision theory investigates decision problems, i.e. how a utility-based
agent a deals with choosing among actions based on the desirability of their outcomes given
by a real-valued utility function U on states s ∈ S: i.e. U : S → R.
: 788 2025-05-14
Decision Theory
If our states are random variables, then we obtain a random variable for the utility function:
529
530 CHAPTER 23. MAKING SIMPLE DECISIONS RATIONALLY
Definition 23.1.3. Let A : Ω→D a random variable (where D is a set of actions) X i : Ω→Di
random variables (the state), and U : D1 ×. . .×Dn →R a utility function. Then the expected
utility of the action a ∈ D is the expected value of U (interpreted as a random variable) given
A = a ; i.e.
X
EU(a) := µ(X 1 = x1 , . . ., X n = xn | A = a) · U (x1 , . . ., xn )
⟨x1 ,...,xn ⟩∈D 1 ×...×D n
: 789 2025-05-14
Utility-based Agents
Definition 23.1.4. A utility-based agent uses a world model along with a utility function
that models its preferences among the states of that world. It chooses the action that leads
to the best expected utility.
54 Chapter 2. Intelligent Agents
Agent Schema:
Sensors
State
What the world
How the world evolves is like now
Environment
What action I
should do now
Agent Actuators
Figure 2.14 A model-based, utility-based agent. It uses a model of the world, along with
a utility
:
function that measures its preferences
790
among states of the world. Then it chooses the
2025-05-14
action that leads to the best expected utility, where expected utility is computed by averaging
over all possible outcome states, weighted by the probability of the outcome.
Maximizing Expected Utility (Ideas)
outcome. (Appendix A defines expectation more precisely.) In Chapter 16, we show that any
rational agent
Definition must(MEU
23.1.5 behaveprinciple
as if it possesses a utility function
for Rationality). We callwhose expected
an action valueif itittries
rational max-
to maximize. An agent that possesses an explicit utility function can make rational decisions
with a general-purpose algorithm that does not depend on the specific utility function being
maximized. In this way, the “global” definition of rationality—designating as rational those
agent functions that have the highest performance—is turned into a “local” constraint on
23.2. DECISION NETWORKS 531
imizes expected utility (MEU). An utility-based agent is called rational, iff it always chooses
a rational action.
Hooray: This solves all of AI. (in principle)
Example 23.1.7 (AI1). Heuristics in tree search (greedy search, A∗ ) and game-play (mini-
max, alpha-beta pruning) maximize “expected” utility.
⇒ In fully observable, deterministic environments, “expected utility” reduces to a specific
determined utility value:
EU(a) = U (T (S(s, e), a)), where e the most recent percept, s the current state, S the sensor
function and T the transition function.
Now let’s figure out how to actually assign utilities!
: 791 2025-05-14
Decision networks
Note the sheer amount of summands in the sum above in the general case! (⇒ We will
simplify where possible later)
532 CHAPTER 23. MAKING SIMPLE DECISIONS RATIONALLY
: 792 2025-05-14
: 793 2025-05-14
: 794 2025-05-14
Idea: A lottery represents the result of a nondeterministic action that can have outcomes
Ai with prior probability pi . For the binary case, we use [p,A;1−p,B]. We can then extend
preferences to include lotteries, as a measure of how strongly we prefer one prize over another.
Convention: We assume S to be closed under lotteries, i.e. lotteries themselves are also
states. That allows us to consider lotteries such as [p,A;1−p,[q,B;1−q,C]].
: 795 2025-05-14
Rational Preferences
Note: Preferences of a rational agent must obey certain constraints – An agent with rational
preferences can be described as an MEU-agent.
Definition 23.3.6. We call a set ≻ of preferences rational, iff the following constraints hold:
: 796 2025-05-14
Orderability: A≻B ∨ B≻A ∨ A∼B Given any two prizes or lotteries, a rational agent must either
prefer one to the other or else rate the two as equally preferable. That is, the agent cannot
avoid deciding. Refusing to bet is like refusing to allow time to pass.
Monotonicity: A≻B ⇒ ((p > q) ⇔ [p,A;1−p,B]≻[q,A;1−q,B]) Suppose two lotteries have the same
two possible outcomes, A and B. If an agent prefers A to B, then the agent must prefer the
lottery that has a higher probability for A (and vice versa).
Decomposability: [p,A;1−p,[q,B;1−q,C]]∼[p,A;((1−p)q),B ;((1−p)(1−q)),C] Compound lotteries
can be reduced to simpler ones using the laws of probability. This has been called the “no fun
in gambling” rule because it says that two consecutive lotteries can be compressed into a single
equivalent lottery: the following two are equivalent:
p
A p A
(1 − p)q
q
B B
1−p
(1 − p)(1 − q)
C
1−q
C
Example 23.3.7. An agent with intransitive preferences can be induced to give away all its
money:
If B≻C, then an agent who has C would pay (say) 1 cent to get B
If A≻B, then an agent who has B would pay (say) 1 cent to get A
If C≻A, then an agent who has A would pay (say) 1 cent to get C
: 797 2025-05-14
23.4 Utilities
Ramseys Theorem and Value Functions
Theorem 23.4.1. (Ramsey, 1931; von Neumann and Morgenstern, 1944)
Given a rational set of preferences there exists P a real valued function U such that U (A) ≥
U (B), iff A⪰B and U ([p1 ,S1 ; . . . ; pn ,Sn ]) = i pi U (Si )
23.4. UTILITIES 535
Observation: With deterministic prizes only (no lottery choices), only a total ordering on
prizes can be determined.
Definition 23.4.2. We call a total ordering on states a value function or ordinal utility
function. (If we don’t need to care about relative utilities of states, e.g. to compute
non-trivial expected utilities, that’s all we need anyway!)
: 798 2025-05-14
Utilities
Intuition: Utilities map states to real numbers.
Question: Which numbers exactly?
: 799 2025-05-14
: 800 2025-05-14
Comparing Utilities
Problem: What is the monetary value of a micromort?
Just ask people: What would you pay to avoid playing Russian roulette with a million-
barrelled revolver? (Usually: quite a
lot!)
But their behavior suggests a lower price:
Driving in a car for 370km incurs a risk of one micromort;
Over the life of your car – say, 150, 000km that’s 400 micromorts.
People appear to be willing to pay about 10, 000€ more for a safer car that halves the
risk of death. (; 25€ per micromort)
This figure has been confirmed across many individuals and risk types.
Of course, this argument holds only for small risks. Most people won’t agree to kill themselves
for 25M€. (Also: People are pretty bad at estimating and comparing risks, especially if
they are small.) (Various cognitive biases and heuristics are at work here!)
: 801 2025-05-14
: 802 2025-05-14
But in practice, our actions often impact multiple distinct “attributes” that need to be
weighed against each other.
⇒ Lotteries become complex very quickly
Definition 23.5.1. Let X 1 , . . ., X n be random variables with domains D1 , . . ., Dn . Then
we call a function u : D1 × . . . × Dn → R a (multi-attribute) utility function on attributes
X 1 , . . ., X n .
Note: In the general (worst) case, a multi-attribute utility function on n random variables
with domain sizes k each requires k n parameters to represent.
But: A utility function on multiple attributes often has “internal structure” that we can
exploit to simplify things.
For example, the distinct attributes are often “independent” with respect to their utility (a
higher-quality product is better than a lower-quality one that costs the same, and a cheaper
product is better than an expensive one of the same quality)
: 803 2025-05-14
Idea 1: Identify conditions under which decisions can be made without complete identifica-
tion of U (X 1 , . . ., X n ).
Idea 2: Identify various types of independence in preferences and derive consequent canonical
forms for U (X 1 , . . ., X n ).
: 804 2025-05-14
Strict Dominance
First Assumption: U is often monotone in each argument. (wlog. growing)
Definition 23.5.3. (Informally) An action B strictly dominates an action A, iff every possible
outcome of B is at least as good as every possible outcome of A,
: 805 2025-05-14
Stochastic Dominance
Definition 23.5.4. Let X1 , X2 distributions with domains ⊆ R.
X1 stochastically dominates X2 iff for all t ∈ R, we have P (X1 ≥ t) ≥ P (X2 ≥ t), and for
some t, we have P (X1 ≥ t) > P (X2 ≥ t).
Observation 23.5.5. If U is monotone in X1 , and P(X1 |a) stochastically dominates P(X1 |b)
for actions a, b, then a is always the better choice than b, with all other attributes Xi being
equal.
⇒ If some action P(Xi |a) stochastically dominates P(Xi |b) for all attributes Xi , we can
ignore b.
Observation: Stochastic dominance can often be determined without exact distributions
using qualitative reasoning.
: 806 2025-05-14
We have seen how we can do inference with attribute-based utility functions, let us consider
the computational implications. We observe that we have just replaced one evil – exponentially
23.5. MULTI-ATTRIBUTE UTILITY 539
many states (in terms of the attributes) – by another – exponentially many parameters of the
utility functions.
Wo we do what we always do in AI-2: we look for structure in the domain, do more theory to
be able to turn such structures into computationally improved representations.
: 807 2025-05-14
X k
Y
U= Ui (X i = xi )
({X 0 ,...,X k }⊆X ) i=1
: 808 2025-05-14
540 CHAPTER 23. MAKING SIMPLE DECISIONS RATIONALLY
label pairs of nodes with stochastic dominance: If (the utility of) some attribute dominates
(the utility of) another attribute, focus on the dominant one (e.g. if price is always more
important than quality, ignore quality whenever the price between two choices differs)
various techniques for variable elimination,
policy iteration (more on that when we talk about Markov decision procedures)
: 809 2025-05-14
: 810 2025-05-14
1
The prior probability of a block having oil is n each (mutually exclusive).
k
The current price of each block is n €.
A “consultant” offers an accurate survey of block (say) 3. How much should we be willing
to pay for the survey?
Solution: Compute the expected value of the best action given the information, minus the
expected value of the best action without information.
Example 23.6.4 (Oil Drilling Rights contd.).
1 k
Survey may say “oil in block 3 with probability n” ; we buy block 3 for n€ and make a
profit of (k − nk )€.
n−1
Survey may say “no oil in block 3 with probability n ” ; we buy another block, and
k
make an expected profit of n−1 − nk €.
Without the survery, the expected profit is 0
1 (n−1)k n−1 k k
Expected profit is n · n + n · n(n−1) = n.
k
So, we should pay up to n€ for the information. (as much as block 3 is worth!)
: 811 2025-05-14
Intuition: The VPI is the expected gain from knowing the value of F relative to the current
expected utility, and considering the relative probabilities of the possible outcomes of F .
: 812 2025-05-14
Properties of VPI
Observation 23.6.6 (VPI is Non-negative).
VPIE (F ) ≥ 0 for all j and E (in expectation, not post hoc)
Observation 23.6.7 (VPI is Non-additive).
VPIE (F, G) ̸= VPIE (F ) + VPIE (G) (consider, e.g., obtaining F twice)
Observation 23.6.8 (VPI is Order-independent).
: 813 2025-05-14
: 814 2025-05-14
We will now use information value theory to specialize our utility-based agent from above.
Definition 23.6.9. A simple information gathering agent. (gathers info before acting)
function Information−Gathering−Agent (percept) returns an action
persistent: D, a decision network
integrate percept into D
j := argmax VPIE (Ek )/Cost(Ek )
k
if VPIE (Ej ) > Cost(Ej ) return Request(Ej )
else return the best action from D
Problem: The information gathering implemented here is myopic, i.e. only acquires a
single evidence variable, or acts immediately. (cf. greedy search)
But it works relatively well in practice. (e.g. outperforms humans for selecting diagnostic
tests)
Strategies for nonmyopic information gathering exist (Not discussed in this course)
: 815 2025-05-14
23.6. THE VALUE OF INFORMATION 543
Summary
An MEU agent maximizes expected utility.
multi-attribute utility functions can usually be “destructured” to allow for better inference
and representation (can be monotone, attributes may dominate others, actions may dominate
others, may be multiplicative,...)
information value theory tells us when to explore rather than exploit, using
VPI (value of perfect information) to determine how much to “pay” for information.
: 816 2025-05-14
544 CHAPTER 23. MAKING SIMPLE DECISIONS RATIONALLY
Chapter 24
Stochastic Processes
The world changes in stochastically predictable ways.
Example 24.1.1.
The weather changes, but the weather tomorrow is somewhat predictable given today’s
weather and other factors, (which in turn (somewhat) depends on yesterday’s weather,
which in turn...)
the stock market changes, but the stock price tomorrow is probably related to today’s price,
A patient’s blood sugar changes, but their blood sugar is related to their blood sugar 10
minutes ago (in particular if they didn’t eat anything in between)
: 817 2025-05-14
545
546 CHAPTER 24. TEMPORAL PROBABILITY MODELS
: 818 2025-05-14
Markov Processes
Idea: Construct a Bayesian network from these variables (parents?)
...without everything exploding in size...?
Definition 24.1.6. Let (X t )t∈S a stochastic process. X has the (nth order) Markov property iff
X t only depends on a bounded subset of X0:t−1 – i.e. for all t ∈ S we have P(X t |X 0 , . . .X t−1 ) =
P(X t |X t−n , . . .X t−1 ) for some n ∈ S.
A stochastic process with the Markov property for some n is called a (nth order) Markov
process.
Important special cases:
Definition 24.1.7.
First-order Markov property: P(Xt |X0:t−1 ) = P(Xt |Xt−1 )
: 819 2025-05-14
Problem: This network does not actually have the First-order Markov property...
Possible fixes: We have two ways to fix this:
1. Increase the order of the Markov process. (more dependencies ⇒ more complex inference)
2. Add more state variables, e.g., Tempt , Pressuret . (more information sources)
24.1. MODELING TIME AND UNCERTAINTY 547
: 820 2025-05-14
Vt−1 Vt Vt+1
Xt−1 Xt Xt+1
Zt−1 Zt Zt+1
Example 24.1.10 (Battery Powered Robot). If the robot has a battery, the Markov property
is violated!
Battery exhaustion has a systematic effect on the change in velocity.
This depends on how much power was used by all previous manoeuvres.
: 821 2025-05-14
Mt−1 Mt Mt+1
Bt−1 Bt Bt+1
Vt−1 Vt Vt+1
Xt−1 Xt Xt+1
Zt−1 Zt Zt+1
: 822 2025-05-14
548 CHAPTER 24. TEMPORAL PROBABILITY MODELS
: 823 2025-05-14
Assumptions on Sensor Models: We usually assume the sensor Markov property and make it
stationary as well: P(E t |X t ) is fixed for all t.
Definition 24.1.16 (Note).
If a Markov chain X is stationary and discrete, we can represent the transition model as a
matrix Tij := P (X t = j | X t−1 = i).
If a sensor model has the sensor Markov property, we can represent each observation E t = et
at time t as the diagonal matrix Ot with Otii := P (E t = et | X t = i).
A pair ⟨X, E⟩ where X is a (stationary) Markov chains, E i only depends on X i , and E has
the sensor Markov property is called a (stationary) Hidden Markov Model (HMM). (X and
E are single variables)
: 824 2025-05-14
: 825 2025-05-14
Inference tasks
Definition 24.2.1. Given a Markov process with state variables X t and evidence variables E t ,
we are interested in the following Markov inference tasks:
Filtering (or monitoring) P(X t |E =e
1:t ): Given the sequence of observations up until time t,
compute the likely state of the world at current time t.
Note: The most likely sequence of states is not (necessarily) the sequence of most likely states
;-)
In this section, we assume X and E to represent multiple variables, where X jointly forms a
Markov chain and the E jointly have the sensor Markov property.
In the case where X and E are stationary single variables, we have a stationary hidden Markov
model and can use the matrix forms.
: 826 2025-05-14
Spoiler:
T
F (et , P(X t−1 |E =e =e
1:t−1 )) = α(Ot · T · P(X t−1 |E 1:t−1 ))
: 827 2025-05-14
Filtering Derivation
P(X t |E =e =e
1:t ) = P(X t |E t = et , E 1:t−1 ) (dividing up evidence)
= α(P(E t = et |X t , E 1:t−1 ) · P(X t |E =e
=e
1:t−1 )) (using Bayes’ rule)
=e
= α(P(E t = et |X t ) · P(XX t |E 1:t−1 )) (sensor Markov property)
=e =e
= α(P(E t = et |X t ) · ( P(X t |X t−1 = x, E 1:t−1 ) · P (X t−1 = x | E 1:t−1 ))) (marginalization)
x∈dom(X)
X
= α(P(E t = et |X t ) ·( P(X t |X t−1 = x) · P (X t−1 = x | E =e
1:t−1 ))) (conditional independence)
| {z } | {z } | {z }
x∈dom(X)
sensor model transition model recursive call
Definition 24.2.2. We call the inner part of the above expression the forward algorithm, i.e.
P(X t |E =e =e
1:t ) = α(FORWARD(et , P(X t−1 |E 1:t−1 ))) =: f 1:t .
: 828 2025-05-14
P (Rt+1 | Rt ) = 0.6, P (¬Rt+1 | ¬Rt ) = 0.8, P (Ut | Rt ) = 0.9 and P (¬Ut | ¬Rt ) = 0.85
0.6 0.4
⇒T=
0.2 0.8
The director carries an umbrella on days 1 and 2, and not on day 3.
0.9 0 0.1 0
⇒ O1 = O2 = and O3 = .
0 0.15 0 0.85
Then:
X
f 1:1 := P(R1 |U1 = T) = α(P(U1 = T|R1 ) · ( P(R1 |R0 = b) · P (R0 = b)))
b∈{T,F}
=α(⟨0.9, 0.15⟩ · (⟨0.6, 0.4⟩ · 0.5 + ⟨0.2, 0.8⟩ · 0.5)) = α(⟨0.36, 0.09⟩) = ⟨0.8, 0.2⟩
24.2. INFERENCE: FILTERING, PREDICTION, AND SMOOTHING 551
T0.5 0.9 0 0.6 0.2 0.5
Using matrices: α(O1 · T · ) = α( · · )
0.5 0 0.15 0.4 0.8 0.5
0.9 · 0.6 0.9 · 0.2 0.5 0.9 · 0.6 · 0.5 + 0.9 · 0.2 · 0.5 0.36
=α( · ) = α( ) = α( )
0.15 · 0.4 0.15 · 0.8 0.5 0.15 · 0.4 · 0.5 + 0.15 · 0.8 · 0.5 0.09
: 829 2025-05-14
: 830 2025-05-14
Observation 24.2.6. As k → ∞, P(X t+k |E =e 1:t ) converges towards a fixed point called the
stationary distribution of the Markov chain. (which we can compute from the equation
S = TT · S)
; the impact of the evidence vanishes.
; The stationary distribution only depends on the transition model.
; There is a small window of time (depending on the transition model) where the evidence
has enough impact to allow for prediction beyond the mere stationary distribution, called the
mixing time of the Markov chain.
; Predicting the future is difficult, and the further into the future, the more difficult it is
(Who knew...)
: 831 2025-05-14
Smoothing
Smoothing: P(X t−k |E =e1:t ) for k > 0.
Intuition: Use filtering to compute P(X t |E =e
1:t−k ), then recurse backwards from t until t − k.
552 CHAPTER 24. TEMPORAL PROBABILITY MODELS
P(X t−k |E =e
1:t ) = P(X t−k |E =e =e
t−(k−1):t , E 1:t−k ) (Divide the evidence)
= α(P(E t−(k−1):t |X t−k , E =e
=e
1:t−k ) · P(X t−k |E =e
1:t−k )) (Bayes Rule)
=e =e
= α(P(E t−(k−1):t |X t−k ) · P(X t−k |E 1:t−k )) (cond. independence)
| {z } | {z }
=:bt−(k−1):t =f 1:t−k
= α(f 1:t−k × bt−(k−1):t )
: 832 2025-05-14
Smoothing (continued)
Definition 24.2.7 (Backward message). bt−k:t = P(E =e
t−k:t |X t−(k+1) )
X
= P(E =e
t−k:t |X t−k = x, X t−(k+1) ) · P(X t−k = x|X t−(k+1) )
x∈dom(X)
X
= P (E =e
t−k:t | X t−k = x) · P(X t−k = x|X t−(k+1) )
x∈dom(X)
X
= P (E t−k = et−k , E =e
t−(k−1):t | X t−k = x) · P(X t−k = x|X t−(k+1) )
x∈dom(X)
X
= P (E t−k = et−k | X t−k = x) · P (E =e
t−(k−1):t | X t−k = x) · P(X t−k = x|X t−(k+1) )
| {z } | {z } | {z }
x∈dom(X)
sensor model =bt−(k−1):t transition model
Note: in a stationary hidden Markov model, we get the matrix formulation bt−k:t = T · Ot−k ·
bt−(k−1):t
Definition 24.2.8. We call the associated algorithm the backward algorithm, i.e. P(X t−k |E =e
1:t ) =
α(FORWARD(et−k , f 1:t−(k+1) ) × BACKWARD(et−(k−1) , bt−(k−2):t )).
| {z } | {z }
f 1:t−k bt−(k−1):t
As a starting point for the recursion, we let bt+1:t the uniform vector with 1 in every compo-
nent.
: 833 2025-05-14
Smoothing example
Example 24.2.9 (Smoothing Umbrellas). Reminder: We assumed P(R0 ) = ⟨0.5, 0.5⟩, P (Rt+1 | Rt ) =
0.6, P (¬Rt+1 | ¬Rt ) = 0.8, P (Ut | Rt ) =0.9, P (¬Ut |
¬Rt ) = 0.85
0.6 0.4 0.9 0 0.1 0
⇒T= , O1 = O2 = and O3 = . (The
0.2 0.8 0 0.15 0 0.85
director carries an umbrella on days 1 and 2, and not on day 3)
f 1:1 = ⟨0.8, 0.2⟩, f 1:2 = ⟨0.87, 0.13⟩ and f 1:3 = ⟨0.12, 0.88⟩
Let’s compute
P(R1 |U1 = T, U2 = T, U3 = F) = α(f 1:1 × b2:3 )
: 834 2025-05-14
: 835 2025-05-14
In the second for-loop, we compute both f 1:i and bt−i:t (Only one copy of f 1:i , bt−i:t is
stored)
⇒ constant space.
But: Requires that both matrices are invertible, i.e. every observation must be possible in
every state. (Possible hack: increase the probabilities of 0 to “negligibly small”)
: 836 2025-05-14
Among the resulting paths, pick the one to the X t = xt with the most likely path,
and then recurse backwards.
; we want to know max P(X =x =e
1:t−1 , X t |E 1:t ), and then pick the xt with the maximal
x1 ,...,xt−1
value.
: 837 2025-05-14
max P(X =x =e
1:t−1 , X t |E 1:t )
x1 ,...,xt−1
Figure 15.5 (a) Possible state sequences for Rain can be viewed as paths through a graph
bold arrows: best predecessor
of the possible measured
states at each time [Link] “best
(States preceding
t
are shown sequence
as rectangles to avoid probability
confusion × transition
probability” with nodes in a Bayes net.) (b) Operation of the Viterbi algorithm for the umbrella obser-
vation sequence [true, true, false, true, true]. For each t, we have shown the values of the
message m1:t , which gives the probability of the best sequence reaching each state at time t.
: 838 2025-05-14
Also, for each state, the bold arrow leading into it indicates its best predecessor as measured
by the product of the preceding sequence probability and the transition probability. Following
the bold arrows back from the most likely state in m1:5 gives the most likely sequence.
The Viterbi Algorithm
butions over single time steps, whereas to find the most likely sequence we must consider
Definition 24.2.13. The Viterbi
joint probabilities over all algorithm now
the time steps. Theproceeds
results can as follows:
in fact be quite different. (See
Exercise 15.4.)
There is a linear-time algorithm for finding the most likely sequence, but it requires a
little more thought. It relies on the same Markov property that yielded efficient algorithms for
filtering and smoothing. The easiest way to think about the problem is to view each sequence
as a path through a graph whose nodes are the possible states at each time step. Such a
graph is shown for the umbrella world in Figure 15.5(a). Now consider the task of finding
the most likely path through this graph, where the likelihood of any path is the product of
the transition probabilities along the path and the probabilities of the given observations at
each state. Let’s focus in particular on paths that reach the state Rain 5 = true. Because of
the Markov property, it follows that the most likely path to the state Rain 5 = true consists of
the most likely path to some state at time 4 followed by a transition to Rain 5 = true; and the
24.3. HIDDEN MARKOV MODELS – EXTENDED EXAMPLE 555
Observation 24.2.14. Viterbi has linear time complexity and linear space complexity (needs to
keep the most likely sequence leading to each state).
: 839 2025-05-14
Remark 24.3.2. This only works for perfect sensors. (else no impossible states)
What if our sensors are imperfect?
: 840 2025-05-14
1
We do not know where the robot starts: P (X 0 ) = n (here n = 42)
Evidence variable E t : four bit presence/absence of obstacles in N, S, W, E. Let dit be the
number of wrong bits and ϵ the error rate of the sensor. Then
4−dit
P (E t = et | X t = i) = Otii = (1 − ϵ) · ϵdit
: 841 2025-05-14
b) Posterior
(b) distribution
(b) Posterior
Posterior overover
distribution
distribution robot
over location
robot
robot locationafter
location after EE111=
after E ==N
NN SW
SW,
SW, E =and
E 22 = N
NSSE2 = N S
Still the same
Figure locationsPosterior
as in the “perfect sensing” case, butonenow other locations have non-zero
Figure 15.7
15.7 Posterior distribution
distribution over
over robot
robot location:
location: (a)
(a) one observation
observation EE11 =
=N SW ;;
N SW
probability. (b) after a second observation E = N S. The size of each disk corresponds to the probability
(b) after a second observation E = N S. The size of each disk corresponds to the probability
2
2
that
that the
the robot
robot is
is at
at that
that location.
location. The
The sensor
sensor error
error rate
rate is
is !! =
= 0.2.
0.2.
: 842 2025-05-14
NNS, S, for
for example,
example, toto mean
mean that
that the
the north
north and
and south
south sensors
sensors report
report an
an obstacle
obstacle and
and the
the east and
east and
west do not. Suppose that each sensor’s error rate is ! and that errors occur
west do not. Suppose that each sensor’s error rate is ! and that errors occur independently forindependently for
HMM Example: Further Inference Applications
the four sensor directions. In that case, the probability
the four sensor directions. In that case, the probability of getting all four bits right is (1 −
of getting all four bits right is (1 − !)4!) 4
and 4
and the the probability
probability ofof getting
getting them
them all
all wrong
wrong is
is !!4.. Furthermore,
Furthermore, if if ddit is the discrepancy—the
it is the discrepancy—the
number
number of of bits
bits that
that are
are different—between
different—between the the true
true values
values for
for square
square ii and
and the
the actual
actual reading
reading
eet ,, then
then the probability that a robot in square i would receive a sensor reading et is
the probability that a robot in square i would receive a sensor reading e is
t t
4−dit dit
P
P (E = eett || X
(Ett = Xtt =
= i) =O
i) = Ottiiii = (1 −
= (1 − !)
!)4−dit !!dit ..
24.4. DYNAMIC BAYESIAN NETWORKS 557
Idea: We can use smoothing: bk+1:t = TOk+1 bk+2:t to find out where it started and the
Section
Section 15.3. algorithm
15.3.
Viterbi HiddenMarkov
Hidden Markov
to Models
find Models
the most likely path it took. 583
583
Example [Link] of HMM localization vs. observation length(various error rates ϵ)
66 11
5.5
5.5 ==0.20
0.20
0.9
==0.10
0.10 0.9
55 0.8
==0.05
0.05 0.8
Localization error
4.5
Localization error
4.5 ==0.02
0.02
accuracy
0.7
Path accuracy
44 0.7
==0.00
0.00
3.5
3.5 0.6
0.6 ==0.00
0.00
33 0.5
0.5 ==0.02
0.02
2.5
Path
2.5 0.4
0.4 ==0.05
0.05
22 = 0.10
= 0.10
0.3
0.3 ==0.20
0.20
1.5
1.5
11 0.2
0.2
0.5
0.5 0.1
0.1
00 5 5 1010 1515 2020 25 25 3030 35
35 40
40 00 55 10 15
10 15 20 20 25 25 3030 35
35 40
40
Numberofofobservations
Number observations Numberofofobservations
Number observations
24.4 Dynamic
takentotoget
taken whereBayesian
getwhere ititisisnow.
[Link] Networks
Figure15.8
15.8 showsthe
shows thelocalization
localizationerror
errorand
andViterbi
Viterbipath
pathaccuracy
accuracy
forvarious
for variousvalues
valuesofofthetheper-bit
per-bitsensor
sensorerror
errorrate rate !.!. Even
Evenwhenwhen!!isis20%—which
20%—which means means thatthat
theoverall
overallsensor
sensorreading
readingisiswrong
wrong59% 59%ofofthe thetime—the
time—therobot robotisisusually
usuallyable
ableto towork
workout outitsits
Dynamic the Bayesian
locationwithin
withintwo
networks
twosquares
squaresafterafter25 25observations.
observations. This Thisisisbecause
because of ofthe
thealgorithm’s
algorithm’s ability
ability
location
totointegrate
integrateevidence
evidenceoverovertime
timeand andtototake
takeintointoaccount
accountthe theprobabilistic
probabilisticconstraints
constraints imposed
imposed
Definition
on the 24.4.1.
location A Bayesian
sequence by network
the transition D is called
model. dynamic
When
on the location sequence by the transition model. When ! is 10%, the performance after ! is (a DBN),
10%, the iff its random
performance after variables
are indexed
a by
half-dozen a time structure.
observations is hard We to assume
distinguish thatfromD is
the performance
a half-dozen observations is hard to distinguish from the performance with perfect sensing. with perfect sensing.
Exercise15.7
Exercise 15.7asks
asksyou
youtotoexplore
explorehow howrobust
robustthe theHMM
HMMlocalization
localizationalgorithm
algorithm isisto toerrors
errors in in
time sliced,
theprior
prior i.e. thatP(X
distribution the0)time
P(X ) and slices
in the Dt – themodel
transition subgraphs
model itself. of t-indexed
Broadly random
speaking, high variables
levels and
the distribution 0 and in the transition itself. Broadly speaking, high levels
the of edges between
localization and them
path –
accuracyare isomorphic.
are maintained even in the face
of localization and path accuracy are maintained even in the face of substantial errors in the of substantial errors in the
models
amodels
[Link] chain, i.e. that variables X can only have parents in D and D
used.
stationary t t t−1 .
The statevariable
The state variable for for the
the example
example we we have have considered
considered inin thisthis section
section isis aa physical
physical
location
Xt , location
E ininthe
t contain the world. Other
arbitrarily
world. Other
many problems
variables
problems can,
can, inofof course, include
a course,
replicated include other aspects
Bayesian
other aspects
network. of the
of the world.
world.
Exercise15.8
Exercise 15.8asks
asksyou
youtotoconsider
consideraaversionversionof ofthethevacuum
vacuumrobot robotthat
thathas
hasthe
thepolicy
policyof ofgoing
going
Examplestraight24.4.2.
straight forasaslong
for longasasititcan;
can;only onlywhenwhenititencounters
encounters an an obstacle
obstacle does
does itit change
change to to aa new
new
(randomly selected) heading. To model this robot, each state in the model consists of aa
(randomly selected) heading. To model this robot, each state in the model consists of
(location,heading)
(location, heading)[Link]
Forthe
For theenvironment
environment ininFigure Robot
Figure15.7, Motion
15.7, which
which has 42
has 42 empty
empty squares,
squares,
thisleads
this leadstoto168168states
statesand
andaatransition
transitionmatrix
matrixwith with168 16822==28, 28,224 entries—stillaamanageable
224entries—still manageable
[Link]
number. weaddaddthe
thepossibility
possibilityofofdirt dirtininthe
thesquares,
squares,the thenumber
numberof ofstates
statesisismultiplied
multiplied by by
42 and the transition matrix ends up with more than 1029 29 entries—no longer a manageable
2242 and the transition matrix ends up with more than 10 entries—no longer a manageable
number;Section
number; Section15.515.5shows
showshow howtotouse usedynamic
dynamicBayesianBayesiannetworks
networksto tomodel
modeldomains
domains with with
many state variables. If we allow the robot to move continuously
many state variables. If we allow the robot to move continuously rather than in a discrete rather than in a discrete
grid,the
grid, thenumber
numberofofstates
statesbecomes
becomesinfinite;
infinite;the thenextnextsection
sectionshowsshowshowhowto tohandle
handlethisthiscase.
case.
: 844 2025-05-14
Example 24.4.4 (Sparse Dependencies). With 20 Boolean state variables, three parents
each, a DBN has 20 · 23 = 160 parameters, the corresponding HMM has 220 · 220 ≈ 1012 .
: 845 2025-05-14
P (R0 )
0.7 Rain0 Rain1
R0 P (R1 )
T 0.7
F 0.3 R1 P (U1 )
T 0.9
F 0.2
Umbrella1
Definition 24.4.6. Rollup filtering: add slice t+1, “sum out” slice t using variable elimination.
Observation: Largest factor is O(dn+1 ), update cost O(dn+2 ), where d is the maximal
domain size.
Note: Much better than the HMM update cost of O(d2n )
: 846 2025-05-14
Summary
Temporal probability models use state and evidence variables replicated over time.
Markov property and stationarity assumption, so we need both
24.4. DYNAMIC BAYESIAN NETWORKS 559
Hidden Markov models have a single discrete state variable; (used for speech recognition)
DBNs subsume HMMs, exact update intractable.
: 847 2025-05-14
560 CHAPTER 24. TEMPORAL PROBABILITY MODELS
Chapter 25
We will now pick up the thread from chapter 23 but using temporal models instead of simply
probabilistic ones. We will first look at a sequential decision theory in the special case, where the
environment is stochastic, but fully observable (Markov decision processes) and then lift that to
obtain POMDPs and present an agent design based on that.
Outline
We will now combine the ideas of stochastic process with that of acting based on maximizing
expected utility:
: 848 2025-05-14
561
562 CHAPTER 25. MAKING COMPLEX DECISIONS
Search
explicit actions uncertainty
and subgoals and utility
: 849 2025-05-14
We will fortify our intuition by an example. It is specifically chosen to be very simple, but
to exhibit all the peculiarities of Markov decision problems, which we will generalize from this
example.
: 850 2025-05-14
Perhaps what is more interesting than the components of an MDP is that is not a component:
a belief and/or sensor model. Recall that MDPs are for fully observable environments.
Idea: We use the rewards as a utility function: The goal is to choose actions such that the
expected cumulative rewards for the “foreseeable future” is maximized
⇒ need to take future actions and future states into account
: 851 2025-05-14
Solving MDPs
In MDPs, the aim is to find an optimal policy π(s), which tells us the best action for every
possible state s. (because we can’t predict where we might end up, we need to consider all
states)
Definition 25.1.5. A policy π for an MDP is a function mapping each state s to an action
a ∈ As.
An optimal policy is a policy that maximizes the expected total rewards. (for some notion of
“total”...)
Example 25.1.6. Optimal policy when state penalty R(s) is 0.04:
Note: When you run against a wall, you stay in your square.
: 852 2025-05-14
+1 +1
+1 +1 +1 +1
1
–1 –1 –1 –1
+1
1 2 3 4
R(s) < –1.6284 – 0.4278 < R(s) < – 0.0850 – 0.0221 < R(s) < 0 R(s) > 0
–1
(a) (b)
Question: Explain what you see in a qualitative manner!
+1 +1
–1 –1
1 2 3 4
: 853 2025-05-14
Recall: We cannot observe/assess utility functions, only preferences ; induce utility func-
tions from rational preferences
Problem: In MDPs we need to understand preferences between sequences of states.
: 854 2025-05-14
: 855 2025-05-14
discounted rewards lead to stationary policies, which are easier to compute and often more
adequate (unless we know that remaining time matters),
discounted rewards mean we value short-term gains over long-term gains (all else being
equal), which is often realistic (e.g. the same amount of money gained early gives more
opportunity to spend/invest ⇒ potentially more utility in the long run)
we can interpret the discount factor as a measure of uncertainty about future rewards ⇒
more robust measure in uncertain environments.
: 856 2025-05-14
Utility of States
Remember: Given a sequence of states S = s0 , s1 , s2 , . . ., and a discount factor 0 ≤ γ < 1,
the utility of the sequence is
∞
X
U (S) = γ t R(st )
t=0
Definition 25.2.3. Given a policy π and a starting state s0 , let Ssπ0 be the random variable giving
the sequence of states resulting from executing π at every state starting at s0 . (Since the
environment is stochastic, we don’t know the exact sequence.)
Then the expected utility obtained by executing π starting in s0 is given by
U π (s0 ):=EU(Ssπ0 ).
Note: This is perfectly well-defined, but almost always computationally infeasible. (requires
considering all possible (potentially infinite) sequences of states)
: 857 2025-05-14
566 CHAPTER 25. MAKING COMPLEX DECISIONS
⇒ given the “true” utilities, we can compute the optimal policy and vice versa.
: 858 2025-05-14
Question: Why do we go left in (3, 1) and not up? (follow the utility)
: 859 2025-05-14
expected sum of rewards = current reward + γ · exp. reward sum after best action
25.3. VALUE/POLICY ITERATION 567
: 860 2025-05-14
Definition 25.3.3. The value iteration algorithm for utilitysutility function is given by
function VALUE−ITERATION (mdp,ϵ) returns a utility fn.
inputs: mdp, an MDP with states S, actions A(s), transition model P (s′ | s,a),
rewards R(s), and discount γ
ϵ, the maximum error allowed in the utility of any state
local variables: U , U ′ , vectors of utilities for states in S, initially zero
δ, the maximum change in the utility of any state in an iteration
repeat
U := U ′ ; δ := 0
for each state s in S do
U ′ [s] := R(s) + γ · max ( s′ U [s′ ] · P (s′ | s,a))
P
a∈A(s)
if |U ′ [s] − U [s]| > δ then δ := |U ′ [s] − U [s]|
until δ < ϵ(1 − γ)/γ
return U
P
Remark: Retrieve the optimal policy with π[s]:=argmax ( s′ U [s′ ] · P (s′ | s,a))
a∈A(s)
: 861 2025-05-14
Figure 17.4
Figure 17.4 The The value
value iteration
iterationalgorithm
algorithmfor
forcalculating
calculatingutilities
utilitiesofofstates.
[Link]
Thetermina-
termina-
568 tion condition
tion condition is
is from
from Equation
Equation(17.8).
(17.8).
CHAPTER 25. MAKING COMPLEX DECISIONS
1e+07
1e+07
11 (4,3)
(4,3) c c==0.0001
0.0001
(3,3)
(3,3) 1e+06
1e+06 c c==0.001
0.001
0.8
0.8 c c==0.01
0.01
(1,1)
(1,1)
Iterations required
c c==0.1
0.1
required
100000
100000
Utility estimates
0.6
0.6 (3,1)
(3,1)
10000
10000
0.4
0.4 (4,1)
(4,1)
Iterations
1000
1000
0.2
0.2
100
100
00
10
10
-0.2
-0.2
11
00 55 10
10 1515 20
20 25
25 30
30 0.5
0.50.55
0.550.6
0.60.65
0.650.7
0.70.75
0.750.8
0.80.85
0.850.9
0.90.95
0.951 1
Number
Numberofofiterations
iterations Discount
Discountfactor
factor
(a)
(a) (where ε = c · Rmax ) (b)
(b)
Figure
Figure 17.5 17.5 (a) (a) Graph
Graph showing
showingthetheevolution
evolutionofofthe
theutilities
utilitiesofofselected
selectedstates
statesusing
usingvalue
value
iteration.
iteration.
: (b)
(b) The
The number
number ofof value
value iterations
iterations
862 kk required
requiredtotoguarantee
guaranteean an error
errorofofatatmost
2025-05-14
most
!== cc ·· R max,, for
Rmax for different
differentvalues
valuesofofc,c,as
asaafunction
functionofofthe
thediscount
discountfactor
factorγ.γ.
Convergence
where the
the update
update isis assumed
assumed to to be
be applied
applied simultaneously
simultaneously totoall allthe
thestates
statesatateach
eachiteration.
iteration.
If we apply
apply the
the Bellman
Bellman update
update infinitely
infinitely often,
often, we
we are
are guaranteed
guaranteed
Definition 25.3.5. The maximum norm is defined as ∥U ∥ = max |U (s)|, so ∥U − V ∥ = to
toreach
reach an
anequilibrium
equilibrium
(see
(see Section
Section 17.2.3), in
in which
17.2.3),betweenwhich case the final utility values must be s solutions to the Bellman
maximum difference U case
and Vthe . final utility values must be solutions to the Bellman
equations.
equations. InIn fact,
fact, they
they are
are also
also the uniquesolutions,
the unique solutions,and
andthe
thecorresponding
correspondingpolicypolicy(obtained
(obtained
using
using Equation (17.4)) is optimal. The algorithm, called VALUE -I TERATION, ,is
Let U Equation
t
and U (17.4))
t+1
be is optimal.
successive The algorithm,
approximations to called
the true V
utility
ALUE U-Iduring value
TERATION isshown
showninin
iteration.
Figure 17.4.
Figure
Theorem 17.4.
25.3.6. For any two approximations U t and V t
We
We can apply
can apply value
value iteration
iteration to to the
the 44××33world
worldininFigure
Figure17.1(a).
17.1(a). Starting
Startingwith
withinitial
initial
values of zero, the utilities evolve
values of zero, the utilities evolve t+1as shown
U as−shown V t+1in Figure 17.5(a).
in≤Figure t
γ U 17.5(a).
−V t Notice how the states at differ-
Notice how the states at differ-
I.e., any distinct approximations get closer to each other over time
In particular, any approximation gets closer to the true U over time
⇒ value iteration converges to a unique, stable, optimal solution.
Theorem 25.3.7. If U t+1 − U t < ϵ, then U t+1 − U < 2ϵγ/1 − γ
(once the change in U t becomes small, we are almost done.)
Remark: The policy resulting from U t may be optimal long before the utilities convergence!
: 863 2025-05-14
So we see that iteration with Bellman updates will always converge towards the utility of
a state, even without knowing the optimal policy. That gives us a first way of dealing with
sequential decision problems: we compute utility functions based on states and then use the
standard MEU machinery. We have seen above that optimal policies and state utilities are
essentially interchangeable: we can compute one from the other. This leads to another approach
to computing state utilities: policy iteration, which we will discuss now.
Policy Iteration
Recap: Value iteration computes utilities ; optimal policy by MEU.
This even works if the utility estimate is inaccurate. (⇝ policy loss small)
Idea: Search for optimal policy and utility values simultaneously [Howard:dpmp60]:
Iterate
25.3. VALUE/POLICY ITERATION 569
policy evaluation: given policy πi , calculate Ui = U πi , the utility of each state were πi to
be executed.
policy improvement: calculate a new MEU policy πi+1 using 1 lookahead
Terminate if policy improvement yields no change in computed utilities.
: 864 2025-05-14
: 865 2025-05-14
Policy Evaluation
Problem: How to implement the POLICY−EVALUATION algorithm?
Solution: To compute utilities given a fixed π: For all s we have
X
U (s) = R(s) + γ( U (s′ ) · P (s′ | s,π(s)))
s′
(i.e. Bellman equation with the maximum replaced by the current policy π)
Example 25.3.11 (Simplified Bellman Equations for π).
: 866 2025-05-14
: 867 2025-05-14
Partial Observability
Definition 25.4.1. A partially observable MDP (a POMDP for short) is a MDP together
with an observation model O that has the sensor Markov property and is stationary: O(s, e) =
P (e | s).
Example 25.4.2 (Noisy 4x3 World).
Problem: Agent does not know which state it is in ; makes no sense to talk about policy
π(s)!
Theorem 25.4.3 (Astrom 1965). The optimal policy in a POMDP is a function π(b) where
b is the belief state (probability distribution over states).
Idea: Convert a POMDP into an MDP in belief state space, where T (b, a, b′ ) is the proba-
bility that the new belief state is b′ given that the current belief state is b and the agent does
a. I.e., essentially a filtering update step.
25.4. PARTIALLY OBSERVABLE MDPS 571
: 868 2025-05-14
For POMDPs, we also need to consider actions. (but the effect is the same)
If b is the previous belief state and agent does action A = a and then perceives E = e, then
the new belief state is
X
b′ = α(P(E = e|s′ ) · ( P(s′ |S = s, A = a) · b(s)))
s
Consequence: The optimal policy can be written as a function π ∗ (b) from belief states to
actions.
Definition 25.4.4. The POMDP decision cycle is to iterate over
1. Given the current belief state b, execute the action a = π ∗ (b)
2. Receive percept e.
3. Set the current belief state to FORWARD(b, a, e) and repeat.
Intuition: POMDP decision cycle is search in belief state space.
: 869 2025-05-14
Observation 25.4.5. Actions change the belief state, not just the (physical) state.
Thus POMDP solutions automatically include information gathering behavior.
Problem: The belief state is continuous: If there are n states, b is an n-dimensional real-
valued vector.
Example 25.4.6. The belief state of the 4x3 world is a 11 dimensional continuous space.
(11 states)
Theorem 25.4.7. Solving POMDPs is very hard! (actually, PSPACE hard)
In particular, none of the algorithms we have learned applies. (discreteness assumption)
The real world is a POMDP (with initially unknown transition model T and sensor model O)
: 870 2025-05-14
572 CHAPTER 25. MAKING COMPLEX DECISIONS
Write the probability of reaching b′ from b, given action a, as P (b′ | b,a), then
X
P (b′ | b,a) = P (b′ | a,b) = P (b′ | e,a,b) · P (e | a,b)
e
X X X
′
= P (b | e,a,b) · ( P (e | s′ ) · ( P (s′ | s,a), b(s)))
e s′ s
Observation: This equation defines a transition model for belief state space!
Idea: We can also define a reward function for belief states:
X
ρ(b):= b(s) · R(s)
s
i.e., the expected reward for the actual states the agent might be in.
Together, P (b′ | b,a) and ρ(b) define an (observable) MDP on the space of belief states.
Theorem 25.4.8. An optimal policy π ∗ (b) for this MDP, is also an optimal policy for the
original POMDP.
Upshot: Solving a POMDP on a physical state space can be reduced to solving an MDP
on the corresponding belief state space.
Remember: The belief state is always observable to the agent, by definition.
: 872 2025-05-14
Definition 25.4.9. Given a set of percepts E and a set of actions A, a conditional plan is either
an action a ∈ A, or a tuple ⟨a, E ′ , p1 , p2 ⟩ such that a ∈ A, E ′ ⊆ E, and p1 , p2 are conditional
plans.
It represents the strategy “First execute a, If we subsequently perceive e ∈ E ′ , continue with
p1 , otherwise continue with p2 .”
The depth of a conditional plan p is the maximum number of actions in any path from p
before reaching a single action plan.
: 873 2025-05-14
Observation 2: We can replace the original actions by conditional plans on those actions!
Let π ∗ be the subsequent optimal policy. At any given belief state b,
π ∗ will choose to execute the conditional plan with highest expected utility
the expected utility of b under the π ∗ is the utility of that plan:
∗
U (b) = U π (b) = max (b·αp )
b
: 874 2025-05-14
574 CHAPTER 25. MAKING COMPLEX DECISIONS
3 3
2.5 2.5
2 2
Utility
Utility
0.5 0.5
0 0
0 0.2 0.4 0.6 0.8 1 0 0.2 0.4 0.6 0.8 1
Probability of state 1 Probability of state 1
(a) (b)
The maximum represents the utility function for the finite-horizon problem that allows
3 7.5
just one action
2.5 7
in each “piece” the optimal action is the first action of the corresponding plan.
2 6.5
Here the optimal one-step policy is to “Stay” when b(1) > 0.5 and “Go” otherwise.
Utility
Utility
1.5 6
compute the utilities for conditional
1 plans of depth 2 by considering 5.5
0 4.5
each possible subsequent percept,
0
and
0.2
then
0.4 0.6 0.8 1 0 0.2 0.4 0.6 0.8 1
each way of choosing a depth-1 plan toProbability
executeof for
state each
1 percept: Probability of state 1
(c) (d)
There are eight of depth 2:
Figure 17.8 (a) Utility of two one-step plans as a function of the initial belief state b(1)
[Stay, if P = 0 then Stay elsetwo-state
for the Stay fi], [Stay,
world, if the
with P = 0 then Stayutility
corresponding else function
Go fi], .shown
.. in bold. (b) Utilities
for 8 distinct two-step plans. (c) Utilities for four undominated two-step plans. (d) Utility
function for optimal eight-step plans.
There are eight distinct depth-2 plans in all, and their utilities are shown in Figure 17.8(b).
Notice that four of the plans, shown as dashed lines, are suboptimal across the entire belief
DOMINATED PLAN space—we say these plans are dominated, and they need not be considered further. There
are four undominated plans, each of which is optimal in a specific region, as shown in Fig-
Chapter 17. Making Complex Decisions
25.4. PARTIALLY OBSERVABLE MDPS 575
3 3
Utility
1.5 [Stay] 1.5 3 3
[Go] 2.5 2.5
1 1
2 2
0.5 0.5
Utility
Utility
1.5 [Stay] 1.5
0 0 [Go]
0 0.2 0.4 0.6 0.8 1 0 0.2 0.4 0.6 0.8 11 1
Chapter
(a) 17. Making Complex Decisions (b) 0 0
0 0.2 0.4 0.6 0.8 1 0 0.2 0.4
Four of them (dashed lines) are suboptimal for the whole belief space Probability of state 1 Probability
3 7.5
We call
3 them dominated (they can
(a) be ignored) (b)
2.5 7
2.5 3 7.5
2 2 6.5
2.5 7
Utility
Utility
Utility
[Stay]
1.5 1.5 6 2 6.5
[Go]
Utility
Utility
1 1 5.5 1.5 6
0.5 1 5.5
0.5 5
0 0.5 5
0.2 0.4 0.6 0 0.8 1 0 0.2 0.4 0.6 0.8 4.5 1
Probability of state 1 0 0.2 0.4 0.6 0.8
Probability of1state 1 0 0.2 0.4 0.6 0.8 10 4.5
0 0.2 0.4 0.6 0.8 1 0 0.2 0.4
(a) Probability of state 1 (b) Probability of state 1
There are four undominated plans, each optimal in their region Probability of state 1 Probability
(c) 7.5 (d) (c) (d)
7
Figure 17.8 (a) Utility of two one-step plans as a function of the initial belief state b(1)
Figure 17.8 (a) Utility of two one-step plans as a function of the initia
for the two-state world, for the two-state world, with the corresponding utility function shown in
6.5 with the corresponding utility function shown in bold. (b) Utilities
for 8 distinct two-step plans. (c) Utilities for four undominated two-step
Utility
for 8 distinct two-step6 plans. (c) Utilities for four undominated two-step plans. (d) Utility
function for optimal eight-step plans.
function for optimal eight-step
5.5 plans.
5 There are eight distinct depth-2 plans in all, and their utilities are show
There are eight distinct 4.5 depth-2 plans in all, and their utilities are shown in Figure 17.8(b).
Notice that four of the plans, shown as dashed lines, are suboptimal acr
0.2 0.4 0.6 0.8 1 0 0.2 0.4 0.6 0.8 1 space—we say these plans are dominated, and they need not be consid
Notice that
Probability of state 1
four of the plans, shown as dashed
Probability of state 1
lines, are suboptimal across the
DOMINATED PLAN
entire belief
are four undominated plans, each of which is optimal in a specific regio
(c)space—we say these plans are dominated, and they need not be considered further. There
D PLAN
(d) ure 17.8(c). The regions partition the belief-state space.
are four undominated plans, Repeat
Idea: each offor whichdepth is optimal
3 and soinon. a specific region, as shown inWe Fig- repeat the process for depth 3, and so on. In general, let p be a
17.8 (a) Utility of two one-step plans as a function of the initial belief state b(1)
ure 17.8(c). The regions partition the belief-state
wo-state world, with the corresponding utility function shown in bold. (b) Utilities space. plan whose initial action is a and whose depth-d − 1 subplan for percept
tinct two-step plans. We(c)repeat
Utilitiesthefor Theorem
process
four 25.4.11
for depth
undominated 3, and
two-step (POMDP
so (d)
plans. InPlan
[Link] Utility).
general, let p beLet p be aconditional
a depth-d depth-d conditional ! plan whose #
" "
for optimalplan
eight-step plans. initial action is a and whose depth-d
whose initial action is a and whose depth-d − 1 subplan for percept e is p.e; then− 1-subplan for percept e is αp.e,
p (s) then
= R(s) + γ P (s !
| s, a) P (e | s !
)αp.e (s !
) .
! X # X s! e
" α (s)" ′
s′ ) recursion
· αp.e (s′naturally
ght distinct depth-2 = R(s)17.8(b).
+ γ( ! (s | s,a)(
P P (e |This ))) gives us a value iteration algorithm, which is sket
αpplans
(s) = in R(s)
all, and+their
γ utilities
P (sare! shown
| s,pa) in Figure P (e | s! )αp.e (s ) . (17.13)
The structure of the algorithm and its error analysis are similar to those of
four of the plans, shown as dashed lines, are suboptimal across the entire beliefs ′ e
s! e
ation algorithm in Figure 17.4 on page 653; the main difference is that in
ay these plans are dominated, and they need not be considered further. There
This recursion
ominated plans, each of which naturally
This gives
isoptimal in aus
recursiona value
specific iteration
naturally
region, algorithm,
as gives
shown us which
a value
in Fig- is sketched
iteration in Figure
algorithm, [Link] for each state, POMDP-VALUE -I TERATION maint
one utility
The regionsThe structure
partition of the algorithm
the belief-state space. and its error analysis are similar to those of the basic value iter-
peat the process
ationforalgorithm
depth 3, and in so on. In17.4
Figure general,
on let p be653;
page a depth-d conditional
the main difference is that instead of computing
nitial action is
one a and whose depth-d − 1 subplan : for percept e is p.e; then
! utility number for each state, # POMDP-VALUE -I TERATION maintains a collection of
878 2025-05-14
" "
= R(s) + γ P (s! | s, a) P (e | s! )αp.e (s! ) . (17.13)
s!
Ae Value Iteration Algorithm for POMDPs
on naturally gives us a value iteration algorithm, which is sketched in Figure 17.9.
Definition
e of the algorithm and its error analysis 25.4.12.
are similar to thoseThe POMDP
of the value
basic value iter- iteration algorithm for POMDPs is given by recursively
hm in Figure 17.4 on page 653;updating
the main difference is that instead of computing
umber for each state, POMDP-VALUE -I TERATION maintains a collection of
X X
αp (s) = R(s) + γ( P (s′ | s,a)( P (e | s′ ) · αp.e (s′ )))
s′ e
576 CHAPTER 25. MAKING COMPLEX DECISIONS
: 879 2025-05-14
: 880 2025-05-14
Figure 17.10 The generic structure of a dynamic decision network. Variables with known
values are shaded. The current time is t and the agent must decide what to do—that is, choose
a value for At . The network has been unrolled into the future for three steps and represents
future rewards, as well as the utility of the state at the look-ahead horizon.
25.5. ONLINE AGENTS WITH POMDPS 577
: 881 2025-05-14
At in P(Xt | E1:t)
Et+1 ...
... ... ... ...
Et+2 ...
... ... ...
Et+3 ...
... ... ...
U(Xt+3) ...
10 4 6 3
Figure 17.11 Part of the look-ahead solution of the DDN in Figure 17.10. Each decision
circle b chance nodes
= (the environment decides)
will be taken in the belief state indicated.
triangle =
b belief state (each action decision is taken there)
E and rewards R are all unknown. Notice that the network includes nodes for the rewards
for Xt+1 : and Xt+2 , but the utility for Xt+3
882 2025-05-14
. This is because the agent must maximize the
(discounted) sum of all future rewards, and U (Xt+3 ) represents the reward for Xt+3 and all
subsequent rewards. As in Chapter 5, we assume that U is available only in some approximate
Designing Online Agents for POMDPs
form: if exact utility values were available, look-ahead beyond depth 1 would be unnecessary.
Figure 17.11 shows part of the search tree corresponding to the three-step look-ahead
DDN in Figure 17.10. Each of the triangular nodes is a belief state in which the agent makes
a decision At+i for i = 0, 1, 2, . . .. The round (chance) nodes correspond to choices by the
environment, namely, what evidence Et+i arrives. Notice that there are no chance nodes
corresponding to the action outcomes; this is because the belief-state update for an action is
deterministic regardless of the actual outcome.
The belief state at each triangular node can be computed by applying a filtering al-
gorithm to the sequence of percepts and actions leading to it. In this way, the algorithm
takes into account the fact that, for decision At+i , the agent will have available percepts
E , . . . , E , even though at time t it does not know what those percepts will be. In this
578 CHAPTER 25. MAKING COMPLEX DECISIONS
Section 17.4. Partially Observable MDPs 665
At in P(Xt | E1:t)
Et+1 ...
... ... ... ...
Et+2 ...
... ... ...
Et+3 ...
... ... ...
U(Xt+3) ...
10 4 6 3
Figure 17.11 Part of the look-ahead solution of the DDN in Figure 17.10. Each decision
will be taken in the belief state indicated.
Belief state at triangle computed by filtering with actions/percepts leading to it
E and rewards R are all unknown. Notice that the network includes nodes for the rewards
for Xt+1 and Xt+2 , but the utility for Xt+3 . This is because the agent must maximize the
for decision At+i will use sum
(discounted) percepts and U (X ) represents the reward (even
Et+1:t+i
of all future rewards, for X and if
all values at time t unknown)
t+3 t+3
subsequent rewards. As in Chapter 5, we assume that U is available only in some approximate
form: if exact utility values were available, look-ahead beyond depth 1 would be unnecessary.
thus a POMDP agent automatically takes into account the value of information and
Figure 17.11 shows part of the search tree corresponding to the three-step look-ahead
DDN in Figure 17.10. Each of the triangular nodes is a belief state in which the agent makes
executes information gathering actions where appropriate.
a decision At+i for i = 0, 1, 2, . . .. The round (chance) nodes correspond to choices by the
environment, namely, what evidence Et+i arrives. Notice that there are no chance nodes
corresponding to the action outcomes; this is because the belief-state update for an action is
d d
Observation: Time complexity for exhaustive search up to depth d is O(|A| · |E| )(|A| =
b
deterministic regardless of the actual outcome.
The belief state at each triangular node can be computed by applying a filtering al-
number of actions, |E| =
b number of percepts)
gorithm to the sequence of percepts and actions leading to it. In this way, the algorithm
takes into account the fact that, for decision At+i , the agent will have available percepts
Et+1 , . . . , Et+i , even though at time t it does not know what those percepts will be. In this
way, a decision-theoretic agent automatically takes into account the value of information and
|E|d−1
Upshot: Much better than POMDP value iteration with O(|A|
will execute information-gathering actions where appropriate.
A decision can be extracted from the search tree by backing up the utility values from
).
the leaves, taking an average at the chance nodes and taking the maximum at the decision
Empirically: For problems in which the discount factor γ is not too close to 1, a shallow
nodes. This is similar to the E XPECTIMINIMAX algorithm for game trees with chance nodes,
except that (1) there can also be rewards at non-leaf states and (2) the decision nodes corre-
: 883 2025-05-14
Summary
Decision theoretic agents for sequential environments
: 884 2025-05-14
Part VI
Machine Learning
579
581
This part introduces the foundations of machine learning methods in AI. We discuss the
problem learning from observations in general, study inference-based techniques, and then go into
elementary statistical methods for learning.
The current hype topics of deep learning, reinforcement learning, and large language models
are only very superficially covered, leaving them to specialized courses.
582
Chapter 26
In this chapter we introduce the concepts, methods, and limitations of inductive learning, i.e.
learning from a set of given examples.
Outline
Learning agents
Inductive learning
Decision tree learning
Measuring learning performance
: 885 2025-05-14
: 886 2025-05-14
583
584 CHAPTER 26. LEARNING FROM OBSERVATIONS
: 887 2025-05-14
Definition 26.1.4. Learning element may use knowledge already acquired in the performance
element.
Definition 26.1.5. Learning may require experimentation actions an agent might not nor-
mally consider such as dropping rocks from the Tower of Pisa.
26.2. SUPERVISED LEARNING 585
: 888 2025-05-14
Ways of Learning
Supervised learning: There’s an unknown function f : A → B called the target function. We
do know a set of pairs T := {⟨ai , f (ai )⟩} of examples. The goal is to find a hypothesis
h ∈ H ⊆ A → B based on T , that is “approximately” equal to f . (Most of the techniques
we will consider)
Unsupervised learning: Given a set of data A, find a pattern in the data; i.e. a function
f : A → B for some predetermined B. (Primarily clustering /dimensionality reduction)
Reinforcement learning: The agent receives a reward for each action performed. T he goal
is to iteratively adapt the action function to maximize the total reward. (Useful in e.g. game
play)
: 889 2025-05-14
a set of examples T ⊆ A × B called the training set, such that for every a ∈ A, there is at
most one b ∈ B with ⟨a, b⟩ ∈ T , (⇒ T is a function on some subset of A)
We assume there is an unknown function f : A → B called the target function with T ⊆ f .
Definition 26.2.2. Inductive learning algorithms solve inductive learning problems by finding a
hypothesis h ∈ H such that h ∼ f (for some notion of similarity).
Definition 26.2.3. We call a supervised learning problem with target function A → B a classifi-
cation problem if B is finite, and call the members of B classes.
We call it a regression problem if B = R.
: 890 2025-05-14
Training Set
Linear Hypothesis
partially, approximatively
consistent
Quadratic Hypothesis
partially consistent
Degree-4 Hypothesis
consistent
High-degree Hypothesis
consistent
26.3. LEARNING DECISION TREES 587
: 891 2025-05-14
Problem: We do not always know whether a given learning problem is realizable, unless we
have prior knowledge. (depending on the hypothesis space)
Solution: Make H large, e.g. the class of all Turing machines.
Tradeoff: The computational complexity of the supervised learning problem is tied to the size
of the hypothesis space. E.g. consistency is not even decidable for general Turing machines.
Much of the research in machine learning has concentrated on simple hypothesis spaces.
Preview: We will concentrate on propositional logic and related languages first.
: 892 2025-05-14
Intuition: This only works, if the training set is “representative” for the underlying process.
Idea: We think of examples (seen and unseen) as a sequence, and express the “representa-
tiveness” as a stationarity assumption for the probability distribution.
Method: Each example before we see it is a random variable Ej , the observed value
ej = (xj ,yj ) samples its distribution.
Example 26.2.8. A sequence of die tosses is IID. (fair or loaded does not matter)
Stationarity Assumption: We assume that the set E of examples is IID in the future.
: 893 2025-05-14
Attribute-based Representations
Definition 26.3.1. In attribute-based representations, examples are described by
attributes: (simple) functions on input samples, (think pre classifiers on examples)
their values, and (classify by attributes)
classifications. (Boolean, discrete, continuous, etc.)
Example 26.3.2 (In a Restaurant). Situations where I will/won’t wait for a table:
Attributes Target
Example Alt Bar F ri Hun P at P rice Rain Res T ype Est WillWait
X1 T F F T Some $$$ F T French 0–10 T
X2 T F F T Full $ F F Thai 30–60 F
X3 F T F F Some $ F F Burger 0–10 T
X4 T F T T Full $ F F Thai 10–30 T
X5 T F T F Full $$$ F T French >60 F
X6 F T F T Some $$ T T Italian 0–10 T
X7 F T F F None $ T F Burger 0–10 F
X8 F F F T Some $$ T T Thai 0–10 T
X9 F T T F Full $ T F Burger >60 F
X 10 T T T T Full $$$ F T Italian 10–30 F
X 11 F F F F None $ F F Thai 0–10 F
X 12 T T T T Full $ F F Burger 30–60 T
Definition 26.3.3. For a boolean classification we say that an example is positive (T) or
negative (F) depending on its class.
: 894 2025-05-14
Decision Trees
Decision trees are one possible representation for hypotheses.
Example 26.3.4 (Restaurant continued). Here is the “true” tree for deciding whether to
wait:
26.3. LEARNING DECISION TREES 589
: 895 2025-05-14
We evaluate the tree by going down the tree from the top, and always take the branch whose
attribute matches the situation; we will eventually end up with a Boolean value; the result. Using
the attribute values from X3 in Example 26.3.2 to descend through the tree in Example 26.3.4 we
indeed end up with the result “true”. Note that
1. some of the original set of attributes X3 are irrelevant.
2. the training set in Example 26.3.2 is realizable – i.e. the target is definable in hypothesis class
of decision trees.
Definition 26.3.6. We call an attribute together with a set of attribute values (an inner
node) with outgoing edge label an attribute test.
the target function is a function A1 × . . . × An → C, where Ai are the domains of the
attributes and C is the set of classifications.
: 896 2025-05-14
Expressiveness
Decision trees can express any function of the input attributes ⇒ H = A1 × . . . × An
Example 26.3.7. For Boolean functions, a path from the root to a leaf corresponds to a
row in a truth table:
: 897 2025-05-14
: 898 2025-05-14
Choosing an Attribute
Idea: A good attribute splits the examples into subsets that are (ideally) “all positive” or
“all negative”.
Example 26.3.9.
Attribute “Patrons?” is a better choice, it gives gives information about the classification.
Can we make this more formal? ; Use information theory! (up next)
: 899 2025-05-14
Information Entropy
Intuition: Information answers questions – the less I know initially, the more Information is
26.4. USING INFORMATION THEORY 591
contained in an answer.
Definition 26.4.1. Let ⟨p1 , . . ., pn ⟩ the distribution of a random variable P . The information
(also called entropy) of P is
n
X
I(⟨p1 , . . ., pn ⟩):= −pi · log2 (pi )
i=1
: 900 2025-05-14
: 901 2025-05-14
Example 26.4.7. If the classification C is Boolean and we have p positive and n negative
examples, the information gain is
p n X pa + n a pa na
Gain(A) = I(⟨ , ⟩) − I(⟨ , ⟩)
p+n p+n a
p+n pa + n a pa + n a
: 902 2025-05-14
Result: Substantially simpler than “true” tree – a more complex hypothesis isn’t justified by
small amount of data.
: 903 2025-05-14
Performance measurement
Question: How do we know that h≊f ? (Hume’s Problem of Induction)
1. Use theorems of computational/statistical learning theory.
26.5. EVALUATING AND CHOOSING THE BEST HYPOTHESIS 593
2. Try h on a new test set of examples. (use same distribution over example space as
training set)
Definition 26.5.1. The learning curve =
b percentage correct on test set as a function of
training set size.
: 904 2025-05-14
: 905 2025-05-14
(limited) training set rather than the underlying relationship. Underfitting occurs when h
cannot capture the underlying trend of the data.
Qualitatively: Overfitting increases with the size of hypothesis space and the number of
attributes, but decreases with number of examples.
: 906 2025-05-14
Definition 26.5.5. For decision tree pruning repeat the following on a learned decision tree:
Find a terminal test node n (only result leaves as children)
If test is irrelevant, i.e. has low information gain, prune it by replacing n by with a leaf
node.
Question: How big should the information gain be to split (; keep) a node?
Idea: Use a statistical significance test.
Definition 26.5.6. A result has statistical significance, if the probability they could arise
from the null hypothesis (i.e. the assumption that there is no underlying pattern) is very low
(usually 5%).
: 907 2025-05-14
For an attribute A with d values, compare the actual numbers pk and nk in each subset sk
with the expected numbers (expected if A is irrelevant)
pbk = p · pkp+n
+nk
bk = n · pkp+n
and n +nk
.
d
X 2 2
(pk − pbk ) (nk − n
bk )
∆= +
pbk bk
n
k=1
Lemma 26.5.7 (Neyman-Pearson). Under the null hypothesis, the value of ∆ is distributed
according to the χ2 distribution with d − 1 degrees of freedom. [NeyPea:pmtsh33]
Definition 26.5.8. Decision tree pruning with Pearson’s χ2 with d − 1 degrees of freedom
for ∆ is called χ2 pruning. (χ2 values from stats library.)
26.5. EVALUATING AND CHOOSING THE BEST HYPOTHESIS 595
Example 26.5.9. The type attribute has four values, so three degrees of freedom, so
∆ = 7.82 would reject the null hypothesis at the 5% level.
: 908 2025-05-14
Definition 26.5.10. Given an inductive learning problem with a set of examples T ⊆ AB,
we define the error rate of a hypothesis h ∈ H as the fraction of errors:
Caveat: A low error rate on the training set does not mean that a hypothesis generalizes
well.
: 909 2025-05-14
: 910 2025-05-14
Model Selection
Definition 26.5.14. The model selection problem is to determine – given data – a good
596 CHAPTER 26. LEARNING FROM OBSERVATIONS
hypothesis space.
Example 26.5.15. What is the best polynomial degree to fit the data
: 911 2025-05-14
: 912 2025-05-14
60
Validation Set Error
Training Set Error
50
40
Error rate
30
20
10
0
1 2 3 4 5 6 7 8 9 10
Tree size
Stops when training set error rate converges, choose optimal tree for validation curve.(here a
tree with 7 nodes)
: 913 2025-05-14
So: Machine learning should maximize “utility”. (not only minimize error rates)
machine learning traditionally deals with utilities in form of “loss functions”.
Definition 26.5.20. The loss function L is defined by setting L(x, y, yb) to be the amount
of utility lost by prediction h(x) = yb instead of f (x) = y. If L is independent of x, we often
use L(y, yb).
Example 26.5.21. L(spam, ham) = 1, while L(ham, spam) = 10.
: 914 2025-05-14
Generalization Loss
Note: L(y, y) = 0. (no loss if you are exactly correct)
Definition 26.5.22 (Popular general loss functions).
absolute value loss L1 (y, yb):=|y − yb| small errors are good
2
squared error loss L2 (y, yb):=(y − yb) ditto, but differentiable
0/1 loss L0/1 (y, yb):=0, if y = yb, else 1 error rate
598 CHAPTER 26. LEARNING FROM OBSERVATIONS
Idea: Maximize expected utility by choosing hypothesis h that minimizes expected loss over
all (x,y) ∈ f .
Definition 26.5.23. Let E be the set of all possible examples and P(X, Y ) the prior proba-
bility distribution over its components, then the expected generalization loss for a hypothesis
h with respect to a loss function L is
X
GenLossL (h):= L(y, h(x)) · P (x, y)
(x,y)∈E
: 915 2025-05-14
Empirical Loss
Problem: P(X, Y ) is unknown ; learner can only estimate generalization loss:
Definition 26.5.24. Let L be a loss function and E a set of examples with #(E) = N ,
then we call
1 X
EmpLossL,E (h):= ( L(y, h(x)))
N
(x,y)∈E
: 916 2025-05-14
Regularization
Idea: Directly use empirical loss to solve model selection. (finding a good H)
Minimize the weighted sum of empirical loss and hypothesis complexity. (to avoid
overfitting).
: 917 2025-05-14
Definition 26.5.28. Let h ∈ H be a hypothesis and E a set of examples, then the description
length of (h,E) is computed as follows:
1. encode the hypothesis as a Turing machine program, count bits.
2. count data bits:
correctly predicted example ; 0b
incorrectly predicted example ; according to size of error.
The minimum description length or MDL hypothesis minimizes the total number of bits
required.
This works well in the limit, but for smaller problems there is a difficulty in that the choice
of encoding for the program affects the outcome.
e.g., how best to encode a decision tree as a bit string?
: 918 2025-05-14
In recent years there has been more emphasis on large-scale learning. (millions of examples)
Generalization error is dominated by limits of computation
there is enough data and a rich enough model that we could find an h that is very
close to the true f ,
but the computation to find it is too complex, so we settle for a sub-optimal approxi-
mation.
Hardware advances (GPU farms, Amazon EC2, Google Data Centers, . . . ) help.
: 919 2025-05-14
: 920 2025-05-14
PAC Learning
Basic idea of Computational Learning Theory:
Any hypothesis h that is seriously wrong will almost certainly be “found out” with high
probability after a small number of examples, because it will make an incorrect prediction.
Thus, if h is consistent with a sufficiently large set of training examples is unlikely to be
seriously wrong.
; h is probably approximately correct.
Definition 26.6.1. Any learning algorithm that returns hypotheses that are probably ap-
proximately correct is called a PAC learning algorithm.
Derive performance bounds for PAC learning algorithms in general, using the
26.6. COMPUTATIONAL LEARNING THEORY 601
Stationarity Assumption (again): We assume that the set E of possible examples is IID
; we have a fixed distribution P(E) = P(X, Y ) on examples.
Simplifying Assumptions: f is a function (deterministic) and f ∈ H.
: 921 2025-05-14
PAC Learning
Start with PAC theorems for Boolean functions, for which L0/1 is appropriate.
Definition 26.6.2. The error rate error(h) of a hypothesis h is the probability that h
misclassifies a new example.
X
error(h):=GenLossL0/1 (h) = L0/1 (y, h(x)) · P (x, y)
(x,y)∈E
: 922 2025-05-14
Sample Complexity
Let’s compute the probability that hb ∈ Hb is consistent with the first N examples.
We know error(hb ) > ϵ
N
; P (hb agrees with N examples) ≤ (1 − ϵ) . (independence)
N N
; P (Hb contains consistent hyp.)≤|Hb | · (1 − ϵ) ≤|H| · (1 − ϵ) . (Hb ⊆ H)
; to bound this by a small δ, show the algorithm N ≥ 1ϵ · (log2 ( 1δ ) + log2 (|H|)) examples.
Definition 26.6.4. The number of required examples as a function of ϵ and δ is called the
sample complexity of H.
n
Example 26.6.5. If H is the set of n-ary Boolean functions, then |H| = 22 .
n
; sample complexity grows with O(log2 (22 )) = O(2n ).
There are 2 possible examples,
n
; PAC learning for Boolean functions needs to see (nearly) all examples.
: 923 2025-05-14
H contains enough hypotheses to classify any given set of examples in all possible ways.
In particular, for any set of N examples, the set of hypotheses consistent with those
examples contains equal numbers of hypotheses that predict xN +1 to be positive and
hypotheses that predict xN +1 to be negative.
: 924 2025-05-14
Remark: Like decision trees, but restricted branching, but more complex tests.
Example 26.6.7 (A decision list for the Restaurant Problem).
No No
P atrons(x, Some) P atrons(x, F ull) ∧ F ri/Sat(x) No
Yes Yes
Yes Yes
Lemma 26.6.8. Given arbitrary size conditions, decision lists can represent arbitrary Boolean
functions.
This directly defeats our purpose of finding a “learnable subset” of H.
: 925 2025-05-14
Definition 26.6.12. We denote the set of k−DL decision lists with at most n Boolean
attributes with k−DL(n). The set of conjunctions of at most k literals over n attributes is
written as Conj(k, n).
Decision lists are constructed of optional yes/no tests, so there are at most 3|Conj(k,n)| distinct
sets of component tests. Each of these sets of tests can be in any order, so |k−DL(n)| ≤
3|Conj(k,n)| · |Conj(k, n)|!
: 926 2025-05-14
Plug this into the equation for the sample complexity: N ≥ 1ϵ · (log2 ( 1δ ) + log2 (|H|)) to
obtain
1 1
N ≥ · (log2 ( ) + log2 (O(nk log2 (nk ))))
ϵ δ
Intuitively: Any algorithm that returns a consistent decision list will PAC learn a k−DL
function in a reasonable number of examples, for small k.
: 927 2025-05-14
1. find test that agrees exactly with some subset E of the training set,
2. add it to the decision list under construction and removes E,
3. construct the remainder of the DL using just the remaining examples,
until there are no examples left.
: 928 2025-05-14
0.8
Decision tree
0.7 Decision list
0.6
0.5
0.4
0 20 40 60 80 100
Training set size
: 929 2025-05-14
Definition 26.7.4. Given a set of examples E ⊆ R×R, the task of finding hw that best fits
E is called linear regression.
Example 26.7.5.
1000
Examples of house price vs. square 900
House price in $1000
: 930 2025-05-14
N
X N
X N
X
2 2
Loss(hw ) = L2 (yj , hw (xj )) = (yj − hw (xj )) = (yj − (w1 xj + w0 ))
j=1 j=1 j=1
Remark: Closed-form solutions only exist for linear regression, for other (differentiable)
hypothesis spaces use gradient descent methods for adjusting/learning weights.
: 931 2025-05-14
Note: it is convex. w0
w1
Observation 26.7.7. The squared error loss function is convex for any linear regression
problem ; there are no local minima.
: 932 2025-05-14
606 CHAPTER 26. LEARNING FROM OBSERVATIONS
Definition 26.7.8. The gradient descent algorithm for finding a minimum of a continuous
function F is hill climbing in the direction of the steepest descent, which can be computed
by the partial derivatives of F .
function gradient−descent(F ,w,α) returns a local minimum of F
inputs: a differentiable function F and initial weights w.
loop until w converges do
for each wi do
∂
wi ←− wi − α ∂w i
F (w)
end for
end loop
The parameter α is called the learning rate. It can be a fixed constant or it can decay as
learning proceeds.
: 933 2025-05-14
: 934 2025-05-14
These updates constitute the batch gradient descent learning rule for univariate linear regres-
sion.
26.7. REGRESSION AND CLASSIFICATION WITH LINEAR MODELS 607
Convergence to the unique global loss minimum is guaranteed (as long as we pick α small
enough) but may be very slow.
Doing batch gradient descent on random subsets of the examples of fixed batch size n is
called stochastic gradient descent (SGD). (More computationally efficient than updating for
every example)
: 935 2025-05-14
Gradient descent will reach the (unique) minimum of the loss function; the update equation
for each weight wi is X
wi ←− wi − α( xj,i (yj − hw (⃗xj )))
j
: 936 2025-05-14
: 937 2025-05-14
: 938 2025-05-14
5
earthquakes, black: underground 4.5
explosions 4
3.5
Also: hw∗ as a decision boundary 3
2.5
x2 = 17x1 − 4.9. 4.5 5 5.5 6 6.5 7
x1
Definition 26.7.14. A decision boundary is a line (or a surface, in higher dimensions) that
separates two classes of points. A linear decision boundary is called a linear separator and
data that admits one are called linearly separable.
Example 26.7.15 (Nuclear Tests continued). The linear separator for Example 26.7.13is
defined by −4.9 + 1.7x1 − x2 = 0, explosions are characterized by −4.9 + 1.7x1 − x2 > 0,
earthquakes by −4.9 + 1.7x1 − x2 < 0.
Useful Trick: If we introduce dummy coordinate x0 = 1, then we can write the classification
hypothesis as hw (x) = 1 if w·x > 0 and 0 otherwise.
: 939 2025-05-14
threshold function.
Problem: T is not differentiable and ∂T
∂z = 0 where defined ;
∂T
No closed-form solutions by setting ∂z = 0 and solving.
Gradient-descent methods in weight-space do not work either.
We can learn weights by iterating over the following rule:
Definition [Link] an example (x,y), the perceptron learning rule is
wi ←− wi + α · (y − hw (x)) · xi
: 940 2025-05-14
Proportion correct
Proportion correct
Theorem 26.7.18. Finding the minimal-error hypothesis is NP-hard, but possible with
learning rate decay.
: 941 2025-05-14
So far: Passing the output of a linear function through a threshold function T yields a linear
classifier.
Problem: The hard nature of T brings problems:
T is not differentiable nor continuous ; learning via perceptron rule becomes unpre-
dictable.
T is “overly precise” near the boundary ⇝ need more graded judgments.
Idea: Soften the threshold, approximate it with a differentiable function.
1
We use the standard logistic function l(x) = 1+e−x
1
So we have hw (x) = l(w·x) = 1+e−(w·x)
: 942 2025-05-14
Logistic Regression
∂ ∂ 2
L2 (w) = ((y − hw (x)) )
∂wi ∂wi
∂
= 2 · hw (x) · (y − hw (x))
∂wi
∂
= −2 · hw (x) · l′ (w·x) · (w·x)
∂wi
= −2 · hw (x) · l′ (w·x) · xi
: 943 2025-05-14
The derivative of the logistic function satisfies l′ (z) = l(z)(1 − l(z)), thus
Definition 26.7.21. The rule for logistic update (weight update for minimizing the loss) is
: 944 2025-05-14
1 1
0.8 0.8
0.6 0.6
0.4 0.4
0.2 0.2
0 0
0 0.2 0.4 0.6 0.8 1 0 0.2 0.4 0.6 0.8 1
: 945 2025-05-14
Definition 26.8.3. Support-vector machines (SVMs; also support-vector networks) are supervised
learning models for classification and regression.
SVMs construct a maximum margin separator by prioritizing critical examples (support vec-
tors).
SVMs are still one of the most popular approaches for “off-the-shelf” supervised learning.
Setting:
We have a training set E = {⟨x1 , y 1 ⟩, . . ., ⟨xn , y n ⟩} where xi ∈ Rp and y i ∈ { − 1, 1}
(instead of {1, 0})
The goal is to find a hyperplane in Rp that maximally separates the two classes (i.e.
y i = −1 from y i = 1)
Remember A hyperplane can be represented as the set {x | (w·x) + b = 0} for some vector w
and scalar b. (w is orthogonal to the plane, b determines the offset from the origin)
: 946 2025-05-14
X 1 X
Theorem 26.8.4 (SVM equation). Let α = argmax ( αj − ( αj αk y j y k (xj ·xk ))) under
j
α 2
P j,k
the constraints αj ≥ 0 and j αj y j = 0. P
The maximum margin separator is given by w = j αj xj and b = w·xi − y i for any xi where
αi ̸= 0.
Proof sketch: By the duality principle for optimization problems
: 947 2025-05-14
Important Properties:
The weights αj associated with each data point are zero except at the support vectors (the
points closest to the separator),
The expression is convex ; the single global maximum can found efficiently,
26.8. SUPPORT VECTOR MACHINES 613
: 948 2025-05-14
1.5
0.5
x2
-0.5
-1
-1.5
-1.5 -1 -0.5 0 0.5 1 1.5
x1
0
-1
-2 2.5
-0.5 -3 2
0 1.5
-1 0.5
1 1 x22
1.5 0.5
-1.5 x21 2
-1.5 -1 -0.5 0 0.5 1 1.5
x1
614 CHAPTER 26. LEARNING FROM OBSERVATIONS
: 950 2025-05-14
: 951 2025-05-14
Multilayer perceptrons
Applications of neural networks
: 952 2025-05-14
Brains
Axiom 26.9.1 (Neuroscience Hypothesis). Mental activity consists consists primarily of
electrochemical activity in networks of brain cells called neurons.
26.9. ARTIFICIAL NEURAL NETWORKS 615
: 953 2025-05-14
One approach to artificial intelligence is to model and simulate brains. (and hope that AI
comes along naturally)
Definition 26.9.3. The AI subfield of neural networks (also called connectionism, parallel
distributed processing, and neural computation) studies computing systems inspired by the
biological neural networks that constitute brains.
Neural networks are attractive computational devices, since they perform important AI tasks
– most importantly learning and distributed, noise-tolerant computation – naturally and effi-
ciently.
: 954 2025-05-14
Bias Weight
a0 = 1 aj = g(inj)
X w0,j
ini = wj,i aj g
wi,j inj
j
X
ai
Σ aj
If g is a threshold function, we call the unit a perceptron unit, if g is a logistic function a sigmoid
perceptron unit.
A McCulloch-Pitts network is a neural network with McCulloch-Pitts units.
: 955 2025-05-14
Theorem 26.9.6 (McCulloch and Pitts). Every Boolean function can be implemented as
McCulloch-Pitts networks.
Proof: by construction
P
1. Recall that ai ←− g( j wj,i aj ). Let g(r) = 1 iff r > 0, else 0.
2. As for linear regression we use a0 = 1 ; w0,i as a bias weight (or intercept) (determines
the threshold)
w0 = −1 w0 = −0.5 w0 = 0.5
w1 = 1 w1 = 1 w1 = −1
w2 = 1 w2 = 1
3. AND OR NOT
: 956 2025-05-14
: 957 2025-05-14
26.9. ARTIFICIAL NEURAL NETWORKS 617
Recurrent neural networks follow largely the same principles as feed-forward networks, so we will
not go into details here.
: 958 2025-05-14
Single-layer Perceptrons
Definition 26.9.10. A perceptron network is a feed-forward network of perceptron units. A
single layer perceptron network is called a perceptron.
Example 26.9.11.
1
0.8
0.6
0.4
0.2
-2-4
0 20x
Input w Output -2 0
x1
2 4 6 10 8
6 4 2
i,j
Layer Layer
: 959 2025-05-14
a5 = g(w3,5 · a3 + w4,5 · a4 )
= g(w3,5 · g(w1,3 · a1 + w2,3 a2 ) + w4,5 · g(w1,4 · a1 + w2,4 a2 ))
: 960 2025-05-14
Expressiveness of Perceptrons
Consider a perceptron with g = step function (Rosenblatt, 1957, 1960)
Can represent AND, OR, NOT, majority, etc., but not XOR (and thus no adders)
Represents a linear separator in input space:
X
wj xj > 0 or W, x· > 0
j
x1 x1 x1
1 1 1
0 0 0
0 1 x2 0 1 x2 0 1 x2
(a) x1 and x2 (b) x1 or x2 (c) x1 xor x2
Minsky & Papert (1969) pricked the first neural network balloon!
: 961 2025-05-14
Perceptron Learning
For learning, we update the weights using gradient descent based on the generalization loss
function.
Let e.g. L(w) = (y − hw (x))2 (the squared error loss).
We compute the gradient:
26.9. ARTIFICIAL NEURAL NETWORKS 619
Xn
∂L(w) ∂(y − hw (x)) ∂
= 2 · (yk − hw (x)k ) · = 2 · (yk − hw (x)k ) · (y − g( wj,k xj ))
∂wj,k ∂wj,k ∂wj,k j=0
; Replacing the constant factor −2 by a learning rate parameter α we get the update rule:
: 962 2025-05-14
0.9 0.9
0.8 0.8
0.7 0.7
: 963 2025-05-14
Multilayer perceptrons
Definition 26.9.13. In multi layer perceptrons (MLPs), layers are usually fully connected;
numbers of hidden units typically chosen by hand.
Output Layer ai
wi,j
Hidden Layer aj
wi,j
Input Layer ak
Definition 26.9.14. Some MLPs have residual connections, i.e. connections that skip layers.
620 CHAPTER 26. LEARNING FROM OBSERVATIONS
: 964 2025-05-14
Expressiveness of MLPs
All continuous functions w/ 2 layers, all functions w/ 3 layers.
: 965 2025-05-14
∂L(w)k ∂ink
= −2 · (yk − hw (x)k ) · g ′ (ink ) · (as before)
∂wi,j | {z } ∂wi,j
=:∆
P k
∂( ℓ wℓ,k aℓ ) ∂aj ∂g(inj )
= −2 · ∆k · = −2 · ∆k · wj,k · = −2 · ∆k · wj,k ·
∂wi,j ∂wi,j ∂wi,j
′
= −2 · ∆k · wj,k · g (inj ) ·ai
| {z }
=:∆j,k
: 966 2025-05-14
26.9. ARTIFICIAL NEURAL NETWORKS 621
Idea: The total “error” of the hidden node j is the sum of all the connected nodes k in the next
layer
Definition [Link] back-propagation rule for hidden nodes of a multilayer perceptron
is ∆j ← g ′ (inj ) · ( wj,i ∆i ) And the update rule for weights in a hidden layer is wk,j ←
i
wk,j + α · ak · ∆j
1. Compute the ∆ values for the output units, using the observed error.
2. Starting with output layer, repeat the following for each layer in the network, until the earliest
hidden layer is reached:
(a) Propagate the ∆ values back to the previous (hidden) layer.
(b) Update the weights between the two layers.
: 967 2025-05-14
: 968 2025-05-14
622 CHAPTER 26. LEARNING FROM OBSERVATIONS
Back-Propagation – Properties
Sum gradient updates for all examples in some “batch” and apply gradient descent.
Learning curve for 100 restaurant examples: finds exact fit.
14
12
: 969 2025-05-14
0.9
0.8
0.7
0.4
0 10 20 30 40 50 60 70 80 90 100
Training set size
Experience shows: MLPs are quite good for complex pattern recognition tasks,
but resulting hypotheses cannot be understood easily.
This makes MLPs ineligible for some tasks, such as credit card and loan approvals, where
law requires clear unbiased criteria.
: 970 2025-05-14
: 971 2025-05-14
Summary
: 972 2025-05-14
: 973 2025-05-14
: 974 2025-05-14
Chapter 27
Statistical Learning
: 975 2025-05-14
625
626 CHAPTER 27. STATISTICAL LEARNING
What kind of bag is it? What flavour will the next candy be?
Note: Every hypothesis is itself a probability distribution over the random variable “flavour”.
: 976 2025-05-14
1 P(h1 | d)
P(h2 | d)
0.8 P(h3 | d)
P(h4 | d)
P(h5 | d)
0.6
0.4
0.2
0
0 2 4 6 8 10
Number of observations in d
Q
if the observations are IID, i.e. P (d | hi ) = j P (dj | hi ) and the hypothesis prior is as
advertised. (e.g. P (d | h3 ) = 0.510 = 0.1%)
The posterior probabilities start with the hypothesis priors, change with data.
: 977 2025-05-14
0.9
0.8
0.7
0.6
0.5
0.4
0 2 4 6 8 10
Number of observations in d
; we compute the expected value of the probability of the next candy being lime over all
hypotheses (i.e. distributions).
; “meta-distribution”
: 978 2025-05-14
where P (d | hi ) is called the likelihood (of the data under each hypothesis) and P (hi )
the hypothesis prior.
Bayesian predictions use a likelihood-weighted average over the hypotheses:
X X
P(X|d) = P(X|d, hi ) · P (hi | d) = P(X|hi ) · P (hi | d)
i i
Observation: No need to pick one best-guess hypothesis for Bayesian predictions! (and
that is all an agent cares about)
: 979 2025-05-14
: 980 2025-05-14
Definition 27.2.1. For maximum a posteriori learning (MAP learning) choose the MAP
hypothesis hMAP that maximizes P (hi | d).
I.e., maximize P (d | hi ) · P (hi ) or (even better) log2 (P (d | hi )) + log2 (P (hi )).
Predictions made according to a MAP hypothesis hMAP are approximately Bayesian to the
extent that P(X|d) ≈ P(X|hMAP ).
Example 27.2.2. In our candy example, hMAP = h5 after three limes in a row
a MAP learner then predicts that candy 4 is lime with probability 1.
compare with Bayesian prediction of 0.8. (see prediction curves above)
As more data arrive, the MAP and Bayesian predictions become closer, because the competi-
tors to the MAP hypothesis become less and less probable.
For deterministic hypotheses, P (d | hi ) is 1 if consistent, 0 otherwise
; MAP = simplest consistent hypothesis. (cf. science)
Remark: Finding MAP hypotheses is often much easier than Bayesian learning, because
it requires solving an optimization problem instead of a large summation (or integration)
problem.
: 981 2025-05-14
Maximizing P (d | hi ) · P (hi ) =
b minimizing −log2 (P (d | hi )) − log2 (P (hi )).
b number of bits to encode data given hypothesis.
−log2 (P (d | hi )) =
b additional bits to encode hypothesis.
−log2 (P (hi )) = (section 26.4)
Indeed if hypothesis predicts the data exactly – e.g. h5 in candy example – then log2 (1) = 0
; preferred hypothesis.
27.3. PARAMETER LEARNING FOR BAYESIAN NETWORKS 629
: 982 2025-05-14
Observation: For large data sets, the prior becomes irrelevant. (we might not trust it
anyways)
Idea: Use this to simplify learning.
Definition 27.2.4. Maximum likelihood learning (ML learning): choose the ML hypothesis
hML maximizing P (d | hi ). (simply get the best fit to the data)
Remark: ML learning = b MAP learning for a uniform prior.(reasonable if all hypotheses are
of the same complexity)
ML learning is the “standard” (non Bayesian) statistical learning method.
: 983 2025-05-14
P (F = cherry)
θ
Flavor
: 984 2025-05-14
630 CHAPTER 27. STATISTICAL LEARNING
N
X
L(d|hθ ) = log2 (P (d | hθ )) = log2 (P (dj | hθ )) = clog2 (θ) + ℓlog2 (1 − θ)
j=1
: 985 2025-05-14
1. Write down an expression for the likelihood of the data as a function of the parameter(s).
2. Write down the derivative of the log likelihood with respect to each parameter.
3. Find the parameter values such that the derivatives are zero
: 986 2025-05-14
P (F = cherry)
θ
Flavor
F P (W = red | F )
cherry θ1
lime θ2
Wrapper
: 987 2025-05-14
Upshot: With complete data, parameters can be learned separately in Bayesian networks.
: 988 2025-05-14
0.8
P(y |x)
4 0.6
3.5
y
3
2.5 0.4
2
1.5
1 1
0.5 0.8 0.2
0 0.6
0 0.2 0.4 y
0.4 0.6 0.2
0.8 0 0
x 1
0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1
x
: 989 2025-05-14
632 CHAPTER 27. STATISTICAL LEARNING
: 990 2025-05-14
: 991 2025-05-14
Chapter 28
Reinforcement Learning
Unsupervised Learning
So far: We have studied “learning from examples”. (functions, logical theories, probability
models)
Now: How can agents learn “what to do” in the absence of labeled examples of “what to
do”. We call this problem unsupervised learning.
Example 28.1.1 (Playing Chess). Learn transition models for own moves and maybe predict
opponent’s moves.
Problem: The agent needs to have some feedback about what is good/bad
; cannot decide “what to do” otherwise. (recall: external performance standard for learning
agents)
Example 28.1.2. The ultimate feedback in chess is whether you win, lose, or draw.
Definition 28.1.3. We call a learning situation where there are no labeled examples unsu-
pervised learning and the feedback involved a reward or reinforcement.
Example 28.1.4. In soccer, there are intermediate reinforcements in the shape of goals,
penalties, . . .
: 992 2025-05-14
633
634 CHAPTER 28. REINFORCEMENT LEARNING
Idea: The task of reinforcement learning is to use observed rewards to come up with an
optimal policy.
In MDPs, the agent has total knowledge about the environment and the reward function, in
reinforcement learning we do not assume this. (; POMDPs+reward-learning)
Example 28.1.6. You play a game without knowing the rules, and at some time the opponent
shouts “you lose!”
: 993 2025-05-14
A utility-based agent learns a utility function on states and uses it to select actions that
maximize the expected outcome utility. (passive learning)
A Q-learning agent learns an action-utility function, or Q-function, giving the expected
utility of taking a given action in a given state. (active learning)
A reflex agent learns a policy that maps directly from states to actions.
: 994 2025-05-14
Passive Learning
Definition 28.2.1 (To keep things simple). Agent uses a state-based representation in a
fully observable environment:
In passive learning, the agent’s policy π is fixed: in state s, it always executes the action
π(s).
Its goal is simply to learn how good the policy is – that is, to learn the utility function
U π (s).
The passive learning task is similar to the policy evaluation task (part of the policy iteration
algorithm) but the agent does not know
the transition model P (s′ | s,a), which specifies the probability of reaching state s′ from
state s after doing action a,
the reward function R(s), which specifies the reward for each state.
: 995 2025-05-14
–1 –1
3 +1 3 0.812 0.868 0.918 +1
+1 +1
1 2 3 4 1 2 3 4
Optimal Policy π
Figure 17.3 The utilities of Utilities,
the states in given
the 4 ×π3 world, calculated
R(s) > 0 with γ = 1 and
– 0.0221 < R(s) < 0
R(s) = − 0.04 for nonterminal states.
The agent executes a set (a) (b)
of trials in the environment using its policy π.
In each trial, Figure 17.2 starts
the agent (a) An
in
Theoptimal
state policy
utility(1,1) and
functionforUexperiences
the
(s) stochastic
allows theaenvironment
sequence
agent with
to selectof R(s)by
state
actions =using theinprinciple of
− 0.04
transitions
the nonterminal states. (b) Optimal
maximum states,
until it reaches one of the terminal expected(4,2)policies
utilityorfromfor four different ranges of R(s).
Chapter 16—that is, choose the action that maximizes the
(4,3).
expected utility of the subsequent state:
Its percepts supply both the current state and! the reward received in that state.
and (3,3) are as shown, every
π ∗ (s) =policy
argmaxis optimal,
P (s# |and
s, a)Uthe(sagent
#
). obtains infinite total reward be- (17.4)
cause it never enters a terminal state. a∈A(s)Surprisingly,
s " it turns out that there are six other optimal
policies
: for various ranges of R(s); 996Exercise 17.5 asks you to find them. 2025-05-14
The next two sections describe algorithms for finding optimal policies.
The careful balancing of risk and reward is a characteristic of MDPs that does not
arise in deterministic searchthisproblems; moreover,
it does not it is fora finite-horizon
characteristic of ormany real-world
Passive Learning by Example
2 Although seems obvious,
time. The proof follows directly
hold
decision problems. For this reason, MDPs have been studied in several fields, on
rewards over from the uniqueness of
policies
the utility
for other
function
ways of combining
including
states, as shown in
Section 17.2.
AI, operations research, economics, and control theory. Dozens of algorithms have been
Exampleproposed
28.2.3. for
Typical trials might
calculating optimallook like this:
policies. In sections 17.2 and 17.3 we describe two of the
most important algorithm families. First,
1. (1, 1)−0.4 ; (1, 2)−0.4 ; (1, 3)−0.4 ; (1, 2)−0.4 ; (1, 3) however, we must complete our investigation of
−0.4 ; (2, 3)−0.4 ; (3, 3)−0.4
utilities
; (4, 3) and policies for sequential decision problems.
+1
2. (1, 1)−0.4 ; (1, 2)−0.4 ; (1, 3)−0.4 ; (2, 3)−0.4 ; (3, 3)−0.4 ; (3, 2)−0.4 ; (3, 3)−0.4
17.1.1 Utilities over time
; (4, 3)+1
In the
3. (1, 1)−0.4 ; MDP example
(2, 1)−0.4 ; (3,in Figure
1)−0.4 17.1,
; (3,the 2)performance
−0.4 ; (4, 2) of−1the. agent was measured by a sum of
rewards for the states visited. This choice of performance measure is not arbitrary, but it is
Definition not28.2.4.
the only The utility for
possibility is defined to function
the utility be the expected
on environment sum ofhistories,
(discounted)
whichrewards
we write as
obtained ifU policy
([s ,
0 1sπ, is
. . followed.
. , s n ]). Our analysis draws on multiattribute utility theory (Section 16.4) and
h
is somewhat technical; the impatient reader " ∞
#
may wish to skip to the next section.
X
FINITE HORIZON The first question toUanswer π
(s):=Eis whether theret ) is a finite horizon or an infinite horizon
γ t R(S
INFINITE HORIZON for decision making. A finite horizon means t=0 that there is a fixed time N after which nothing
matters—the game is over, so to speak. Thus, Uh ([s0 , s1 , . . . , sN +k ]) = Uh ([s0 , s1 , . . . , sN ])
where R(s)for isallthe
k >reward
0. For for a state,
example, St (a an
suppose random variable)
agent starts is the
at (3,1) state
in the 4 × reached
3 world of at Figure
time t17.1,
when executing policy π, and S = s. (for 4 × 3 we take the
and suppose that N = 3. Then, to have any chance of reaching the +1 state, the agent
0 discount factor γ = 1)must
head directly for it, and the optimal action is to go Up. On the other hand, if N = 100,
then
:
there is plenty of time to take 997
the safe route by going Left. So, with a finite horizon,
2025-05-14
Idea: Each trial provides a sample of the reward to go for each state visited.
Example 28.2.6. The first trial in Example 28.2.3 provides a sample total reward of 0.72 for
state (1,1), two samples of 0.76 and 0.84 for (1,2), two samples of 0.80 and 0.88 for (1,3),
...
Definition 28.2.7. The direct utility estimation algorithm cycles over trials, calculates the
reward to go for each state, and updates the estimated utility for that state by keeping the
running average for that for each state in a table.
Observation 28.2.8. In the limit, the sample average will converge to the true expectation
(utility) from Definition 28.2.4.
Remark 28.2.9. Direct utility estimation is just supervised learning, where each example has
the state as input and the observed reward to go as output.
Upshot: We have reduced reinforcement learning to an inductive learning problem.
: 998 2025-05-14
The utility of each state equals its own reward plus the expected utility of its successor states.
So: The utility values obey a Bellman equation for a fixed policy π.
X
U π (s) = R(s) + γ · ( P (s′ | s,π(s)) · U π (s′ ))
s′
Observation 28.2.10. By ignoring the connections between states, direct utility estimation
misses opportunities for learning.
Example 28.2.11. Recall trial 2 in Example 28.2.3; state (3,3) is new.
2 (1, 1)−0.4 ; (1, 2)−0.4 ; (1, 3)−0.4 ; (2, 3)−0.4 ; (3, 3)−0.4 ; (3, 2)−0.4 ; (3, 3)−0.4
; (4, 3)+1
The next transition reaches (3,3), (known high utility from trial 1)
Bellman equation: ; high U (3, 2) because (3, 2)−0.4 ; (3, 3)
π
But direct utility estimation learns nothing until the end of the trial.
Intuition: Direct utility estimation searches for U in a hypothesis space that too large ⇝
many functions that violate the Bellman equations.
Thus the algorithm often converges very slowly.
: 999 2025-05-14
As above: These equations are linear (no maximization involved)(solve with any any linear
algebra package).
Observation 28.2.12. Learning the model itself is easy, because the environment is fully
observable.
Corollary 28.2.13. We have a supervised learning task where the input is a state–action
pair and the output is the resulting state.
In the simplest case, we can represent the transition model as a table of probabilities.
Count how often each action outcome occurs and estimate the transition probability
P (s′ | s,a) from the frequency with which s′ is reached by action a in s.
Example 28.2.14. In the 3 trials from Example 28.2.3, Right is executed 3 times in (1, 3)
and 2 times the result is (2, 3), so P ((2, 3) | (1,3),Right) is estimated to be 2/3.
: 1000 2025-05-14
: 1001 2025-05-14
Note the large changes occurring around the 78th trial – this is the first time that the agent
falls into the -1 terminal state at (4,2).
Observation 28.2.17. The ADP agent is limited only by its ability to learn the transition
model. (intractable for large state spaces)
: 1002 2025-05-14
: 1003 2025-05-14
Example 28.3.1 (Greedy ADP learning curves for the 4x3 world).
The agent follows the optimal policy for the learned model at each step.
It does not learn the true utilities or the true optimal policy!
instead, in the 39th trial, it finds a policy that reaches the +1 reward along the lower
route via (2,1), (3,1), (3,2), and (3,3).
After experimenting with minor variations, from the 276th trial onward it sticks to that
policy, never learning the utilities of the other states and never finding the optimal route
via (1,2), (1,3), and (2,3).
: 1004 2025-05-14
Pure exploitation risks getting stuck in a rut. Pure exploration to improve one’s knowledge is
of no use if one never puts that knowledge into practice.
Compare with the information gathering agent from section 23.6.
: 1005 2025-05-14
640 CHAPTER 28. REINFORCEMENT LEARNING
Chapter 29
Knowledge in Learning
Method: Search for suitable functions in the hypothesis space. ( e.g. decision trees)
Observation 29.1.1. Every learning task begins from zero. (except for the choice of
hypothesis space)
Problem: We have to forget everything before we can learn something new.
Idea: Utilize prior knowledge about the world! (represented e.g. in logic)
: 1006 2025-05-14
641
642 CHAPTER 29. KNOWLEDGE IN LEARNING
: 1007 2025-05-14
The classification is given by the goal predicate WillWait, in this case WillWait(X 1 ) or
¬WillWait(X 1 ).
: 1008 2025-05-14
can be represented as
Method: Construct a disjunction of all the paths from the root to the positive leaves inter-
preted as conjunctions of the attributes on the path.
Note: The equivalence takes care of positive and negative examples.
: 1009 2025-05-14
Cumulative Development
Example 29.1.6. Learning from very few examples using background knowledge:
Problem: To use background knowledge, need a method to obtain it. (use learning)
Question: How to use knowledge to learn more efficiently?
Answer: Cumulative development: collect knowledge and use it in learning!
Prior
Knowledge
Logic based
Observations Hypotheses Predictions
inductive learning
644 CHAPTER 29. KNOWLEDGE IN LEARNING
Definition 29.1.7. We call the body of knowledge accumulated by (a group of) agents
their background knowledge. It acts as prior knowledge in logic based learning processes.
: 1010 2025-05-14
: 1011 2025-05-14
: 1012 2025-05-14
Definition 29.2.2. Knowledge based inductive learning (KBIL) replaces the explanation
constraint by the KBIL constraint:
: 1013 2025-05-14
29.2. INDUCTIVE LOGIC PROGRAMMING 645
1. The effective hypothesis space is reduced to include only those theories that are consistent
with what is already known.
2. Prior knowledge can be used to reduce the size of the hypothesis explaining the observations.
Smaller hypotheses are easier to find.
Observation: ILP systems can formulate hypotheses in first-order logic.
: 1014 2025-05-14
: 1015 2025-05-14
29.2.1 An Example
ILP: An example
General knowledge-based induction problem
equivalently: A Prolog program that computes the value of the target predicate
; We obtain a perfectly comprehensible hypothesis
: 1016 2025-05-14
George Mum
: 1017 2025-05-14
Example
Descriptions include facts like
Goal: Find a set of sentences for hypothesis such that the entailment constraint is satisfied.
Example 29.2.5. Without background knowledge, define grandparent in terms of mother
and father.
grandparent(x, y)⇔(∃[Link](x, z)∧mother(z, y))∨(∃[Link](x, z)∧father(z, y))∨. . .∨(∃[Link](x, z)∧father(z, y))
: 1018 2025-05-14
A large disjunction of specific cases without any hope of generalization to new examples.
: 1019 2025-05-14
Background knowledge
Observation: A little bit of background knowledge helps a lot.
Example 29.2.6. If the background knowledge contains
Example 29.2.8. Use constructive induction to introduce a predicate parent to simplify the
definitions of the target predicates.
: 1020 2025-05-14
: 1021 2025-05-14
: 1022 2025-05-14
FOIL
function Foil(examples,target) returns a set of Horn clauses
inputs: examples, set of examples
target, a literal for the goal predicate
local variables: clauses, set of clauses, initially empty
while examples contains positive examples do
clause := New−Clause(examples,target)
remove examples covered by clause from examples
add clause to clauses
return clauses
: 1023 2025-05-14
FOIL
function New−Clause(examples,target) returns a Horn clause
local variables: clause, a clause with target as head and an empty body
l, a literal to be added to the clause
extendedExamples, a set of examples with values for new variables
extendedExamples := examples
while extendedExamples contains negative examples do
l := Choose−Literal(New−Literals(clause),extendedExamples)
append l to the body of clause
extendedExamples := map Extend−Example over extendedExamples
return clause
function Extend−Example(example,literal) returns a new example
if example satisfies literal
then return the set of examples created by extending example with each
possible constant value for each new variable in literal
else return the empty set
function New−Literals(clause) returns a set of possibly ‘‘useful’’ literals
29.2. INDUCTIVE LOGIC PROGRAMMING 649
: 1024 2025-05-14
father(x, z) ⇒ grandfather(x, y)
Add literals using predicates
Negated or unnegated
Use any existing predicate (including the goal)
Arguments must be variables
Each literal must include at least one variable from an earlier literal or from the head of
the clause
Valid: M other(z, u), M arried(z, z), grandfather(v, x)
Invalid: M arried(u, v)
Equality and inequality literals
: 1025 2025-05-14
If the clause becomes longer than the total length of the positive examples that the clause
explains, this clause is not a valid hypothesis.
Most impressive demonstration
Learn the correct definition of list-processing functions in Prolog from a small set of
examples, using previously learned functions as background knowledge.
: 1026 2025-05-14
Inverse Resolution
Definition 29.2.9. Inverse resolution in a nutshell
Classifications follows from Background ∧ Hypothesis ∧ Descriptions.
This can be proven by resolution.
Run the proof backwards to find hypothesis.
Problem: How to run the resolution proof backwards?
Recap: In ordinary resolution we take two clauses C1 = L ∨ R1 and C2 = ¬L ∨ R2 and
resolve them to produce the resolvent C = R1 ∨ R2 .
Idea: Two possible variants of inverse resolution:
Take resolvent C and produce two clauses C1 and C2 .
Take C and C1 and produce C2 .
: 1027 2025-05-14
1. Start with an example classified as both positive and negative (Need a contradiction)
2. Invent clauses that resolve with a fact in our knowledge base
[George/x],[Elisabeth/z]
[Anne/y]
{}
: 1028 2025-05-14
: 1029 2025-05-14
Can inverse resolution infer the law of gravity from examples of falling bodies?
Yes, given suitable background mathematics!
Monkey and typewriter problem: How to overcome the large branching factor and the lack
of structure in the search space?
: 1030 2025-05-14
: 1031 2025-05-14
Example 29.2.12. mother(x, y)⇒P (x, y) or father(x, y)⇒P (x, y) leading to the “Parent”
relationship.
Inventing new predicates is important to reduce the size of the definition of the goal predicate.
Some of the deepest revolutions in science come from the invention of new predicates. (e.g.
Galileo’s invention of acceleration)
: 1032 2025-05-14
Applications of ILP
ILP systems have outperformed knowledge free methods in a number of domains.
Molecular biology: the GOLEM system has been able to generate high-quality predictions of
protein structures and the therapeutic efficacy of various drugs.
GOLEM is a completely general-purpose program that is able to make use of background
knowledge about any domain.
: 1033 2025-05-14
Part VII
Natural Language
653
655
This part introduces the basics of natural language processing and the use of natural language
for communication with humans.
In other words: the language you use all day long, e.g. English, German, . . .
Why Should we care about natural language?:
Even more so than thinking, language is a skill that only humans have.
It is a miracle that we can express complex thoughts in a sentence in a matter of seconds.
It is no less miraculous that a child can learn tens of thousands of words and complex
syntax in a matter of a few years.
: 1034 2025-05-14
: 1035 2025-05-14
656
Chapter 30
: 1036 2025-05-14
Language Technology
Language Assistance:
657
658 CHAPTER 30. NATURAL LANGUAGE PROCESSING
Dialog Systems/Interfaces:
information systems: at airport, tele-banking, e-commerce, call centers,
dialog interfaces for computers, robots, cars. (e.g. Siri/Alexa)
Observation: The earlier technologies largely rely on pattern matching, the latter ones
need to compute the meaning of the input utterances, e.g. for database lookups in information
systems.
: 1037 2025-05-14
: 1038 2025-05-14
A good probe into the issues involved in natural language understanding is to look at translations
between natural language utterances – a task that arguably involves understanding the utterances
first.
: 1039 2025-05-14
If it is indeed the meaning of natural language, we should look further into how the form of the
utterances and their meaning interact.
But: What really counts is not the words themselves, but the meaning information they
carry.
Example 30.2.5 (Word Meaning).
“Newspaper” ;
For questions/answers, it would be very useful to find out what words (sentences/texts)
mean.
language
utterance
: 1040 2025-05-14
Let us support the last claim a couple of initial examples. We will come back to these phenomena
again and again over the course of the course and study them in detail.
: 1041 2025-05-14
But there are other phenomena that we need to take into account when compute the meaning
of NL utterances.
Grammar Inference
relevant
Utterance Meaning information
of utterance
Lexicon World knowledge
: 1042 2025-05-14
We will look at another example, that shows that the situation with semantic/pragmatic analysis
is even more complex than we thought. Understanding this is one of the prime objectives of the
AI-2 lecture.
Grammar Inference
utterance- relevant
semantic
Utterance specific information
potential
meaning of utterance
: 1043 2025-05-14
Example 30.2.13 is also a very good example for the claim ??? that even for high-quality (machine)
translation we need semantics.
: 1044 2025-05-14
Logical analysis vs. conceptual analysis: These examples — mostly borrowed from David-
son:tam67 — help us to see the difference between “logical-analysis” and “conceptual-analysis”.
We observed that from “This is a big diamond.” we cannot conclude “This is big”. Now
consider the sentence “Jane is a beautiful dancer”. Similarly, it does not follow from this that
Jane is beautiful, but only that she dances beautifully. Now, what it is to be beautiful or to be a
beautiful dancer is a complicated matter. To say what these things are is a problem of conceptual
analysis. The job of semantics is to uncover the logical form of these sentences. Semantics should
tell us that the two sentences have the same logical forms; and ensure that these logical forms make
the right predictions about the entailments and truth conditions of the sentences, specifically, that
they don’t entail that the object is big or that Jane is beautiful. But our semantics should provide
a distinct logical form for sentences of the type: “This is a fake diamond.” From which it follows
that the thing is fake, but not that it is a diamond.
662 CHAPTER 30. NATURAL LANGUAGE PROCESSING
: 1045 2025-05-14
One way to think about the examples of ambiguity on the previous slide is that they illustrate a
certain kind of indeterminacy in sentence meaning. But really what is indeterminate here is what
sentence is represented by the physical realization (the written sentence or the phonetic string).
The symbol “duck” just happens to be associated with two different things, the noun and the verb.
Figuring out how to interpret the sentence is a matter of deciding which item to select. Similarly
for the syntactic ambiguity represented by PP attachment. Once you, as interpreter, have selected
one of the options, the interpretation is actually fixed. (This doesn’t mean, by the way, that as
an interpreter you necessarily do select a particular one of the options, just that you can.) A
brief digression: Notice that this discussion is in part a discussion about compositionality,
and gives us an idea of what a non-compositional account of meaning could look like. The Radical
Pragmatic View is a non-compositional view: it allows the information content of a sentence to
be fixed by something that has no linguistic reflex.
To help clarify what is meant by compositionality, let me just mention a couple of other ways
in which a semantic account could fail to be compositional.
• Suppose your syntactic theory tells you that S has the structure [a[bc]] but your semantics
computes the meaning of S by first combining the meanings of a and b and then combining the
result with the meaning of c. This is non-compositional.
• Recall the difference between:
1. Jane knows that George was late.
2. Jane believes that George was late.
Sentence 1. entails that George was late; sentence 2. doesn’t. We might try to account for
this by saying that in the environment of the verb “believe”, a clause doesn’t mean what it
usually means, but something else instead. Then the clause “that George was late” is assumed
to contribute different things to the informational content of different sentences. This is a
non-compositional account.
Example 30.3.4. “Every man loves a woman.” (Keira Knightley or his mother!)
Example 30.3.5. “Every car has a radio.” (only one reading!)
Example 30.3.6. “Some student in every course sleeps in every class at least some of the
time.” (how many readings?)
30.3. LOOKING AT NATURAL LANGUAGE 663
Example 30.3.7. “The president of the US is having an affair with an intern.” (2002 or
2000?)
Example 30.3.8. “Everyone is here.” (who is everyone?)
: 1046 2025-05-14
Observation: If we look at the first sentence, then we see that it has two readings:
1. there is one woman who is loved by every man.
2. for each man there is one woman whom that man loves.
These correspond to distinct situations (or possible worlds) that make the sentence true.
Observation: For the second example we only get one reading: the analogue of 2. The reason
for this lies not in the logical structure of the sentence, but in concepts involved. We interpret
the meaning of the word “has” as the relation “has as physical part”, which in our world carries a
certain uniqueness condition: If a is a physical part of b, then it cannot be a physical part of c,
unless b is a physical part of c or vice versa. This makes the structurally possible analogue to 1.
impossible in our world and we discard it.
Observation: In the examples above, we have seen that (in the worst case), we can have one
reading for every ordering of the quantificational phrases in the sentence. So, in the third example,
we have four of them, we would get 4! = 24 readings. It should be clear from introspection that
we (humans) do not entertain 12 readings when we understand and process this sentence. Our
models should account for such effects as well.
Context and Interpretation: It appears that the last two sentences have different informational
content on different occasions of use. Suppose I say “Everyone is here.” at the beginning of class.
Then I mean that everyone who is meant to be in the class is here. Suppose I say it later in the
day at a meeting; then I mean that everyone who is meant to be at the meeting is here. What
shall we say about this? Here are three different kinds of solution:
Radical Semantic View On every occasion of use, the sentence literally means that everyone
in the world is here, and so is strictly speaking false. An interpreter recognizes that the speaker
has said something false, and uses general principles to figure out what the speaker actually
meant.
Radical Pragmatic View What the semantics provides is in some sense incomplete. What the
sentence means is determined in part by the context of utterance and the speaker’s intentions.
The differences in meaning are entirely due to extra-linguistic facts which have no linguistic
reflex.
The Intermediate View The logical form of sentences with the quantifier “every” contains a
slot for information which is contributed by the context. So extra-linguistic information is
required to fix the meaning; but the contribution of this information is mediated by linguistic
form.
We now come to a phenomenon of natural language, that is a paradigmatic challenge for pragmatic
analysis: anaphora – the practice of replacing a (complex) reference with a mere pronoun.
“John loves his wife. Peter does too.” (whom does Peter love?)
“John loves golf, and Mary too.” (who does what?)
Definition 30.3.10. A word or phrase is called anaphoric (or an anaphor), if its interpretation
depends upon another phrase in context. In a narrower sense, an anaphor refers to an earlier
phrase (its antecedent), while a cataphor to a later one (its postcedent).
Definition 30.3.11. The process of determining the antecedent or postcedent of an anaphoric
phrase is called anaphor resolution.
Definition 30.3.12. An anaphoric connection between anaphor and its antecedent or postce-
dent is called direct, iff it can be understood purely syntactically. An anaphoric connection is
called indirect or a bridging reference if additional knowledge is needed.
Anaphora are another example, where natural languages use the inferential capabilities of the
hearer/reader to “shorten” utterances.
Anaphora challenge pragmatic analysis, since they can only be resolved from the context
using world knowledge.
: 1047 2025-05-14
Anaphora are also interesting for pragmatic analysis, since they introduce (often initially massive
amoungs of) ambiguity that needs to be taken care of in the language understanding process.
We now come to another challenge to pragmatic analysis: presuppositions. Instead of just being
subject to the context of the readers/hearers like anaphora, they even have the potential to change
the context itself or even affect their world knowledge.
: 1048 2025-05-14
: 1049 2025-05-14
Thus, a trigram model for a language with 100 characters, P(ci |ci−2:i−1 ) has 1.000.000
entries. It can be estimated from a corpus with 107 characters.
: 1050 2025-05-14
666 CHAPTER 30. NATURAL LANGUAGE PROCESSING
ℓ∗ = argmax (P (ℓ | c1:N ))
ℓ
= argmax (P (ℓ) · P (c1:N | ℓ))
ℓ
N
Y
= argmax (P (ℓ) · ( P (ci | ci−2:i−1 ,ℓ)))
ℓ i=1
The prior probability P (ℓ) can be estimated, it is not a critical factor, since the trigram
language models are extremely sensitive.
: 1051 2025-05-14
Remark 30.4.13. While many features help make this classification, counts of punctuation
and other character n-gram features go a long way [KesNunSch:adtg97].
Definition 30.4.14. Named entity recognition (NER) is the task of finding names of things
in a document and deciding what class they belong to.
Example 30.4.15. In “Mr. Sopersteen was prescribed aciphex.” NER should recognize that
“Mr. Sopersteen” is the name of a person and “aciphex” is the name of a drug.
Remark 30.4.16. Character-level language models are good for this task because they can
associate the character sequence “ex ” with a drug name and “steen ” with a person name,
and thereby identify words that they have never seen before.
: 1052 2025-05-14
: 1053 2025-05-14
Remark 30.4.18. OOV words are usually content words such as names and locations which
contain information crucial to the success of NLP tasks.
Idea: Model OOV words by
1. adding a new word token, e.g. <UNK> to the vocabulary,
2. in the training corpus, replacing the respective first occurrence of a previously unknown
word by <UNK>,
3. counting n grams as usual, treating <UNK> as a regular word.
This trick can be refined if we have a word classifier, then use a new token per class, e.g.
<EMAIL> or <NUM>.
: 1054 2025-05-14
Clearly there are differences, how can we measure them to evaluate the models?
If some characters or words are more likely than others, and the model reflects that, then the
perplexity of correct sequences will be less than n.
Example 30.4.22. In Example 30.4.19, the perplexity was 891 for the unigram model, 142
for the bigram model and 91 for the trigram model.
: 1055 2025-05-14
Native Speakers However: Will tell you that “a black cat” matches a familiar pattern:
article-adjective-noun, while “cat black a” does not!
Example 30.5.1. Consider “the fulvous kitten” a native speaker reasons that it
follows the determiner-adjective-noun pattern
“fulvous” (=
b brownish yellow) ends in “ous” ; adjective
: 1056 2025-05-14
Part-of-Speech Tagging
Definition 30.5.2. Part-of-speech tagging (also POS tagging, POST, or grammatical tag-
ging) is the process of marking up a word in corpus with tags (called POS tags) as corre-
sponding to a particular part of speech (a category of words with similar syntactic properties)
based on both its definition and its context.
Example 30.5.3. A sentence tagged with POS tags from the Penn treebank: (see below)
From the start , it took a person with great qualities to succeed
IN DT NN , PRP VBD DT NN IN JJ NNS TO VB
Observation: Even though POS tagging is uninteresting in its own right, it is useful as a
first step in many NLP tasks.
30.5. PART OF SPEECH TAGGING 669
Example 30.5.4. In text-to-speech synthesis, a POS tag of “noun” for “record” helps deter-
mine the correct pronunciation (as opposed to the tag
“verb”)
: 1057 2025-05-14
: 1058 2025-05-14
starts in the tag predicted by the prior probability (usually IN) (problematic!)
and then, for each step makes two choices:
what word – e.g. “From” – should be emitted
what state – e.g. DT – should come next
This works, but there are problems
the HMM does not consider context other than the current state (Markov property)
it does not have any idea what the sentence is trying to convey
Idea: Use the Viterbi algorithm to find the most probable sequence of hidden states (POS
tags)
670 CHAPTER 30. NATURAL LANGUAGE PROCESSING
POS taggers based on the Viterbi algorithm can reach an F1 score of up to 97%.
: 1059 2025-05-14
These numbers also come from the corpus with appropriate smoothing.
Limitations: HMM models only know about the transition and sensor models
In particular, we cannot take into account that e.g. words ending in “ous” are likely adjectives.
We will see methods based on neural networks later.
: 1060 2025-05-14
: 1061 2025-05-14
Spam Detection
Definition 30.6.5. Spam detection – classifying an email message as spam or ham (i.e.
non-spam)
30.6. TEXT CLASSIFICATION 671
: 1062 2025-05-14
where P (c) is estimated just by counting the total number of spam and ham messages.
This approach works well for spam detection, just as it did for language identification.
: 1063 2025-05-14
#(T P )
#(T P )+#(F N ) , where T P is the set of true positives and F N /F P the sets of false neg-
atives and false positives of fC .
Intuitively these measure the rates of:
: 1064 2025-05-14
Definition 30.7.2. An information object is medium that is mainly used for its information
content.
Definition 30.7.3. Information retrieval (IR) deals with the representation, organization,
storage, and maintenance of information objects that provide users with easy access to the
relevant information and satisfy their various information needs.
Observation (Hjørland 1997): Information need is closely related to relevance: If something
is relevant for a person in relation to a given task, we might say that the person needs the
information for that task.
Definition 30.7.4. Relevance denotes how well an information object meets the information
need of the user. Relevance may include concerns such as timeliness, authority or novelty of
the object.
Observation: We normally come in contact with IR in the form of web search.
Definition 30.7.5. Web search is a fully automatic process that responds to a user query by
returning a sorted document list relevant to the user requirements expressed in the query.
Example 30.7.6. Google and Bing are web search engines, their query is a bag of words
and documents are web pages, PDFs, images, videos, shopping portals.
: 1065 2025-05-14
30.7. INFORMATION RETRIEVAL 673
Example 30.7.9. If we have two documents: d1 = “Have a good day!” and d2 = “Have a great day!”,
then we can use V = “Have”, “a”, “good”, “great”, “day” and can represent “good” as ⟨0, 0, 1, 0, 0⟩,
“great” as ⟨0, 0, 0, 1, 0⟩, and d1 a ⟨1, 1, 1, 0, 1⟩.
Words outside the vocabulary are ignored in the BOW approach. So the document d3 =
“What a day, a good day” is represented as ⟨0, 2, 1, 0, 2⟩.
: 1066 2025-05-14
term 1
D1 (t1,1 , t1,2 , t1,3 )
D2 (t2,1 , t2,2 , t2,3 )
term 3
term 2
Lemma 30.7.10 (Euclidean Dot Product Formula). A·B = ∥A∥2 ∥B∥2 cos θ, where θ is
the angle between A and B.
: 1067 2025-05-14
Definition 30.7.14. Given a document collection D = {d1 , . . ., dN } and a word t the inverse
document frequency is given by idf(t, D) := log10 ( |{d∈DN| t∈d}| ).
: 1068 2025-05-14
TF-IDF Example
Let D := {d1 , d2 } be a document corpus over the vocabulary
tf(“this′′ , d1 ) = 1
5 = 0.2 and tf(“this′′ , d2 ) = 1
7 ≊ 0.14,
′′
idf is constant over D, we have idf(“this , D) = log10 ( 22 ) = 0,
thus tfidf(“this′′ , d1 , D) = 0 = tfidf(“this′′ , d2 , D). (“this” occurs in both)
The word “example” is more interesting, since it occurs only in d2 (thrice)
tf(“example′′ , d1 ) = 0
5 = 0 and tf(“example′′ , d2 ) = 3
7 ≊ 0.429.
′′
idf(“example , D) = log10 ( 12 ) ≊ 0.301,
thus tfidf(“example , d1 , D) = 0·0.301 = 0 and tfidf(“example′′ , d2 , D) ≊ 0.429·0.301 =
′′
0.129.
: 1069 2025-05-14
Once an answer set has been determined, the results have to be sorted, so that they can be
presented to the user. As the user has a limited attention span – users will look at most at three
to eight results before refining a query, it is important to rank the results, so that the hits that
contain information relevant to the user’s information need early. This is a very difficult problem,
as it involves guessing the intentions and information context of users, to which the search engine
has no access.
Definition 30.7.17. Let A be a web page that is hyperlinked from web pages S1 , . . . , Sn ,
then the page rank PR of A is defined as
PR(S1 ) PR(Sn )
PR(A) = 1 − d + d + ··· +
C(S1 ) C(Sn )
: 1070 2025-05-14
Getting the ranking right is a determining factor for success of a search engine. In fact, the early
of Google was based on the pagerank algorithm discussed above (and the fact that they figured
out a revenue stream using text ads to monetize searches).
Example 30.8.3. Extracting instances of storms from weather reports, with attributes for
temperature, wind speed, and precipitation.
Observation: In a limited domain, this can be done with high accuracy.
: 1071 2025-05-14
\{Manufacturer=IBM, Model=ThinkBook970,Price=$399.00\}.
Idea: Try a template-based approach for each attribute.
Definition 30.8.6. A template is a finite automaton that recognizes the information to be
extracted. The template often consists of three sub-automata per attribute: the prefix pattern
followed by the target pattern (it matches the attribute value) and the postfix pattern.
Example 30.8.7 (Extracing Prices with Regular Expressions).
When we want to extract computer price information, we could use regular expressions for
the automata, concretely, the
Example 30.8.8. For “List price $99.00, special sale price $78.00, shipping $3.00.” take the
lowest price that is within 50% of the highest price. ; “$78.00”
: 1072 2025-05-14
: 1073 2025-05-14
: 1074 2025-05-14
678 CHAPTER 30. NATURAL LANGUAGE PROCESSING
Chapter 31
Overview:
1. Word embeddings
2. Recurrent neural networks for NLP
3. Sequence-to-sequence models
4. Transformer Architecture
5. Pretraining and transfer learning.
: 1075 2025-05-14
Word Embeddings
Problem: For ML methods in NLP, we need numerical data. (not words)
679
680 CHAPTER 31. DEEP LEARNING FOR NLP
: 1076 2025-05-14
Word2Vec
Idea: Use feature extraction to map words to vectors in RN :
Train a neural network on a “dummy task”, throw away the output layer, use the previous
layer’s output (of size N ) as the word embedding
First Attempt: Dimensionality Reduction: Train to predict the original one hot vector:
For a vocabulary size V , train a network with a single hidden layer; i.e. three layers of sizes
(V, N, V ). The first two layers will compute our embeddings.
Feed the one hot encoded input word into the network, and train it on the one hot vector
itself, using a softmax activation function at the output layer. (softmax normalizes a vector
into a probability distribution)
: 1077 2025-05-14
: 1078 2025-05-14
Properties
Vector embeddings like CBOW have interesting properties:
Similarity : Using e.g. cosine similarity (A · B · cos(θ)) to compare vectors, we can find words
with similar meanings.
: 1079 2025-05-14
: 1080 2025-05-14
an adjective
a noun.
If a nearby temporal adverb refers to the past ; this occurrence may be a past tense verb.
Note: CBOW treats all context words identically reagrdless of order, but in POS tagging the
exact positions of the words matter.
: 1081 2025-05-14
POS/Embedding Network
Idea: Start with a random (or pretrained) embedding of the words in the corpus and just
concatenate them over some context window size
Figure 24.3
Feedforward part-of-speech tagging model. This model takes a 5-word window as input and
predicts the tag of the word in the middle—here, cut. The model is able to account for word
Layer 1 has (in this case) 5 · N inputs, Output layer is one hot over POS classes.
position because each of the 5 input embeddings is multiplied by a different part of the first
hidden layer. The parameter values for the word embeddings and for the three layers are all
learned simultaneously during training.
The embedding layers treat all words the same, but the first hidden layer will treat them
differently depending7. on the position.
To encode a sequence of words into an input vector, simply look up the
embedding for each word and concatenate the embedding vectors. The result is a
real-valued input vector of length . Even though a given word will have the
The embeddings will same
be embedding
finetuned for the POS task during training.
vector whether it occurs in the first position, the last, or
somewhere in between, each embedding will be multiplied by a different part of the
first hidden layer; therefore we are implicitly encoding the relative position of each
word.
8. Train the weights and the other weight matrices , , and using gradient
descent. If all goes well, the middle word, cut, will be labeled as a past-tense verb,
based on the evidence in the window, which includes the temporal past word
“yesterday,” the third-person subject pronoun “they” immediately before cut, and so
31.2. RECURRENT NEURAL NETWORKS 683
Note: Better positional encoding techniques exist (e.g. sinusoidal), but for fixed small context
window sizes, this works well.
: 1082 2025-05-14
Observation: For advanced tasks like question answering we need more context!
Example 31.2.1. In the sentence “Eduardo told me that Miguel was very sick so I took
him to the hospital”, the pronouns “him” refers to “Miguel” and not “Eduardo”. (14 words of
context)
Observation: Language models with n-grams or n-word feed-forward networks have prob-
lems:
Either the context is too small or the model has too many parameters! (or both)
Observation: Feed-forward networks N also have the problem of asymmetry: whatever N
learns about a word w at position n, it has to relearn about w at position m ̸= n.
Idea: What about recurrent neural networks – nets with cycles? (up next)
: 1083 2025-05-14
Intuition: RNNs are a bit like HMMs and dynamic Bayesian Networks:
indicates a delay. Each input is the word embedding vector of the next w
output is the output for that time step. (b) The same network unrolled o
They make a Markov assumption: the hidden state z suffices to capture the input from all
feedforward network. Note that the weights are shared across all timestep
previous inputs.
In an RNN language model each input word is encoded as a wor
There is a hidden layer which gets passed as input from one tim
interested in doing multiclass classification: the classes are the w
Side Benefit: RNNs solve the asymmetry problem ⇝, the Wz,z are the same at every step.
: 1084 2025-05-14
Problem: The weight matrices Wx,z , Wz,z , and Wz,y are shared over all time slides.
(a) Schematic diagram of an RNN where the hidden layer has recurrent connections; the symbol
indicates a delay. Each input is the word embedding vector of the next word in the sentence. Each
Definition 31.2.4. The back-propagation through time algorithm carefully maintains the
output is the output for that time step. (b) The same network unrolled over three timesteps to create a
identity of W over all steps
feedforward network. Note
z,z that the weights are shared across all timesteps.
In an RNN language model each input word is encoded as a word embedding vector, .
: 1085 2025-05-14
There is a hidden layer which gets passed as input from one time step to the next. We are
interested in doing multiclass classification: the classes are the words of the vocabulary.
Bidirectional
Thus the output RNN
will for probability
be a softmax more Context
distribution over the possible values of the
next word in the sentence.
Observation: RNNs only take left context – i.e. words before – into account, but we may
also need right context – the words after.
The RNN architecture solves the problem of too many parameters. The number of
Example
parameters in the31.2.5. For “Eduardo
weight matrixes , , andtold stays
me constant,
that Miguel wasofvery
regardless sick so
the number I took him to the
hospital”is
of words—it the. This
pronoun “him” toresolves
is in contrast to “Miguel”
feedforward withhave
networks, which high probability.
If the sentence
parameters, ended
and -gram with
models, “to
which have
see thenwhere
parameters,
Miguel”, it should
is thebe
size“Eduardo”.
of the
vocabulary.
Definition 31.2.6. A bidirectional RNN concatenates a separate right-to-left model onto a
left-to-right model
The RNN architecture also solves the problem of asymmetry, because the weights are the
Example
same 31.2.7.
for every word Bidirectional
position. RNNs can be used for POS tagging, extending the network
from ???
The RNN architecture can sometimes solve the limited context problem as well. In theory
there is no limit to how far back in the input the model can look. Each update of the hidden
layer has access to both the current input word and the previous hidden layer ,
which means that information about any word in the input can be kept in the hidden layer
indefinitely, copied over (or modified as appropriate) from one time step to the next. Of
course, there is a limited amount of storage in , so it can’t remember everything about all
the previous words.
referent him would be different if the sentence concluded “to see Miguel” rather than “to the
hospital,” so looking ahead is crucial. We know from eye-tracking experiments that human
To capture the context on the right, we can use a bidirectional RNN, which concatenates a
separate right-to-left model onto the left-to-right model. An example of using a bidirectional
: 1086 2025-05-14
: 1087 2025-05-14
LSTM: Idea
Introduce a memory vector c in addition to the recurrent (short-term memory) vector z
c is essentially copied from the previous time step, but can be modified by the forget gate f ,
the input gate i, and the output gate o.
the forget gate f decides which components of c to retain or discard
the input gate i decides which components of the current input to add to c (additive, not
multiplicative ; no vanishing gradients)
the output gate o decides which components of c to output as z
: 1088 2025-05-14
686 CHAPTER 31. DEEP LEARNING FOR NLP
Idea: For MT, generate one word at a time, but keep track of the context, so that
we can remember parts of the source we have not translated yet
we remember what we already translated so we do not repeat ourselves.
We may have to process the whole source sentence before generating the target!
sentences we have to process the entire source sentence before starting to generate the
Sequence-To-Sequence Models
This gives text generation for MT a close connection to a standard RNN language model, as
described in Section 24.2 . Certainly, if we had trained an RNN on English text, it would be
target is the output of the last hidden layer of the source RNN.
any random target language sentence; we want to generate a target language sentence that
corresponds to the source language sentence. The simplest way to do that is to use two
Definition 31.3.1.
RNNs, one A forsequence-to-sequence (seq2seq)
the source and one for the target. model
We run the sourceis
RNNa neural
over themodel
source for translating
an input sequence
sentencexandinto
thenanuseoutput
the final sequence
hidden state y bythe
from ansource
encoder
RNN asfollowed
the initialby a decoder
hidden state generates
y. for the target RNN. This way, each target word is implicitly conditioned on both the entire
source sentence and the previous target words.
output
This neural network architecture is called a basic sequence-to-sequence model, an example
hi
Encoder Decoder
of which is shown in Figure 24.6 . Sequence-to-sequence models are most commonly used
for machine translation, but can also be used for a number of other tasks, like automatically
input
generating a text caption from an image, or summarization: rewriting a long text into a
Example 31.3.2. A simple seq2seq model (without embedding and output layers)
Figure 24.6
Basic sequence-to-sequence model. Each block represents one LSTM timestep. (For simplicity, the
embedding and output layers are not shown.) On successive steps we feed the network the words of the
Each block represents
source sentenceone LSTM
“The man is tall,”time step;
followed by the inputs areto fed
<start> tag successively
indicate that the networkfollowed
should start by the token
<start> to producing
start the decoder.
the target sentence. The final hidden state at the end of the source sentence is used as the
hidden state for the start of the target sentence. After that, each target sentence word at time is used as
input at time , until the network produces the <end> tag to indicate that sentence generation is
finished.
31.3. SEQUENCE-TO-SEQUENCE MODELS 687
: 1090 2025-05-14
Seq2Seq Evaluation
Remark: Seq2seq models were a major breakthrough in NLP and MT. But they have three
major shortcomings:
nearby context bias: RNNs remember with their hidden state, which has more informa-
tion about a word in – say – step 56 than in step 5. BUT long-distance context can also
be important.
fixed context size: the entire information about the source sentence must be compressed
into the fixed-dimensional – typically 1024 – vector. Larger vectors ; slow training and
overfitting.
Idea: Concatenate all source RNN hidden vectors to use all of them to mitigate the nearby
context bias.
Problem: Huge increase of weights ; slow training and overfitting.
: 1091 2025-05-14
Attention
Bad Idea: Concatenate all source RNN hidden vectors to use all of them to mitigate the
nearby context bias.
Better Idea: The decoder generates the target sequence one word at a time. ; Only a
small part of the source is actually relevant.
the decoder must focus on different parts of the source for every word.
Idea: We need a neural component that does context-free summarization.
Definition 31.3.3. An attentional seq2seq model is a seq2seq that passes along a context
vector ci in the decoder. If hi = RN N (hi−1 , xi ) is the standard decoder, then the decoder
with attention is given by hi = RN N (hi−1 , xi + ci ), where xi + ci is the concatenation of
the input xi and context vectors ci with
output
context
vector
Encoder Decoder xi + c i
input
: 1092 2025-05-14
words. Finally, these probabilities are used to generate a weighted average of the source
timestep , and is the output of the source RNN vector for the source word (or timestep) .
RNN vectors, Both
(another
and -dimensional vector).
are -dimensional vectors, where is the hidden size. The value of is
therefore the raw “attention score” between the current target state and the source word .
when; the model learns what to use. Attention can also be combined with multilayer RNNs.
: 1093 2025-05-14
Definition 31.3.6. Always selecting the highest probability word is called greedy decoding.
Problem: This may not always maximize the probability of the whole sequence
Example 31.3.7. Let’s use a greedy decoder on “The front door is red”.
The correct translation is “La puerta de entrada es roja”.
Suppose we have generated the first word “La” for “The”.
A greedy decoder might propose “entrada” for “front”.
Greedy decoding is fast, but has no mechanism for correcting mistakes.
Solution: Use an optimizing search algorithm (e.g. local beam search)
: 1094 2025-05-14
Idea: Search for an optimal decoding (or at least a good one) using one of the search
algorithms from chapter 6.
Local beam search is a common choice in machine translation. Concretely:
Observation: The better the seq2seq models get, the smaller we can keep beam size
Today beams of b = 4 are sufficient after b = 100 a decade ago.
: 1095 2025-05-14
Beam search with beam size of . The score of each word is the log-probability generated by the target
WordRNN
scores areand
softmax, log-probabilities generated
the score of each hypothesis by ofthe
is the sum the decoder
word [Link]
At timestep 3, the highest
scoring hypothesis La entrada can only generate low-probability continuations, so it “falls off the beam.”
hypothesis score is the sum of the word scores.
At time step 3, the highest scoring hypothesis “La entrada” can only generate low-probability
continuations, so it “falls off the beam”. (as intended)
: 1096 2025-05-14
Self-attention extends this so that each hidden states sequence also attends to itself.(*coder
to *coder)
Idea: Just use the dot product of the input vectors
Problem: Always high, so each hidden state will be biased towards attending to itself.
690 CHAPTER 31. DEEP LEARNING FOR NLP
Self-attention solves this by first projecting the input into three different representations using
three different weight matrices:
the query vector qi = Wq xi =
b standard attention
key vector ki = Wk xi =
b the source in seq2seq
value vector vi = Wv xi is the context being generated
√
rij = (qi ·kiP
)/ d
aij erij /( k erij )
= P
ci = j aij · vj
: 1097 2025-05-14
use positional embeddings to cope with that. learned about, the output of layer is used as the input to layer .
Example 31.4.2. Figure 24.9
Positional embedding
: 1098 2025-05-14
The transformer architecture does not explicitly capture the order of words in the sequence,
A Transformer for POS tagging since context is modeled only through self-attention, which is agnostic to word order. To
capture the ordering of the words, the transformer uses a technique called positional
embedding. If our input sequence has a maximum length of , then we learn new
sentence used in Figure 24.3 . At the bottom, the word embedding and the positional
embeddings are summed to form the input for a three-layer transformer. The transformer
produces one vector per word, as in RNN-based POS tagging. Each vector is fed into a final
output layer and softmax layer to produce a probability distribution over the tags.
: 1099 2025-05-14
In this section, we have actually only told half the transformer story: the model we
described here is called the transformer encoder. It is useful for text classification tasks. The
Pretraining version
and ofTransfer Learning
decoder. The encoder and decoder are nearly identical, except that the decoder uses a
self-attention where each word can only attend to the words before it, since text
is generated left-to-right. The decoder also has a second attention module in each
Getting enough data layer
transformer to build a robust
that attends modelof can
to the output be a challenge.
the transformer encoder.
Idea: Why not let other’s do this work and re-use their training efforts.
Definition 31.5.1. In pretraining we use
a large amount of shared general-domain language data to train an initial version of an
NLP model.
a smaller amount of domain-specific data (perhaps labeled) to finetune it to the vocabulary,
idioms, syntactic structures, and other linguistic phenomena that are specific to the new
domain.
Pretraining is a form of transfer learning:
Definition 31.5.2. In Transfer learning (TL), knowledge learned from a task is re-used in
order to boost performance on a related task.
Idea: Take a pretrained neural network, replace the last layer(s), and then train those on
your own corpus.
: 1100 2025-05-14
692 CHAPTER 31. DEEP LEARNING FOR NLP
: 1101 2025-05-14
While ℓ < N , find the most common pair of tokens (a, b) and let BPE(⟨a, b⟩) = ℓ + 1 (and
increase ℓ by 1).
Repeat until ℓ = N .
; we obtain a one-hot encoding of tokens of size N , where the most common sequences of bytes
are represented by a single token. By retaining BPE(⟨b⟩) = b, we avoid OOV problems.
; We can then train a word embedding on the resulting tokens
Alternative techniques include WordPiece and SentencePiece.
: 1102 2025-05-14
Tokenization - Example
[Link]
31.5. LARGE LANGUAGE MODELS 693
: 1103 2025-05-14
Positional encodings
Definition 31.5.5. Let ⟨w1 , . . . , wn ⟩ be a sequence of tokens. A positional encoding PEi (wi ) is
a vector that retains the position of wi in the sequence alongside the word embedding of wi .
We want positional encodings to satisfy the following properties:
1. PEi (w) ̸= PEj (w) for i ̸= j,
: 1104 2025-05-14
: 1105 2025-05-14
Masked Token Prediction: Given a sentence (e.g. “The river rose five feet”), randomly replace
tokens by a special mask token (e.g. “The river [MASK] five feet”). The LLM should predict
694 CHAPTER 31. DEEP LEARNING FOR NLP
the masked tokens (e.g. “rose”). (BERT et al; well suited for generic tasks)
Discrimination: Train a small masked token prediction model M . Given a masked sentence,
let M generated possible completions. Train the actual model to distinguish between tokens
generated by M and the original tokens. (Google Electra et al; well suited for generic tasks)
Next Token Prediction: Given the (beginning of) a sentence, predict the next token in the
sequence. (GPT et al; well suited for generative tasks)
: 1106 2025-05-14
DL4NLP methods do very well, but only after processing orders of magnitude more data than
humans do for learning language.
This suggests that there is of scope for new insigths from all areas.
: 1107 2025-05-14
Chapter 32
Planning
Planning Frameworks
Planning Algorithms
Planning and Acting in the real world
: 1108 2025-05-14
695
696 CHAPTER 32. WHAT DID WE LEARN IN AI 1/2?
Agent Sensors
Percepts
Environment
?
Actions
Actuators
there is to say about the agent. Mathematically speaking, we say that an agent’s behavior is
Agent Sensors
AGENT FUNCTION described by the agent function that maps any given percept sequence to an action.
We can imagine tabulating the agent function that describes any given agent; for most
What the world
agents, this would be a very large table—infinite,is like in now
fact, unless we place a bound on the
length of percept sequences we want to consider. Given an agent to experiment with, we can,
Environment
in principle, construct this table by trying out all possible percept sequences and recording
which actions the agent does in response.1 The table is, of course, an external characterization
of the agent. Internally, the agent function for an artificial agent will be implemented by an
AGENT PROGRAM agent program. It is important to keep these two ideas distinct. The agent function is an
What action I
abstract mathematical Condition-action
description; rules
the agent program isnow
should do a concrete implementation, running
within some physical system.
To illustrate these ideas, we use a very simple example—the vacuum-cleaner world
Actuators
shown in Figure 2.2. This world is so simple that we can describe everything that happens;
it’s also a made-up world, so we can invent many variations. This particular world has just two
Figure 2.9 Schematic diagram of a simple reflex agent.
locations:
Reflex Agentssquares A and B. The vacuum agent perceives which square it is in and whether
with State
there is dirt in the square. It can choose to move left, move right, suck up the dirt, or do
nothing. One very simple agent function is the following: if the current square is dirty, then
function
suck; S IMPLE
otherwise, -R EFLEX
move to the-Aother
GENTsquare. ) returns
( perceptA an action of this agent function is shown
partial tabulation
persistent: rules, a set of condition–action rules
in Figure 2.3 and an agent program that implements it appears in Figure 2.8 on page 48.
Looking
state at Figure-I2.3,
← I NTERPRET NPUT we see that
( percept ) various vacuum-world agents can be defined simply
by filling
rule ←in Rthe
ULE -M ATCH(state,
right-hand column in various ways. The obvious question, then, is this: What
rules)
right ←
is theaction rule.A
way CTION
to fill out the table? In other words, what makes an agent good or bad,
returnor
intelligent action
stupid? We answer these questions in the next section.
1 If the agent2.10
Figure uses some randomization
A simple to choose
reflex agent. It its
actsactions, then we
according to awould have to condition
rule whose try each sequence
matchesmany
times the
to identify
currentthe probability
state, of each
as defined action.
by the One might imagine that acting randomly is rather silly, but we
percept.
show later in this chapter that it can be very intelligent.
Section 2.4. The Structure of Agents 51 697
Sensors
State
How the world evolves What the world
is like now
Environment
What my actions do
Agent Actuators
Environment
What it will be like
What my actions do
state ← U PDATE -S TATE(state, action , percept ,ifmodel ) A
I do action
rule ← RULE -M ATCH(state, rules)
action ← [Link]
return action
What action I
Goals should do now
Figure 2.12 A model-based reflex agent. It keeps track of the current state of the world,
using an internal model. It then chooses an actionActuators
Agent in the same way as the reflex agent.
54 is responsible
Figure 2.13 for creating the newgoal-based
A model-based, internal state description.
agent. It keepsChapter The
track details
of [Link]
howasmodels
state as and
wellAgents
Utility-Based
statesa are
set of Agent
goals it is trying
represented to achieve,
vary widely and chooses
depending on thean action
type ofthat will (eventually)
environment and lead to the
the particular
achievement
technology used ofin its
thegoals.
agent design. Detailed examples of models and updating algorithms
appear in Chapters 4, 12, 11, 15, 17, and 25. Sensors
Regardless
example, the taxi of maythebekind of representation
driving
State back home, and used,it may it ishaveseldom
a rule possible fortothe
telling it fill agent
up with to
determine the current
gas on the way homeHow state
unless of a partially observable
it has at least half What a istank. environment exactly. Instead,
Although “driving back home” may
the world the box
the world evolves like now
labeled
seem to “what
an aspectthe of
world is likestate,
the world now”the(Figure
fact of2.11)
the taxi’srepresents the agent’s
destination “bestanguess”
is actually aspect (orof
Environment
sometimes
the agent’s best guesses).
internal state. Foryou
If example,
find thisanpuzzling,
automated willtaxi
What itconsider may
be like thatnot
the betaxi
able to see
could be around
in the
exactly
What my actions do
large truckplace
the same that at
hasthestopped
same time,in front
but of it and can
intending
if Ionly
do action
to reach guess
A about what may be causing the
a different destination.
hold-up. Thus, uncertainty about the current state may be unavoidable, but the agent still has
Utility How happy I will be
to make Goal-based
2.4.4 a decision. agents in such a state
A perhaps less obvious point about the internal “state” maintained by a model-based
What action I
Knowing
agent something
is that it does not about thetocurrent
have describe state of thethe
“what environment
should world
do nowis like is not
now” always
in a enough to decide
literal sense. For
what to do. For example, at a road junction, the taxi can turn left, turn right, or go straight
on. The correct decisionAgent depends on where the taxiActuators is trying to get to. In other words, as well
GOAL as a current state description, the agent needs some sort of goal information that describes
situations
Figurethat2.14are desirable—for
A model-based, example,utility-basedbeing
agent. at Ittheusespassenger’s
a model of destination.
the world, along Thewith
agent
Learning
program Agents
canfunction
a utility combine thatthis with the
measures model (theamong
its preferences same information
states of the [Link] wasThenused in the model-
it chooses the
basedaction
reflex agent)
that leads to
to choose
the best actions
expectedthat achieve
utility, wherethe goal. Figure
expected 2.13
utility is shows by
computed theaveraging
goal-based
overstructure.
agent’s all possible outcome states, weighted by the probability of the outcome.
Sometimes goal-based action selection is straightforward—for example, when goal sat-
isfaction results immediately from a single action. Sometimes it will be more tricky—for
outcome. (Appendix A defines expectation more precisely.) In Chapter 16, we show that any
example, when the agent has to consider long sequences of twists and turns in order to find a
rational
way to achievemust
agent behave
the goal. it possesses
as if (Chapters
Search 3 toa 5)
utility
and function
planningwhose (Chaptersexpected
10 andvalue it tries
11) are the
to maximize. An agent that possesses an explicit utility
subfields of AI devoted to finding action sequences that achieve the agent’s goals. function can make rational decisions
with aNotice
general-purpose
that decision algorithm
making that does
of this notisdepend
kind fundamentally on the specific
differentutility
from thefunction being
condition–
Section 2.4. The Structure of Agents 55
698 CHAPTER 32. WHAT DID WE LEARN IN AI 1/2?
Performance standard
Critic Sensors
feedback
Environment
changes
Learning Performance
element element
knowledge
learning
goals
Problem
generator
Actuators
Agent
He estimates how much work this might take and concludes “Some more expeditious method
Rational Agent
seems desirable.” The method he proposes is to build learning machines and then to teach
them. In many areas of AI, this is now the preferred method for creating state-of-the-art
systems. Learning has another advantage, as we noted earlier: it allows the agent to operate
Idea: Try to design agents that are successful (do the right thing)
in initially unknown environments and to become more competent than its initial knowledge
alone might
Definition allow. An
32.0.1. In agent
this section, werational,
is called briefly introduce the whichever
if it chooses main ideasaction
of learning agents.
maximizes the
Throughout the book, we comment on opportunities and methods for learning
expected value of the performance measure given the percept sequence to date. This is called in particular
thekinds
MEU of principle.
agents. Part V goes into much more depth on the learning algorithms themselves.
A learning agent can be divided into four conceptual components, as shown in Fig-
Note:
LEARNING ELEMENT
A rational
ure 2.15. The most agent need not
important be perfectis between the learning element, which is re-
distinction
PERFORMANCE
ELEMENT sponsible
for making
only needs improvements,
to maximize expected and the performance element, which
value is responsible
(rational for
̸= omniscient)
selecting external actions. The performance element is what we have previously considered
need not predict e.g. very unlikely but catastrophic events in the future
to be the entire agent: it takes in percepts and decides on actions. The learning element uses
CRITIC perceptsfrom
feedback
maythenotcritic
supplyonallhow
relevant information
the agent is doing and determines(Rational
how the ̸= clairvoyant)
performance
element should
if we be modified
cannot perceive to do better
things we doin not
the future.
need to react to them.
but we may need to try to find out about very
The design of the learning element depends much
hidden on the design of the performance
dangers (exploration)
element. When trying to design an agent that learns a certain capability, the first question is
action outcomes may not be as expected (rational ̸= successful)
not “How am I going to get it to learn this?” but “What kind of performance element will my
but
agent needwe to may need
do this to ittake
once has action
learnedtohow?”
ensure that an
Given they do design,
agent (more often) (learning)
learning mechanisms
can be constructed to improve every part of the agent.
Rational ; exploration, learning, autonomy
The critic tells the learning element how well the agent is doing with respect to a fixed
performance standard. The critic is necessary because the percepts themselves provide no
indication: of the agent’s success. For example, 1110 a chess program could receive
2025-05-14 a percept
indicating that it has checkmated its opponent, but it needs a performance standard to know
that this is a good thing; the percept itself does not say so. It is important that the performance
Symbolic AI: Adding Knowledge to Algorithms
: 1111 2025-05-14
: 1112 2025-05-14
: 1113 2025-05-14
: 1114 2025-05-14
Part VIII
Excursions
701
703
As this course is predominantly an overview over the topics of artificial intelligence, and not
about the theoretical underpinnings, we give the discussion about these as a “suggested readings”
part here.
704
Appendix A
The next step is to analyze the two calculi for completeness. For that we will first give ourselves
a very powerful tool: the “model existence theorem” (???), which encapsulates the model-theoretic
part of completeness theorems. With that, completeness proofs – which are quite tedious otherwise
– become a breeze.
705
706 APPENDIX A. COMPLETENESS OF CALCULI FOR PROPOSITIONAL LOGIC
Idea: Re-package the argument, so that the model-construction for S can be re-used for
multiple calculi ; the abstract consistency/model-existence method:
1. Definition A.1.1. Abstract consistency class ∇ =
b family of ∇-consistent sets.
2. Definition A.1.2. A ∇-Hintikka set is a ⊆-maximally ∇-consistent.
3. Theorem A.1.3 (Hintikka Lemma). ∇-Hintikka set are satisfiable.
4. Theorem A.1.4 (Extension Theorem). If Φ is ∇-consistent, then Φ can be extended to
a ∇-Hintikka set.
5. Corollary A.1.5 (Henkins theorem). If Φ is ∇-consistent, then Φ is satisfiable.
6. Lemma A.1.6 (Application). Let C be a calculus, if Φ is C-consistent, then Φ is ∇-
consistent.
7. Corollary A.1.7 (Completeness). C is complete.
Note: Only the last two are C-specific, the rest only depend on S.
: 1115 2025-05-14
The proof of the model-existence theorem goes via the notion of a ∇-Hintikka set, a set of
formulae with very strong syntactic closure properties, which allow to read off models. Jaako
Hintikka’s original idea for completeness proofs was that for every complete calculus C and every
C-consistent set one can induce a ∇-Hintikka set, from which a model can be constructed. This
can be considered as a first model-existence theorem. However, the process of obtaining a ∇-Hin-
tikka set for a C-consistent set Φ of propositions usually involves complicated calculus dependent
constructions.
In this situation, Raymond Smullyan was able to formulate the sufficient conditions for the
existence of ∇-Hintikka set in the form of “abstract consistency properties” by isolating the calculus
independent parts of the Hintikka set construction. His technique allows to reformulate ∇-Hintikka
set as maximal elements of abstract consistency classes and interpret the Hintikka set construction
as a maximizing limit process.
To carry out the abstract consistency/model-existence method, we will first have to look at the
notion of consistency.
consistency and refutability are very important notions when studying the completeness for calculi;
they form syntactic counterparts of satisfiability.
Definition A.1.10. We call a calculus C reasonable, iff implication elimination and conjunc-
tion introduction are admissible in C and A ∧ ¬A ⇒ B is a C-theorem.
Theorem A.1.11. C-inconsistency and C-refutability coincide for reasonable calculi.
Remark A.1.12. We will use that C-irrefutable =
b C-consistent below.
: 1116 2025-05-14
It is very important to distinguish the syntactic C-refutability and C-consistency from satisfiability,
which is a property of formulae that is at the heart of semantics. Note that the former have the
calculus (a syntactic device) as a parameter, while the latter does not. In fact we should actually
say S-satisfiability, where ⟨L, ⊨⟩ is the current logical system.
Even the word “contradiction” has a syntactical flavor to it, it translates to “saying against
each other” from its Latin root.
Abstract Consistency
Definition A.2.1. Let ∇ be a collection of sets. We call ∇ closed under subsets, iff for each
Φ ∈ ∇, all subsets Ψ ⊆ Φ are elements of ∇.
Definition A.2.2 (Notation). We will use Φ∗A for Φ ∪ {A}.
: 1117 2025-05-14
So a collection of sets (we call it a collection, so that we do not have to say “set of sets” and we
can distinguish the levels) is an abstract consistency class, iff it fulfills five simple conditions, of
which the last three are closure conditions.
Think of an abstract consistency class as a collection of “consistent” sets (e.g. C-consistent
for some calculus C), then the properties make perfect sense: They are naturally closed under
subsets — if we cannot derive a contradiction from a large set, we certainly cannot from a subset,
furthermore,
∇c ) If both P ∈ Φ and ¬P ∈ Φ, then Φ cannot be “consistent”.
∇¬ ) If we cannot derive a contradiction from Φ with ¬¬A ∈ Φ then we cannot from Φ∗A, since
they are logically equivalent.
The other two conditions are motivated similarly. We will carry out the proof here, since it
gives us practice in dealing with the abstract consistency properties.
The main result here is that abstract consistency classes can be extended to compact ones.
The proof is quite tedious, but relatively straightforward. It allows us to assume that all abstract
708 APPENDIX A. COMPLETENESS OF CALCULI FOR PROPOSITIONAL LOGIC
consistency classes are compact in the first place (otherwise we pass to the compact extension).
Actually we are after abstract consistency classes that have an even stronger property than just
being closed under subsets. This will allow us to carry out a limit construction in the ∇-Hintikka
set extension argument later.
Compact Collections
Definition A.2.7. We call a collection ∇ of sets compact, iff for any set Φ we have
Φ ∈ ∇, iff Ψ ∈ ∇ for every finite subset Ψ of Φ.
Lemma A.2.8. If ∇ is compact, then ∇ is closed under subsets.
Proof:
1. Suppose S ⊆ T and T ∈ ∇.
2. Every finite subset A of S is a finite subset of T .
3. As ∇ is compact, we know that A ∈ ∇.
4. Thus S ∈ ∇.
□
: 1118 2025-05-14
The property of being closed under subsets is a “downwards-oriented” property: We go from large
sets to small sets, compactness (the interesting direction anyways) is also an “upwards-oriented”
property. We can go from small (finite) sets to large (infinite) sets. The main application for
the compactness condition will be to show that infinite sets of formulae are in a collection ∇ by
testing all their finite subsets (which is much simpler).
Proof:
1. We choose ∇′ := {Φ ⊆ wff 0 (V0 ) | every finite subset of Φ is in ∇}.
2. Now suppose that Φ ∈ ∇. ∇ is closed under subsets, so every finite subset of Φ is in ∇
and thus Φ ∈ ∇′ . Hence ∇ ⊆ ∇′ .
3. Next let us show that ∇′ is compact.
3.1. Suppose Φ ∈ ∇′ and Ψ is an arbitrary finite subset of Φ.
3.2. By definition of ∇′ all finite subsets of Φ are in ∇ and therefore Ψ ∈ ∇′ .
3.3. Thus all finite subsets of Φ are in ∇′ whenever Φ is in ∇′ .
3.4. On the other hand, suppose all finite subsets of Φ are in ∇′ .
3.5. Then by the definition of ∇′ the finite subsets of Φ are also in ∇, so Φ ∈ ∇′ . Thus
∇′ is compact.
5. Note that ∇′ is closed under subsets by the Lemma above.
6. Now we show that if ∇ satisfies ∇∗ , then ∇′ does too.
6.1. To show ∇c , let Φ ∈ ∇′ and suppose there is an atom A, such that {A, ¬A} ⊆ Φ.
Then {A, ¬A} ∈ ∇ contradicting ∇c .
6.2. To show ∇¬ , let Φ ∈ ∇′ and ¬¬A ∈ Φ, then Φ∗A ∈ ∇′ .
A.2. ABSTRACT CONSISTENCY AND MODEL EXISTENCE FOR PROPOSITIONAL LOGIC709
: 1120 2025-05-14
Hintikka sets are sets of formulae with very strong analytic closure conditions. These are motivated
as maximally consistent sets i.e. sets that already contain everything that can be consistently
added to them.
∇-Hintikka set
Definition A.2.10. Let ∇ be an abstract consistency class, then we call a set H ∈ ∇ a
∇-Hintikka set, iff H is ⊆-maximal in ∇, i.e. for all A with H∗A ∈ ∇ we already have
A ∈ H.
: 1121 2025-05-14
∇-Hintikka set
Proof: We prove the properties in turn
1. Hc goes by induction on the structure of A
1.1. A ∈ V0
Then A ̸∈ H or ¬A ̸∈ H by ∇c .
1.3. A = ¬B
1.3.1. Let us assume that ¬B ∈ H and ¬¬B ∈ H,
1.3.2. then H∗B ∈ ∇ by ∇¬ , and therefore B ∈ H by maximality.
1.3.3. So both B and ¬B are in H, which contradicts the induction hypothesis.
1.5. A = B ∨ C
is similar to the previous case
3. We prove H¬ by maximality of H in ∇.
3.1. If ¬¬A ∈ H, then H∗A ∈ ∇ by ∇¬ .
3.2. The maximality of H now gives us that A ∈ H.
710 APPENDIX A. COMPLETENESS OF CALCULI FOR PROPOSITIONAL LOGIC
: 1122 2025-05-14
The following theorem is one of the main results in the abstract consistency/model-existence
method. For any ∇-consistentset Φ it allows us to construct a ∇-Hintikka setH with Φ ∈ H.
Extension Theorem
Theorem A.2.12. If ∇ is an abstract consistency class and Φ ∈ ∇, then there is a ∇-Hintikka
setH with Φ ⊆ H.
Proof:
1. Wlog. we assume that ∇ is compact (otherwise pass to compact extension)
2. We choose an enumeration A1 , . . . of the set wff 0 (V0 )
3. and construct a sequence of sets Hi with H0 := Φ and
Hn if Hn ∗An ∈
̸ ∇
Hn+1 :=
Hn ∗An if Hn ∗An ∈ ∇
S
4. Note that all Hi ∈ ∇, choose H := i∈N Hi
5. Ψ ⊆ H finite implies there is a j ∈ N such that Ψ ⊆ Hj ,
6. so Ψ ∈ ∇ as ∇ is closed under subsets and H ∈ ∇ as ∇ is compact.
7. Let H∗B ∈ ∇, then there is a j ∈ N with B = Aj , so that B ∈ Hj+1 and Hj+1 ⊆ H
8. Thus H is ∇-maximal
□
: 1123 2025-05-14
Note that the construction in the proof above is non-trivial in two respects. First, the limit
construction for H is not executed in our original abstract consistency class ∇, but in a suitably
extended one to make it compact — the original would not have contained H in general. Second,
the set H is not unique for Φ, but depends on the choice of the enumeration of wff 0 (V0 ). If we pick
a different enumeration, we will end up with a different H. Say if A and ¬A are both ∇-consistent
with Φ, then depending on which one is first in the enumeration H, will contain that one; with all
the consequences for subsequent choices in the construction process.
Valuation
Definition A.2.13. A function ν : wff 0 (V0 ) → D0 is called a (propositional) valuation, iff
ν(¬A) = T, iff ν(A) = F
ν(A ∧ B) = T, iff ν(A) = T and ν(B) = T
Lemma A.2.14. If ν : wff 0 (V0 ) → D0 is a valuation and Φ ⊆ wff 0 (V0 ) with ν(Φ) = {T},
then Φ is satisfiable.
Proof sketch: ν|V0 : V0 → D0 is a satisfying variable assignment.
A.3. A COMPLETENESS PROOF FOR PROPOSITIONAL TABLEAUX 711
: 1124 2025-05-14
Now, we only have to put the pieces together to obtain the model existence theorem we are
after.
Model Existence
Lemma A.2.16 (Hintikka-Lemma). If ∇ is an abstract consistency class and H a ∇-
Hintikka set, then H is satisfiable.
Proof:
1. We define ν(A) := T, iff A ∈ H
2. then ν is a valuation by the Hintikka properties
3. and thus ν|V0 is a satisfying assignment.
□
: 1125 2025-05-14
3.1. For the proof of the contrapositive we assume that Φ∗A has a closed tableau T and
show that already Φ has one:
3.2. Applying each of T0 ¬T and T0 ¬F once allows to extend any tableau branch that contains
¬¬Bα by Bα .
3.3. Any branch in T that is closed with ¬¬Aα , can be closed by Aα .
5. ∇∨
Suppose A ∨ B ∈ Φ and both Φ∗A and Φ∗B have closed tableaux
5.1. Consider the tableaux:
ΨT
ΦT ΦT T
(A ∨ B)
AT BT
Rest1 Rest2 AT BT
Rest1 Rest2
7. ∇∧
Suppose, ¬(A ∨ B) ∈ Φ and Φ{¬A, ¬B} have closed tableau T .
7.1. We consider
ΨT
ΦT F
(A ∨ B)
AF F
A
BF
Rest BF
Rest
where Φ = Ψ∗¬(A ∨ B).
□
: 1127 2025-05-14
Observation: If we look at the completeness proof below, we see that the Lemma above is the
only place where we had to deal with specific properties of the T0 .
So if we want to prove completeness of any other calculus with respect to propositional logic,
then we only need to prove an analogon to this Lemma and can use the rest of the machinery we
have already established “off the shelf”.
This is one great advantage of the “abstract consistency/model-existence method”; the other is
that the method can be applied to other logics as well. In particular, if these logic are extensions,
then we can re-use the work we did already and only cover the additions.
Completeness of T0
Corollary A.3.2. T0 is complete.
Proof: by contradiction
1. We assume that A ∈ wff 0 (V0 ) is valid, but there is no closed tableau for AF .
2. We have {¬A} ∈ ∇ as ¬AT = AF .
3. So ¬A is satisfiable by the model-existence theorem (which is applicable as ∇ is an abstract
consistency class by our Lemma above).
4. This contradicts our assumption that A is valid.
□
: 1128 2025-05-14
Appendix B
P F
T
X1
T F
Xn Xn
T F T F
Q Q Q Q
T F T F T F T F
T T T T T T T T
R ; 2R ; 2R ; 2R ; 2R ; 2R ; 2R ; 2R ; 2
: 1129 2025-05-14
713
714 APPENDIX B. CONFLICT DRIVEN CLAUSE LEARNING
: 1130 2025-05-14
Intuition: The initial vertices are the choice literals and unit clauses of ∆.
: 1131 2025-05-14
1. UP Rule: R 7→ T
Implied literal RT . Implication graph:
P T ∨ QT ; P F ∨ Q F ; P T ∨ Q F
PF
2. Splitting Rule:
2a. P 7→ F
Choice literal P F .
QT ; QF QT
3a. UP Rule: Q 7→ T
Implied literal QT
edges (RT ,QT ) and (P F ,QT ).
2
Conflict vertex 2P T ∨QF RT 2P T ∨QF
edges (P F ,2P T ∨QF ) and (QT ,2P T ∨QF ).
: 1132 2025-05-14
P F
T
X1
T F
Xn Xn
T F T F
Q Q Q Q
T F T F T F T F
T T T T T T T T
R ; 2R ; 2R ; 2R ; 2R ; 2R ; 2R ; 2R ; 2
PT
QT X1 T ... Xn T
RT 2P T ∨QF ∨RT
: 1133 2025-05-14
716 APPENDIX B. CONFLICT DRIVEN CLAUSE LEARNING
∆ := P F ∨ QF ∨ R T ; P F ∨ QF ∨ R F ; P F ∨ QT ∨ R T ; P F ∨ Q T ∨ R F
Θ := X 1T ∨ . . . ∨ X nT ; X 1F ∨ . . . ∨ X nF
DPLL on ∆ ; Θ ; Φ with Φ := QF ∨ S T ; QF ∨ S F
Choice literals: P T , (X 1 T ), . . ., (X n T ), QT . Implied literals:
PT
QT X1 T ... Xn T
RT 2P T ∨QF ∨RT ST 2
: 1134 2025-05-14
It depends on “ordering decisions” during UP: Which unit clause is picked first.
Example B.1.8. ∆ = P F ∨ QF ; QT ; P T
Option 1 Option 2
T
Q PT
2P F ∨QF PF 2P F ∨QF QF
: 1135 2025-05-14
Conflict Graphs
A conflict graph captures “what went wrong” in a failed node.
Definition B.1.9 (Conflict Graph). Let ∆ be a clause set, and let Gimpl
β be the implication
graph for some search branch β of DPLL on ∆. A subgraph C of Gimpl
β is a conflict graph if:
(i) C contains exactly one conflict vertex 2C .
B.1. UP CONFLICT ANALYSIS 717
(ii) If l′ is a vertex in C, then all parents of l′ , i.e. vertices li with a I edge (li ,l′ ), are vertices
in C as well.
(iii) All vertices in C have a path to 2C .
Conflict graph =
b Starting at a conflict vertex, backchain through the implication graph until
reaching choice literals.
: 1136 2025-05-14
PT
QT X1 T ... Xn T
RT 2P T ∨QF ∨RT
: 1137 2025-05-14
∆ := P F ∨ QF ∨ R T ; P F ∨ Q F ∨ R F ; P F ∨ QT ∨ R T ; P F ∨ Q T ∨ R F
Θ := X 1T ∨ . . . ∨ X nT ; X 1F ∨ . . . ∨ X nF
DPLL on ∆ ; Θ ; Φ with Φ := QF ∨ S T ; QF ∨ S F
Choice literals: P T , (X 1 T ), . . ., (X n T ), QT . Implied literals: RT .
718 APPENDIX B. CONFLICT DRIVEN CLAUSE LEARNING
PT
QT X1 T ... Xn T
RT 2P T ∨QF ∨RT ST 2
PT
QT X1 T ... Xn T
RT 2P T ∨QF ∨RT ST 2
: 1138 2025-05-14
Clause Learning
Observation: Conflict graphs encode the entailment relation.
Definition B.2.1. Let ∆ be a clause set, C be a conflict graph at some W
time point during
a run of DPLL on ∆, and L be the choice literals in C, then we call c := l∈L l the learned
clause for C.
Theorem B.2.2. Let ∆, C, and c as in Definition B.2.1, then ∆ ⊨ c.
Idea: We can add learned clauses to DPLL derivations at any time without losing soundness.
(maybe this helps, if we have a good notion of learned clauses)
Definition B.2.3. Clause learning is the process of adding learned clauses to DPLL clause
sets at specific points. (details coming up)
: 1139 2025-05-14
∆ := P F ∨ QF ∨ RT ; P F ∨ QF ∨ RF ; P F ∨ QT ∨ RT ; P F ∨ QT ∨ RF
DPLL on ∆ ; Θ with Θ := X 1 T ∨ . . . ∨ X n T ; X 1 F ∨ . . . ∨ X n F
Choice literals: P T , (X 1 T ), . . ., (X n T ), QT . Implied literals: RT .
PT
QT X1 T ... Xn T
RT 2P T ∨QF ∨RT
Learned clause: P F ∨ QF
: 1140 2025-05-14
Observation: Given the earlier choices l1 , . . . , lk , after we learned the new clause C =
l1 ∨ . . . ∨ lk ∨ l′ , the value of l′ is now set by UP!
So we can continue:
3. We set the opposite choice l′ as an implied literal.
e.g. QF as an implied literal.
4. We run UP and analyze conflicts.
Learned clause: earlier choices only! e.g. C = P F , see next slide.
: 1141 2025-05-14
∆ := P F ∨ QF ∨ R T ; P F ∨ QF ∨ R F ; P F ∨ QT ∨ R T ; P F ∨ Q T ∨ R F
Θ := X 1 T ∨ . . . ∨ X 100 T ; X 1 F ∨ . . . ∨ X 100 F
DPLL on ∆ ; Θ ; Φ with Φ := P F ∨ QF
Choice literals: P T , (X 1 T ), . . ., (X 100 T ), QT . Implied literals: QF , RT .
PT
QF X1 T ... Xn T
RT 2
Learned clause: P F
: 1142 2025-05-14
∆ := P F ∨ QF ∨ RT ; P F ∨ QF ∨ RF ; P F ∨ QT ∨ RT ; P F ∨ QT ∨ RF
DPLL on ∆ ; Θ with Θ := X 1 T ∨ . . . ∨ X n T ; X 1 F ∨ . . . ∨ X n F
P F
T
X1
T
Xn
T
Q
T F set by UP
T
R ;2 RT ; 2
learn P F ∨ QF learn P F
Note: Here, the problem could be avoided by splitting over different variables.
Problem: This is not so in general! (see next slide)
: 1143 2025-05-14
B.2. CLAUSE LEARNING 721
Recall: DPLL =
b tree resolution (from slide 404)
1. in particular: each derived clause C (not in ∆) is derived anew every time it is used.
2. Problem: there are ∆ whose shortest tree resolution proof is exponentially longer than
their shortest (general) resolution proof.
: 1144 2025-05-14
: 1145 2025-05-14
Remarks
Which clause(s) to learn?:
722 APPENDIX B. CONFLICT DRIVEN CLAUSE LEARNING
: 1146 2025-05-14
I promise you’re not gonna find this easy . . . (although it is of course possible: e.g., the
“Pigeon Hole Problem”).
People noticed by the early 90s that, in practice, the DPLL worst case does not tend to
happen.
Modern SAT solvers successfully tackle practical instances where n > 1.000.000.
: 1147 2025-05-14
Difficulty 1: What is the “typical case” in applications? E.g., what is the “average” hardware
verification instance?
Consider precisely defined random distributions instead.
Difficulty 2: Search trees get very complex, and are difficult to analyze mathematically,
even in trivial examples. Never mind examples of practical relevance . . .
The most successful works are empirical. (Interesting theory is mainly concerned with
hand-crafted formulas, like the Pigeon Hole Problem.)
B.3. PHASE TRANSITIONS 723
: 1148 2025-05-14
: 1149 2025-05-14
: 1150 2025-05-14
724 APPENDIX B. CONFLICT DRIVEN CLAUSE LEARNING
: 1151 2025-05-14
: 1152 2025-05-14
: 1153 2025-05-14
Appendix C
We will now analyze the first-order calculi for completeness. Just as in the case of the propositional
calculi, we prove a model existence theorem for the first-order model theory and then use that
for the completeness proofs1 . The proof of the first-order model existence theorem is completely EdN:1
analogous to the propositional one; indeed, apart from the model construction itself, it is just an
extension by a treatment for the first-order quantifiers.2 EdN:2
Abstract Consistency
Definition C.1.1. A collection ∇ ⊆ wff o (Σι , Vι ) of sets of formulae is called a first-order
abstract consistency class (ACC1 ), iff it is a ACC0 and additionally
∇∀ ) If ∀X.A ∈ Φ, then Φ∗([B/X](A)) ∈ ∇ for each closed term B.
∇∃ ) If ¬(∀X.A) ∈ Φ and c is an individual constant that does not occur in Φ, then
Φ∗¬([c/X](A)) ∈ ∇
Example C.1.2. The collection {∅, {∀x.p(x)}} is an ACC1 . (no closed terms)
Example C.1.3. The collection Φ := {∅, {p(a)}, {∀x.p(x)}} is not an ACC1 .
⇝ {p(a), ∀x.p(x)} is missing from Φ.
Example C.1.4. The collection Φ := {∅, {∃x.p(x)}} is not an ACC1 .
⇝ {p(c), ∃x.p(x)} is missing from Φ or some individual constant c
: 1154 2025-05-14
Again, the conditions are very natural: Take for instance ∇∀ , it says that if a set Φ that contains
a sentence ¬(∀X.A) is “consistent”, then we should be able to extend it by ¬([c/X](A)) for any
1 EdNote: reference the theorems
2 EdNote: MK: what about equality?
725
726 APPENDIX C. COMPLETENESS OF CALCULI FOR FIRST-ORDER LOGIC
new individual constant c without losing this property; in other words, a complete calculus should
be able to recognize ¬(∀X.A) and ¬([c/X](A)) to be equivalent.
: 1155 2025-05-14
Hintikka sets are sets of sentences with very strong analytic closure conditions. These are motivated
as maximally consistent sets i.e. sets that already contain everything that can be consistently
added to them.
∇-Hintikka set
Theorem C.1.6 (Hintikka Properties). Let ∇ be a ACC1 and H be a ∇-Hintikka set, then
H has all the propositional Hintikka properties plus
H∀ ) If ∀X.A ∈ H, then [B/X](A) ∈ H for each closed term B.
H∃ ) If ¬(∀X.A) ∈ H then ¬([B/X](A)) ∈ H for some closed term B.
: 1156 2025-05-14
The following theorem is one of the main results in the abstract consistency/model-existence
method. For any ∇-consistent set Φ it allows us to construct a ∇-Hintikka set H with Φ ∈ H.
C.1. ABSTRACT CONSISTENCY AND MODEL EXISTENCE FOR FIRST-ORDER LOGIC727
Extension Theorem
Theorem C.1.7. If ∇ is a ACC1 and Φ ∈ ∇ finite, then there is a ∇-Hintikka set H with
Φ ⊆ H.
Proof:
1. Wlog. assume that ∇ compact (else use compact extension)
2. Choose an enumeration A1 , . . . of cwff o (Σι ) and c1 , c2 , . . . of Σsk
0 .
: 1157 2025-05-14
Note that the construction in the proof above is non-trivial in two respects. First, the limit
construction for H is not executed in our original abstract consistency class ∇, but in a suitably
extended one to make it compact — the original would not have contained H in general. Second,
the set H is not unique for Φ, but depends on the choice of the enumeration of cwff o (Σι ). If we pick
a different enumeration, we will end up with a different H. Say if A and ¬A are both ∇-consistent
with Φ, then depending on which one is first in the enumeration H, will contain that one; with all
the consequences for subsequent choices in the construction process.
What now?
The next step is to take a ∇-Hintikka set – the extension lemma above gives us one – and
show that it is satisfiable.
Problem: For that we have to conjure a model ⟨A, I ⟩ out of thin air.
Idea 1: Maybe the ∇-Hintikka set will help us with the interpretation
⇝ After all it helped us with the variable assignments in PL0 .
Idea 2: For the universe we use something that is already lying around:
; The set cwff ι (Σ) of closed terms!
Again, the notion of a valuation helps write things down, so we start with that.
: 1158 2025-05-14
728 APPENDIX C. COMPLETENESS OF CALCULI FOR FIRST-ORDER LOGIC
Valuations
Definition C.1.8. A function ν : cwff o (Σι ) → D0 is called a (first-order) valuation, iff ν is a
propositional valuation and
ν(∀X.A) = T, iff ν([B/X](A)) = T for all closed terms B.
Lemma C.1.9. If φ : Vι →U is a variable assignment, then I φ : cwff o (Σι )→D0 is a valuation.
: 1159 2025-05-14
Note: A valuation is a weaker notion of evaluation in first-order logic; the other direction is also
true, even though the proof of this result is much more involved: The existence of a first-order
valuation that makes a set of sentences true entails the existence of a model that satisfies it.
: 1161 2025-05-14
Herbrand-Model
Definition C.1.11. Let Σ := ⟨Σf , Σp ⟩ be a first-order signature, then we call ⟨D, I ⟩ a
C.1. ABSTRACT CONSISTENCY AND MODEL EXISTENCE FOR FIRST-ORDER LOGIC729
: 1162 2025-05-14
Now, we only have to put the pieces together to obtain the model existence theorem we are
after.
Model Existence
Theorem C.1.15 (Hintikka-Lemma). If ∇ is an ACC1 and H a ∇-Hintikka set, then H is
satisfiable.
Proof:
1. we define ν(A):=T, iff A ∈ H,
2. then ν is a valuation by the Hintikka set properties.
3. We have ν(H) = {T}, so H is satisfiable.
□
Proof:
1. There is a ∇-Hintikka set H with Φ ⊆ H (Extension Theorem)
2. We know that H is satisfiable. (Hintikka-Lemma)
3. In particular, Φ ⊆ H is satisfiable.
730 APPENDIX C. COMPLETENESS OF CALCULI FOR FIRST-ORDER LOGIC
: 1163 2025-05-14
: 1164 2025-05-14
This directly yields two important results that we will use for the completeness analysis.
Henkin’s Theorem
Corollary C.2.2 (Henkin’s Theorem). Every ND1 -consistent set of sentences has a model.
Proof:
1. Let Φ be a ND1 -consistent set of sentences.
2. The collection of sets of ND1 -consistent sentences constitute an ACC1 .
3. Thus the model existence theorem guarantees a model for Φ.
□
: 1165 2025-05-14
Now, the completeness result for first-order natural deduction is just a simple argument away.
We also get a compactness theorem (almost) for free: logical systems with a complete calculus are
always compact.
C.3. SOUNDNESS AND COMPLETENESS OF FIRST-ORDER TABLEAUX 731
: 1166 2025-05-14
Soundness of T1f
Lemma C.3.1. Tableau rules transform satisfiable tableaux into satisfiable ones.
Proof:
we examine the tableau rules in turn
1. propositional rules
as in propositional tableaux
3. T1f ∃
by ???
5. T1f⊥
by ??? (substitution value lemma)
7. T1f ∀
7.1. I φ (∀X.A) = T, iff I ψ (A) = T for all a ∈ Dι
7.2. so in particular for some a ∈ Dι ̸= ∅.
□
: 1167 2025-05-14
732 APPENDIX C. COMPLETENESS OF CALCULI FOR FIRST-ORDER LOGIC
The only interesting steps are the cut rule, which can be directly handled by the substitution
value lemma, and the rule for the existential quantifier, which we do in a separate lemma.
Soundness of T1f ∃
where W := free(∀X.A) = {X 1 , . . ., X k }
1. Let T be satisfiable in M := ⟨D, I⟩, then I φ (∀X.A) = F.
We need to find a model M′ that satisfies T ′ (find interpretation for f )
′
4. choose M = ⟨D, I ′ ⟩ with I ′ := I,[g/f ], then by subst. value lemma
: 1168 2025-05-14
This proof is paradigmatic for soundness proofs for calculi with Skolemization. We use the axiom
of choice at the meta-level to choose a meaning for the Skolem constant. Armed with the Model
Existence Theorem for first-order logic (???), the completeness of first-order tableaux is similarly
straightforward. We just have to show that the collection of tableau-irrefutable sentences is an
abstract consistency class, which is a simple proof-transformation exercise in all but the universal
quantifier case, which we postpone to its own Lemma (???).
Completeness of (T1f )
ΨT ΨT
F F
(∀X.A) (∀X.A)
F F
([c/X](A)) ([f (X 1 , . . ., X k )/X](A))
Rest [f (X 1 , . . ., X k )/c](Rest)
□
C.4. SOUNDNESS AND COMPLETENESS OF FIRST-ORDER RESOLUTION 733
: 1169 2025-05-14
So we only have to treat the case for the universal quantifier. This is what we usually call
a “lifting argument”, since we have to transform (“lift”) a proof for a formula θ(A) to one for
A. In the case of tableaux we do that by an induction on the tableau for θ(A) which creates a
tableau-isomorphism to a tableau for A.
Tableau-Lifting
Theorem C.3.5. If Tθ is a closed tableau for a set θ(Φ) of formulae, then there is a closed
tableau T for Φ.
Proof: by induction over the structure of Tθ we build an isomorphic tableau T , and a tableau-
isomorphism ω : T → Tθ , such that ω(A) = θ(A).
only the tableau-substitution rule is interesting.
T F
1. Let (θ(Ai )) and (θ(Bi )) cut formulae in the branch Θiθ of Tθ
2. there is a joint unifier σ of (θ(A1 )) =? (θ(B1 )) ∧ . . . ∧ (θ(An )) =? (θ(Bn ))
3. thus σ ◦ θ is a unifier of A and B
4. hence there is a most general unifier ρ of A1 =? B1 ∧ . . . ∧ An =? Bn
5. so Θ is closed.
□
: 1170 2025-05-14
Again, the “lifting lemma for tableaux” is paradigmatic for lifting lemmata for other refutation
calculi.
Correctness (CNF)
Lemma C.4.1. A set Φ of sentences is satisfiable, iff CNF1 (Φ) is.
Proof: propositional rules and ∀-rule are trivial; do the ∃-rule
F
1. Let (∀X.A) satisfiable in M := ⟨D, I⟩ and free(A) = {X 1 , . . ., X n }
2. I φ (∀X.A) = F, so there is an a ∈ D with I φ,[a/X] (A) = F (only depends on φ|free(A) )
: 1171 2025-05-14
734 APPENDIX C. COMPLETENESS OF CALCULI FOR FIRST-ORDER LOGIC
Resolution (Correctness)
Definition C.4.2. A clause is called satisfiable, iff I φ (A) = α for one of its literals Aα .
Lemma C.4.3. 2 is unsatisfiable
: 1172 2025-05-14
Completeness (R1 )
Theorem C.4.6. R1 is refutation complete.
Proof: ∇ := {Φ | ΦT has no closed tableau} is an abstract consistency class
1. as for propositional case.
2. by the lifting lemma below
F
3. Let T be a closed tableau for ¬(∀X.A) ∈ Φ and ΦT ∗([c/X](A)) ∈ ∇.
F
4. CNF1 (ΦT ) = CNF1 (ΨT ) ∪ CNF1 (([f (X 1 , . . ., X k )/X](A)) )
F
5. ([f (X 1 , . . ., X k )/c](CNF1 (ΦT )))∗([c/X](A)) = CNF1 (ΦT )
6. so R1 : CNF1 (ΦT )⊢D′ 2, where D = [f (X1′ , . . . , Xk′ )/c](D).
□
: 1173 2025-05-14
Definition C.4.8. Let Φ and Ψ be clause sets, then we call a bijection Ω : Φ → Ψ a clause
set isomorphism, iff there is a clause isomorphism ω : C → Ω(C) for each C ∈ Φ.
Lemma C.4.9. If θ(Φ) is set of formulae, then there is a θ-compatible clause set isomorphism
Ω : CNF1 (Φ) → CNF1 (θ(Φ)).
: 1174 2025-05-14
Lifting for R1
C.4. SOUNDNESS AND COMPLETENESS OF FIRST-ORDER RESOLUTION 735
Dθ′ Dθ′′
T F
1. If Dθ ends in ((θ(A)) ∨ (θ(C))) (θ(B)) ∨ (θ(D))
res
(σ(θ(C))) ∨ (σ(θ(B)))
T
then we have (IH) clause isormorphisms ω ′ : AT ∨ C → (θ(A)) ∨ (θ(C)) and ω ′ : BT ∨
T
D → (θ(B)) , θ(D)
AT ∨ C BF ∨ D
2. thus Res where ρ = mgu(A, B) (exists, as σ ◦ θ unifier)
(ρ(C)) ∨ (ρ(B))
□
: 1175 2025-05-14