Logic and Set Theory Basics

In the previous chapters, we introduced algebra, functions, and geometry, all of which focus on "numbers" and "figures."

In this chapter, we will deal with something more fundamental:How to describe "conditions"(logic),How to describe "a collection of things"(set theory).

In machine learning, almost all content involving "probability" and "uncertainty" is fundamentally expressed in set theory; all content involving "conditional judgments" and "algorithm flows" is fundamentally expressed in logic.


Basic logical operations: AND, OR, NOT, IMPLIES

Logical AND (AND, symbol ∧)

is true if and only if p and qare both true。

Intuition: the two conditions must be satisfied at the same time; if either one is missing, it won't work—just like "you get wet only if it rains and you don't have an umbrella."

Logical OR (OR, symbol ∨)

is true as long as p and qat least one of them is true。

The "or" in mathematics is an "inclusive or": when both are true, the whole statement is also true. It does not mean "either/or" in everyday speech.

Logical NOT (NOT, symbol ¬)

It simply flips the truth value of p: when p is true,it is false; when p is false,it is true.

Logical implication (IMPLIES, symbol ⇒)

Read as "if p, then q", it is the one most likely to go against intuition:

p (the antecedent)q (consequent)Explanation
truetruetrueNormal case
truefalsefalseThe only false case: "antecedent true, consequent false"
falsetruetrueIf the antecedent is false, the whole statement is true
falsefalsetrueIf the antecedent is false, the whole statement is true

The two most counterintuitive rows: when p is false, no matter what q is,is judged astrue。

An example to help understand: "If it rains tomorrow (p), I'll bring an umbrella (q)."

If tomorrowdoes not rain(p is false), then no matter whether you bring an umbrella or not, you cannot say the statement is "false"—it simply makes no promise about the "no rain" situation.

Logical equivalence (IFF, symbol ⇔)

Read as "p if and only if q", meaning p and q always have the same truth value (either both true, or both false).

Click the switches below to personally "light up" each combination and observe the results of the four operations.

Interactive demo: truth switches for logic operations
Click the p and q switches to toggle true/false, and the four cards below display the result of each logic operation in real time. Focus on observing that when p is false, p ⇒ q is always true.
p
true
q
true
p ∧ q
true
p ∨ q
true
¬p
false
p ⇒ q
true
Try setting p to "false" and keeping q as "true"—p ⇒ q is still "true". This is the most counterintuitive part of implication.

Why these symbols are important for AI

When reading algorithm pseudocode and conditional judgments in model training (such as the trigger condition for "early stopping"), these are all combinations of logical expressions.

A decision tree model is essentially composed of layers of "if...then..." (implication) judgments.

Many theorems in probability theory make extensive use of logical operations to describe relationships between events during proofs.

Examples

# Print the complete truth table using Python's boolean operations
# Note: Python has no "implication" operator; p ⇒ q is equivalent to (not p) or q

print('p      q      p∧q    p∨q    ¬p     p⇒q')

for p in [True, False]:
    for q in [True, False]:
        implies = (not p) or q     # Implication: the only false case is "p true and q false"
        print(p, q, p and q, p or q, not p, implies)

Executing the above code yields the following output:

p      q      p∧q    p∨q    ¬p     p⇒q
True True True True False True
True False False True False False
False True False True True True
False False False False True True

The second row is that unique "false": p true, q false, the implication does not hold.

Exercise: p = "Today is the weekend" is false, q = "I have to go to work" is true. Please determinethe truth value of.

Click to see the answer

p is false. According to the truth table, no matter what q is,it is true.


Set concepts: intersection, union, subset

What is a set?

A set is a whole made up of "a bunch of definite things", for examplerepresents the set containing the three elements 1, 2, 3.

SymbolMeaningExample
x is an element of set A (belongs to)
x is not an element of set A
Empty set, contains no elements
Universal set, "everything" within the scope of discussionAll possible outcomes of rolling a die

Subset

If every element in set A is also an element of set B, then A is B'ssubset, denoted as。

For example, then。

Union, intersection, difference, complement

design:

OperationSymbolMeaningResult
UnionThe elements of A and B combined (duplicates counted only once)
IntersectionElements that are in both A and B
DifferenceBelongs to A but not to B
ComplementThe part of the universal set U that is not in A, i.e.Depends on U

Correspondence between set operations and logical operations

Set theory and logical operations are actually "two languages for the same thing":

Set languageLogical language

This is also why these two sections are placed in the same chapter: they are two expressions of the same underlying logic.

Click the button to switch set operations and see the highlighted areas in the Venn diagram.

