1. Home
  2. Explore
  3. Computer Science
  4. Introduction to AI with Python

Study methods

Flashcards
Quiz
Fill in the blanks
Written test
Lesson
Notes
Podcast
Content

Introduction to AI with Python

Comprehensive Study Notes: Introduction to Artificial Intelligence with Python

This course explores the concepts and algorithms at the foundation of modern artificial intelligence, including graph search algorithms, classification, optimization, reinforcement learning, neural networks, and natural language processing. The goal is to provide a thorough understanding of how AI can solve problems ranging from game-playing to handwriting recognition to machine translation.


Search Problems

An agent is any entity that perceives its environment and acts upon it. A state is a configuration of the agent in its environment. The initial state is where the agent begins. Actions are choices available in a given state. Formally, actions(s)actions(s)actions(s) returns the set of all actions executable in state sss. A transition model describes the result of taking an action in a state: result(s,a)result(s, a)result(s,a) returns the state after performing action aaa in state sss.

The state space is the set of all states reachable from the initial state via any sequence of actions. This can be visualized as a graph where nodes are states and edges represent actions.

A goal test determines whether a given state is a goal state. A path cost assigns a numerical cost to each path; the objective is to find a solution (a sequence of actions from initial to goal) and ideally an optimal solution (one with the lowest path cost among all solutions).

Node Data Structure

A node stores:

  • state: the current state

  • parent: the node that led to this state (used to reconstruct the path)

  • action: the action taken from parent to current state

  • path cost: the cumulative cost from the initial state to this state

Search Algorithm Pseudocode

  1. Start with a frontier containing the initial state.

  2. Repeat:

    • If the frontier is empty, return failure (no solution).

    • Remove a node from the frontier.

    • If the node contains a goal state, return the solution.

    • Expand the node: consider all neighbors (states reachable by one action) and add them to the frontier.

To avoid infinite loops, maintain an explored set of states already visited. Only add a neighbor to the frontier if it is not already in the frontier and not in the explored set.

Uninformed Search Strategies

Depth-First Search (DFS)

  • Uses a stack (Last-In, First-Out) for the frontier.

  • Explores the deepest node in the frontier first.

  • If a dead end is reached, it backtracks to the last decision point.

  • Complete for finite state spaces, but not optimal (may find a longer path).

  • Memory-efficient compared to BFS in some cases.

Breadth-First Search (BFS)

  • Uses a queue (First-In, First-Out) for the frontier.

  • Explores the shallowest node in the frontier first.

  • Explores all nodes at distance 1 from the start, then distance 2, etc.

  • Complete and optimal for unweighted graphs (equal step costs).

  • May require more memory than DFS.

Informed Search Strategies

Informed search uses problem-specific knowledge (a heuristic) to estimate which node is closest to the goal.

Greedy Best-First Search

  • Expands the node with the smallest heuristic value h(n)h(n)h(n), where h(n)h(n)h(n) estimates the distance from node nnn to the goal.

  • Example heuristic: Manhattan distance (number of vertical and horizontal steps ignoring obstacles).

  • Not optimal: can get stuck in local optima because it only considers immediate heuristic improvement.

A Search

  • Expands the node with the smallest f(n)=g(n)+h(n)f(n) = g(n) + h(n)f(n)=g(n)+h(n), where:

    • g(n)g(n)g(n) = cost to reach node nnn from the start

    • h(n)h(n)h(n) = heuristic estimate of cost from nnn to goal

  • Optimal if h(n)h(n)h(n) is admissible (never overestimates true cost) and consistent (satisfies triangle inequality).

  • Typically uses more memory than greedy best-first.


Adversarial Search (Game-Playing)

In adversarial search, there are two agents with opposing objectives. The most common algorithm is Minimax, used for deterministic two-player games like tic-tac-toe.

Game Definition Components

  • Initial state s0s_0s0​: how the game begins (e.g., empty board).

  • Player function player(s)player(s)player(s): returns which player moves in state sss.

  • Actions actions(s)actions(s)actions(s): set of legal moves in state sss.

  • Transition model result(s,a)result(s, a)result(s,a): new state after taking action aaa.

  • Terminal test terminal(s)terminal(s)terminal(s): true if the game is over.

  • Utility function utility(s)utility(s)utility(s): numerical value for a terminal state (e.g., +1 for win, 0 for draw, -1 for loss).

Minimax Algorithm

