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) returns the set of all actions executable in state s. A transition model describes the result of taking an action in a state: result(s,a) returns the state after performing action a in state s.
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
Start with a frontier containing the initial state.
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), where h(n) estimates the distance from node n 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), where:
g(n) = cost to reach node n from the start
h(n) = heuristic estimate of cost from n to goal
Optimal if 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 s0: how the game begins (e.g., empty board).
Player function player(s): returns which player moves in state s.
Actions actions(s): set of legal moves in state s.
Transition model result(s,a): new state after taking action a.
Terminal test terminal(s): true if the game is over.
Utility function 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).
Initialize v=−∞.
For each action a in actions(s), set v=max(v,min-value(result(s,a))).
Return v.
Min value function:
If terminal, return utility(s).
Initialize v=∞.
For each action a in actions(s), set v=min(v,max-value(result(s,a))).
Return v.
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:
α: the best value found so far for max.
β: the best value found so far for min.
If the current node's value is worse than α (for min) or better than β (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., P, Q, R) represent facts that can be true or false. Logical connectives combine propositions:
Connective | Symbol | Meaning |
|---|---|---|
Not | ¬ | Negation |
And | ∧ | Conjunction |
Or | ∨ | Disjunction |
Implication | → | If...then |
Biconditional | ↔ | If and only if |
Truth tables define the semantics of these connectives. For example, P→Q is false only when P is true and Q 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⊨α) means that in every model where the KB is true, α 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 KB is true in all models where α is true, then KB⊨α. Complexity is exponential in the number of symbols (2n models).
Inference Rules
Rules allow deriving new sentences without enumerating all models. Key rules include:
Modus Ponens: From α→β and α, infer β.
And Elimination: From α∧β, infer α (or β).
Double Negation Elimination: From ¬¬α, infer α.
Implication Elimination: From α→β, infer ¬α∨β.
Biconditional Elimination: From α↔β, infer (α→β)∧(β→α).
De Morgan's Laws:
¬(α∧β)≡¬α∨¬β
¬(α∨β)≡¬α∧¬β
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:
Generalized: given two clauses with complementary literals, resolve them to produce a new clause containing all other literals (with duplicates removed).
To prove KB⊨α by resolution:
Convert KB∧¬α to conjunctive normal form (CNF): a conjunction of clauses.
Repeatedly apply resolution to generate new clauses.
If the empty clause (contradiction) is derived, then KB⊨α.
CNF conversion steps: eliminate biconditionals, eliminate implications, move negations inward (using De Morgan's), distribute ∨ over ∧.
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 ∀: "for all" (e.g., ∀xPerson(x)→∃yHouse(y)∧BelongsTo(x,y))
Existential ∃: "there exists"
Probability and Uncertainty
Basic Probability
A possible world ω has probability 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(B)P(A∧B). This can be rewritten as P(A∧B)=P(B)⋅P(A∣B).
Bayes' rule: 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)
Inclusion-Exclusion: P(A∨B)=P(A)+P(B)−P(A∧B)
Marginalization: P(A)=∑bP(A∧B=b)
Conditioning: P(A)=∑bP(A∣B=b)P(B=b)
Independence: A and B are independent if 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)
Sensor (emission) model: 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 (how much worse) and temperature 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,…,Xn
Domains for each variable
Constraints (e.g., X1=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 X is arc-consistent with Y if every value in X's domain has a compatible value in Y'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 k nearest neighbors.
Perceptron (linear classifier): h(x)=1 if w⋅x+b≥0, else 0. 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+w1x. 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∣ (absolute error).
L2 Loss: (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) estimating the value of taking action a in state s. The update rule:
where α is the learning rate, γ is the discount factor, r is the immediate reward, and s′ is the next state.
Exploration vs. Exploitation: ϵ-greedy selects the best action with probability 1−ϵ and a random action with probability ϵ.
Unsupervised Learning
No labeled data. Common task: clustering.
k-Means Clustering:
Choose k initial cluster centers randomly.
Assign each point to the nearest center.
Recompute each center as the mean of its assigned points.
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), outputs between 0 and 1 (good for probabilities).
ReLU (Rectified Linear Unit): 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:
Computing error at the output layer.
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→NPVP, NP→DN, etc. Parsing with CFGs reveals sentence structure but requires many rules.
N-grams and Markov Models
N-grams are contiguous sequences of n 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.