Interactive demo: Venn diagram and set operations
Let U = {1..10}, A = {1,2,3,4,5}, B = {4,5,6,7}. Click the button to switch operations; the orange area is the selected result.
Universal set box U The normal outlines of the two circles A B Highlight layer: displays according to the selected operation

Examples

# Python set operations: one-to-one correspondence with mathematical symbols
A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7}
U = set(range(1, 11))     # Universal set {1, 2, ..., 10}

print(A | B)      # Union A ∪ B
print(A & B)      # Intersection A ∩ B
print(A - B)      # Difference A \ B
print(A ^ B)      # Symmetric difference A △ B (elements in only one of the sets)
print(U - A)      # Complement Ā = U \ A

The output after running the above code is:

{1, 2, 3, 4, 5, 6, 7}
{4, 5}
{1, 2, 3}
{1, 2, 3, 6, 7}
{6, 7, 8, 9, 10}

Exercise:,(Within the range 1~12). Findand。

Click to see the answer


Why probability theory is built on set theory

Events are sets

An "event" in probability theory is essentially a set: the set of all "possible outcomes" that satisfy a certain condition.

For example, when rolling a die, the set corresponding to the event "rolling an even number" is。

Probability operations directly correspond to set operations

Probability LanguageSet LanguageMeaning
A or B occursAt least one of events A and B occurs
Both A and B occurEvents A and B occur simultaneously
A does not occurComplement of A
A and B are mutually exclusiveThe two events cannot occur simultaneously

Addition formula: inclusion-exclusion principle

The geometric intuition of this formula: the overlapping part of two circles is counted twice, so it needs to be subtracted once.

This can be seen very intuitively using a Venn diagram (a graphical representation of sets).

Conditional probability

It is read as "the probability of A occurring given that B has already occurred."

Intuition: once we know B has occurred, the "universe" under discussion shrinks from the original U to B.

At this point, the probability of A occurring is naturally the proportion of "the intersection of A and B" in the "new universe B".

The prototype of Bayes' theorem

Conditional probability can also be written in reverse:

Rearranging this, we obtain the core formula of Bayes' theorem:

It is the theoretical foundation of many machine learning models (such as the naive Bayes classifier), and its derivation starts precisely from the simple set intuition that "conditional probability is the proportion of a set intersection."

The classic disease detection problem best demonstrates the power of Bayes: a test "accuracy of 95%" is not the same as "a 95% probability of being diseased after a positive test." Drag the slider and calculate it yourself.

Interactive demo: Bayes' theorem and disease testing
The 100 dots represent 100 people. Adjust the prevalence rate, test sensitivity, and false positive rate to observe how the proportion of 'actually being sick after testing positive' changes.
Diseased and positive Diseased but not detected Healthy but false positive Healthy and negative
Try raising the prevalence to 1%: even if test sensitivity is as high as 90%, fewer than two in ten of those who test positive may actually have the disease--the large number of false positives drowns out the true positives.

Examples

# Bayes' Theorem: Classic calculation for disease detection
# A = has the disease, B = tests positive

p_a = 0.01       # Prevalence (prior probability)
p_b_given_a = 0.95   # Sensitivity: probability that a diseased person tests positive
p_b_given_na = 0.05  # False positive rate: probability that a healthy person tests positive

# Total probability formula: P(B) = P(B|A)P(A) + P(B|¬A)P(¬A)
p_b = p_b_given_a * p_a + p_b_given_na * (1 - p_a)

# Bayes' theorem: P(A|B) = P(B|A)P(A) / P(B)
p_a_given_b = p_b_given_a * p_a / p_b
print(p_b)          # Total probability of a positive test is approximately 5.9%
print(p_a_given_b)  # Proportion of true positives among positives: only about 16.1%!

The output from running the above code is:

0.059000000000000004
0.16101694915254236

The conclusion is very counterintuitive: the test "accuracy is 95%", but the probability of actually being sick among positive results is only about 16% -- because the prevalence itself is only 1%, a large number of false positives drown out true positives.

This is exactly the value of Bayes' theorem: it tells youhow to use new evidence (test result) to update old beliefs (prevalence), which is also the common intellectual origin of the naive Bayes classifier and Bayesian optimization.

Exercise: In a standard deck of 52 cards, event A = 'draw a heart' (13 cards), event B = 'draw an Ace' (4 cards, 1 of which is the Ace of hearts). Findand。

Click to view answer


Chapter summary

TopicOne-sentence core
Logical operations∧ requires both to be true, ∨ only requires one to be true, ⇒ is false only when "antecedent true and consequent false" (most counterintuitive)
Set operations∪ is union, ∩ is intersection, and they correspond one-to-one with logical operations
Probability and setsEvents are sets; P(A∪B), P(A∩B), and conditional probability can all be intuitively understood using the overlapping relationships of sets
Other extensions