The max player (e.g., X) aims to maximize the utility. The min player (e.g., O) aims to minimize it.

  • Max value function:

    • If terminal, return utility(s)utility(s)utility(s).

    • Initialize v=−∞v = -\inftyv=−∞.

    • For each action aaa in actions(s)actions(s)actions(s), set v=max⁡(v,min-value(result(s,a)))v = \max(v, \text{min-value}(result(s, a)))v=max(v,min-value(result(s,a))).

    • Return vvv.

  • Min value function:

    • If terminal, return utility(s)utility(s)utility(s).

    • Initialize v=∞v = \inftyv=∞.

    • For each action aaa in actions(s)actions(s)actions(s), set v=min⁡(v,max-value(result(s,a)))v = \min(v, \text{max-value}(result(s, a)))v=min(v,max-value(result(s,a))).

    • Return vvv.

The optimal action for max is the one that yields the highest min-value.

Optimization: Alpha-Beta Pruning

Alpha-beta pruning eliminates branches that cannot affect the final decision by keeping track of:

  • α\alphaα: the best value found so far for max.

  • β\betaβ: the best value found so far for min.

If the current node's value is worse than α\alphaα (for min) or better than β\betaβ (for max), the remaining subtree is pruned. This significantly reduces computation without affecting the result.

Depth-Limited Minimax and Evaluation Functions

For complex games like chess, the game tree is too large to explore fully. Depth-limited minimax stops after a fixed depth and uses an evaluation function to estimate the utility of non-terminal states. The quality of the AI depends heavily on the evaluation function.


Knowledge Representation and Inference

Propositional Logic

Propositional symbols (e.g., PPP, QQQ, RRR) represent facts that can be true or false. Logical connectives combine propositions:

Connective

Symbol

Meaning

Not

¬\neg¬

Negation

And

∧\land∧

Conjunction

Or

∨\lor∨

Disjunction

Implication

→\rightarrow→

If...then

Biconditional

↔\leftrightarrow↔

If and only if

Truth tables define the semantics of these connectives. For example, P→QP \rightarrow QP→Q is false only when PPP is true and QQQ is false.

A model assigns a truth value to every propositional symbol. A knowledge base (KB) is a set of sentences known to be true. Entailment (KB⊨αKB \models \alphaKB⊨α) means that in every model where the KB is true, α\alphaα is also true. Inference is the process of deriving new sentences from old ones.

Inference Algorithms

Model Checking

Enumerate all possible models (assignments of truth values to symbols). If KBKBKB is true in all models where α\alphaα is true, then KB⊨αKB \models \alphaKB⊨α. Complexity is exponential in the number of symbols (2n2^n2n models).

Inference Rules

Rules allow deriving new sentences without enumerating all models. Key rules include:

  • Modus Ponens: From α→β\alpha \rightarrow \betaα→β and α\alphaα, infer β\betaβ.

  • And Elimination: From α∧β\alpha \land \betaα∧β, infer α\alphaα (or β\betaβ).

  • Double Negation Elimination: From ¬¬α\neg \neg \alpha¬¬α, infer α\alphaα.

  • Implication Elimination: From α→β\alpha \rightarrow \betaα→β, infer ¬α∨β\neg \alpha \lor \beta¬α∨β.

  • Biconditional Elimination: From α↔β\alpha \leftrightarrow \betaα↔β, infer (α→β)∧(β→α)(\alpha \rightarrow \beta) \land (\beta \rightarrow \alpha)(α→β)∧(β→α).

  • De Morgan's Laws:

    • ¬(α∧β)≡¬α∨¬β\neg(\alpha \land \beta) \equiv \neg \alpha \lor \neg \beta¬(α∧β)≡¬α∨¬β

    • ¬(α∨β)≡¬α∧¬β\neg(\alpha \lor \beta) \equiv \neg \alpha \land \neg \beta¬(α∨β)≡¬α∧¬β

Theorem proving can be treated as a search problem where states are sets of known sentences and actions are inference rules.

Resolution

Resolution is a powerful inference rule that works on clauses (disjunctions of literals). The rule:

P∨Q,¬P∨RQ∨R\frac{P \lor Q, \quad \neg P \lor R}{Q \lor R}Q∨RP∨Q,¬P∨R​

Generalized: given two clauses with complementary literals, resolve them to produce a new clause containing all other literals (with duplicates removed).

To prove KB⊨αKB \models \alphaKB⊨α by resolution:

  1. Convert KB∧¬αKB \land \neg \alphaKB∧¬α to conjunctive normal form (CNF): a conjunction of clauses.

  2. Repeatedly apply resolution to generate new clauses.

  3. If the empty clause (contradiction) is derived, then KB⊨αKB \models \alphaKB⊨α.

CNF conversion steps: eliminate biconditionals, eliminate implications, move negations inward (using De Morgan's), distribute ∨\lor∨ over ∧\land∧.

First-Order Logic

First-order logic is more expressive than propositional logic. It includes:

  • Constant symbols: objects (e.g., Minerva, Gryffindor)

  • Predicate symbols: relations or properties (e.g., BelongsTo(Minerva, Gryffindor))

  • Quantifiers:

    • Universal ∀\forall∀: "for all" (e.g., ∀x  Person(x)→∃y  House(y)∧BelongsTo(x,y)\forall x\; Person(x) \rightarrow \exists y\; House(y) \land BelongsTo(x, y)∀xPerson(x)→∃yHouse(y)∧BelongsTo(x,y))

    • Existential ∃\exists∃: "there exists"


Probability and Uncertainty

Basic Probability

A possible world ω\omegaω has probability P(ω)P(\omega)P(ω) between 0 and 1. All possible worlds sum to 1.

Unconditional probability: probability of an event without any evidence.

Conditional probability: P(A∣B)=P(A∧B)P(B)P(A \mid B) = \frac{P(A \land B)}{P(B)}P(A∣B)=P(B)P(A∧B)​. This can be rewritten as P(A∧B)=P(B)⋅P(A∣B)P(A \land B) = P(B) \cdot P(A \mid B)P(A∧B)=P(B)⋅P(A∣B).

Bayes' rule: P(B∣A)=P(A∣B)P(B)P(A)P(B \mid A) = \frac{P(A \mid B) P(B)}{P(A)}P(B∣A)=P(A)P(A∣B)P(B)​. This is fundamental for inference: it allows computing the probability of a cause given an effect.

Random Variables and Distributions

A random variable has a domain of possible values. A probability distribution assigns probabilities to each value. A joint probability distribution gives probabilities for combinations of values of multiple variables.

Key probability rules:

  • Negation: P(¬A)=1−P(A)P(\neg A) = 1 - P(A)P(¬A)=1−P(A)

  • Inclusion-Exclusion: P(A∨B)=P(A)+P(B)−P(A∧B)P(A \lor B) = P(A) + P(B) - P(A \land B)P(A∨B)=P(A)+P(B)−P(A∧B)

  • Marginalization: P(A)=∑bP(A∧B=b)P(A) = \sum_b P(A \land B = b)P(A)=∑b​P(A∧B=b)

  • Conditioning: P(A)=∑bP(A∣B=b)P(B=b)P(A) = \sum_b P(A \mid B = b) P(B = b)P(A)=∑b​P(A∣B=b)P(B=b)

Independence: AAA and BBB are independent if P(A∧B)=P(A)P(B)P(A \land B) = P(A) P(B)P(A∧B)=P(A)P(B).

Bayesian Networks

A Bayesian network is a directed acyclic graph where nodes represent random variables and edges represent dependencies. Each node has a conditional probability distribution given its parents.

Inference in Bayesian networks: given evidence (observed values for some variables), compute the posterior distribution of other variables. Inference by enumeration sums over all hidden variables. Since exact inference can be expensive, approximate inference using sampling is common:

  • Rejection sampling: generate samples from the network, reject those inconsistent with evidence, and count remaining samples.

  • Likelihood weighting: fix evidence variables, sample non-evidence variables, and weight each sample by the probability of the evidence.

Markov Models

Markov assumption: the current state depends only on a finite number of previous states. A Markov chain is a sequence of random variables where each depends only on the previous one, governed by a transition model.

Hidden Markov Models (HMMs)

An HMM has hidden states (not directly observed) and observations (emissions) that depend on the hidden states. It includes:

  • Transition model: P(statet∣statet−1)P(state_t \mid state_{t-1})P(statet​∣statet−1​)

  • Sensor (emission) model: P(observationt∣statet)P(observation_t \mid state_t)P(observationt​∣statet​)

Common tasks:

  • Filtering: given observations up to now, compute distribution for current state.

  • Prediction: given observations up to now, compute distribution for a future state.

  • Smoothing: given observations up to now, compute distribution for a past state.

  • Most likely explanation: given observations, find the most likely sequence of states.


Optimization

Local Search

Local search algorithms maintain a single "current" state and move to a neighbor state. They are useful when the path to the goal is irrelevant.

A state-space landscape plots states against an objective function (to maximize) or cost function (to minimize). The goal is to find a global maximum or global minimum.

Hill Climbing

  • Start at a random state.

  • Repeatedly move to the best neighbor (steepest ascent) until no neighbor is better.

  • Problems: can get stuck at local maxima/minima or plateaus.

  • Variants:

    • Stochastic hill climbing: randomly choose among better neighbors.

    • First-choice hill climbing: move to the first better neighbor found.

    • Random-restart hill climbing: run hill climbing multiple times from random starts.

Simulated Annealing

  • Allows moves to worse states with a probability that decreases over time (temperature).

  • Early on (high temperature), worse moves are more likely, helping escape local optima.

  • Later (low temperature), the algorithm behaves more like hill climbing.

  • The probability of accepting a worse neighbor depends on ΔE\Delta EΔE (how much worse) and temperature TTT: eΔE/Te^{\Delta E / T}eΔE/T.

Linear Programming

Linear programming minimizes (or maximizes) a linear cost function subject to linear constraints (equalities or inequalities). Variables are real numbers. Algorithms like the simplex method and interior-point methods solve these efficiently.

Constraint Satisfaction Problems (CSPs)

A CSP has:

  • Variables X1,X2,…,XnX_1, X_2, \dots, X_nX1​,X2​,…,Xn​

  • Domains for each variable

  • Constraints (e.g., X1≠X2X_1 \neq X_2X1​=X2​)

Backtracking search is a depth-first search that assigns variables one by one, checking consistency, and backtracking when no consistent value remains.

Heuristics improve efficiency:

  • Minimum Remaining Values (MRV): choose the variable with the fewest legal values.

  • Degree heuristic: choose the variable involved in the most constraints.

  • Least Constraining Value: choose the value that rules out the fewest choices for neighboring variables.

Inference (e.g., arc consistency via AC-3 algorithm) reduces domains before or during search. A variable XXX is arc-consistent with YYY if every value in XXX's domain has a compatible value in YYY's domain.


Machine Learning

Supervised Learning

Given input-output pairs (labeled data), learn a function mapping inputs to outputs.

Classification (discrete output)

Nearest Neighbor: classify a new point based on the class of its nearest neighbor. k-Nearest Neighbors: classify based on the majority class among the kkk nearest neighbors.

Perceptron (linear classifier): h(x)=1h(\mathbf{x}) = 1h(x)=1 if w⋅x+b≥0\mathbf{w} \cdot \mathbf{x} + b \geq 0w⋅x+b≥0, else 000. The perceptron learning rule updates weights when misclassifying.

Support Vector Machine (SVM): finds the maximum margin separator (decision boundary with largest distance to nearest points). Works well in high dimensions and can handle non-linearly separable data via kernel tricks.

Regression (continuous output)

Linear regression models the relationship as a line: h(x)=w0+w1xh(x) = w_0 + w_1 xh(x)=w0​+w1​x. The parameters are learned by minimizing a loss function (e.g., squared error).

Loss Functions and Overfitting

  • 0-1 Loss: 0 if correct, 1 if wrong (for classification).

  • L1 Loss: ∣actual−predicted∣|actual - predicted|∣actual−predicted∣ (absolute error).

  • L2 Loss: (actual−predicted)2(actual - predicted)^2(actual−predicted)2 (squared error, penalizes large errors more).

Overfitting: model fits training data too closely and fails to generalize. Solutions:

  • Regularization: add a penalty for model complexity to the cost function.

  • Cross-validation: split data into training and testing sets; use k-fold cross-validation to evaluate generalization.

Reinforcement Learning

An agent learns from rewards (positive) and punishments (negative) by interacting with an environment. Modeled as a Markov decision process (MDP) with states, actions, transition model, and reward function.

Q-learning learns a function Q(s,a)Q(s, a)Q(s,a) estimating the value of taking action aaa in state sss. The update rule:

Q(s,a)←Q(s,a)+α[r+γmax⁡a′Q(s′,a′)−Q(s,a)]Q(s,a) \leftarrow Q(s,a) + \alpha \left[ r + \gamma \max_{a'} Q(s', a') - Q(s,a) \right]Q(s,a)←Q(s,a)+α[r+γmaxa′​Q(s′,a′)−Q(s,a)]

where α\alphaα is the learning rate, γ\gammaγ is the discount factor, rrr is the immediate reward, and s′s's′ is the next state.

Exploration vs. Exploitation: ϵ\epsilonϵ-greedy selects the best action with probability 1−ϵ1-\epsilon1−ϵ and a random action with probability ϵ\epsilonϵ.

Unsupervised Learning

No labeled data. Common task: clustering.

k-Means Clustering:

  1. Choose kkk initial cluster centers randomly.

  2. Assign each point to the nearest center.

  3. Recompute each center as the mean of its assigned points.

  4. Repeat steps 2-3 until convergence.


Neural Networks

An artificial neural network is a mathematical model inspired by biological neurons. A single unit (neuron) computes a weighted sum of its inputs plus a bias, then applies an activation function.

Common activation functions:

  • Step function: 0 if input < 0, else 1.

  • Sigmoid: 1/(1+e−x)1/(1+e^{-x})1/(1+e−x), outputs between 0 and 1 (good for probabilities).

  • ReLU (Rectified Linear Unit): max(0,x)max(0, x)max(0,x).

Single-Layer Network (Perceptron)

A perceptron can only learn linearly separable decision boundaries.

Multilayer Neural Networks

Adding hidden layers allows learning non-linear decision boundaries. A deep neural network has multiple hidden layers.

Backpropagation trains multilayer networks by:

  1. Computing error at the output layer.

  2. Propagating the error backward through the network to update weights using gradient descent.

Gradient descent minimizes loss by iteratively moving weights in the direction of the negative gradient. Variants:

  • Stochastic gradient descent: update after each data point.

  • Mini-batch gradient descent: update after a small batch.

Dropout prevents overfitting by randomly dropping units during training.

Convolutional Neural Networks (CNNs)

Used for image analysis. Key operations:

  • Convolution: apply a filter (kernel) to an image to create a feature map (e.g., edge detection).

  • Pooling: reduce spatial size (e.g., max pooling takes the maximum value in each region).

A typical CNN: Image → Convolution → Pooling → (repeat) → Flatten → Dense layers → Output.

Recurrent Neural Networks (RNNs)

Used for sequence data (text, time series). RNNs have connections that feed back, allowing them to maintain a hidden state across time steps. However, they are difficult to parallelize.

Long Short-Term Memory (LSTM) networks address the vanishing gradient problem and can capture long-term dependencies.

Attention and Transformers

Attention allows the model to focus on relevant parts of the input when generating each output token. The transformer architecture uses self-attention and feed-forward networks, processing all tokens in parallel (enabling efficient training). Transformers are the basis for large language models (e.g., GPT, BERT) and have revolutionized natural language processing.


Natural Language Processing

Natural language processing (NLP) covers tasks like summarization, translation, question answering, text classification, and sentiment analysis.

Syntax and Formal Grammars

Context-free grammars (CFGs) define syntactic rules, e.g., S→NP  VPS \rightarrow NP\; VPS→NPVP, NP→D  NNP \rightarrow D\; NNP→DN, etc. Parsing with CFGs reveals sentence structure but requires many rules.

N-grams and Markov Models

N-grams are contiguous sequences of nnn items from text. They capture statistical patterns (e.g., common word sequences). Markov chains built from n-grams can generate text that mimics the style of the training data.

Text Classification: Naive Bayes

The bag-of-words model represents text as an unordered collection of words. Naive Bayes applies Bayes' rule with the (naive) assumption that word occurrences are independent given the class. Laplace smoothing avoids zero probabilities for unseen words.

Word Representations

One-hot encoding: each word is a vector with a single 1; suffers from high dimensionality and inability to capture similarity.

Distributed representations (e.g., Word2Vec): each word is a dense vector where similar words have similar vectors. Word2Vec learns from contexts: "you shall know a word by the company it keeps." It can capture analogies (e.g., king - man + woman ≈ queen).

Encoder-Decoder Architecture

For sequence-to-sequence tasks (translation, question answering), an encoder processes the input into a context representation (often via an RNN), and a decoder generates the output sequence from that context. Attention allows the decoder to focus on different parts of the input at each step, improving performance.

Transformers

The transformer architecture relies entirely on attention, eliminating recurrence. It uses:

  • Positional encodings to represent word order.

  • Self-attention to relate words within the same sequence.

  • Multi-headed attention to capture multiple relationships.

  • Stacked encoder and decoder layers.

Transformers are highly parallelizable and have become the standard for state-of-the-art NLP models.

Ask anything

We've read this whole study set, so questions about it get the best answers.

FlashcardsQuizFill in the blanksWritten testLessonNotesPodcastContent