AI Comprehensive Notes
AI Comprehensive Notes
MODULES COVERED
Module 1: Fundamentals of Artificial Intelligence
• Problem solving
Formal definition:
AI is a branch of computer science concerned with building intelligent agents that can
perceive their environment and take actions to achieve specific goals.
Artificial intelligence (AI) is a branch of computer science that develops systems capable of
simulating human cognitive processes—such as learning, reasoning, problem-solving,
perception, and decision-making—to perform tasks independently or with minimal
oversight.
Core Goals of AI
• Simulate human reasoning and problem solving
• Build systems that learn from data and improve over time
• Automate complex tasks that require judgment and adaptability
• Enable natural interaction between humans and machines
💡 Key Insight
AI is not just about mimicking humans — it's about creating systems that act rationally and
achieve goals effectively, sometimes surpassing human performance.
Timeline of AI History
Period Era Key Developments
1940s–1950s Foundations Alan Turing proposes the Turing
Test (1950). Warren McCulloch
& Walter Pitts model artificial
neurons (1943). Norbert Wiener
develops Cybernetics. The
modern concept of AI began with
Alan Turing, who asked: Can
machines think?
He proposed the Turing Test as
a way to measure machine
intelligence.
1956 Birth of AI John McCarthy organizes the
Dartmouth Conference — AI is
officially named as a field.
McCarthy, Minsky, Shannon, and
Simon attend.
1956–1974 First AI Summer Early programs like ELIZA
(natural language), DENDRAL
(chemistry), and GPS (General
Problem Solver) are developed.
Optimism is high. Notable
systems:
ELIZA (a simple chatbot)
Shakey the Robot (early mobile
robot)
Limitations in computing power
and data soon became clear.
1974–1980 First AI Winter Funding is cut due to unmet
expectations. Limitations of early
systems become apparent.
DARPA withdraws support.
1980–1987 Expert Systems Boom Rule-based expert systems (e.g.,
MYCIN for medical diagnosis,
XCON for computer
configuration) dominate.
Commercial interest returns.
1987–1993 Second AI Winter Expert systems prove brittle and
expensive to maintain. Funding
dries up again.
1993–2011 AI Resurgence Machine Learning gains traction.
Deep Blue defeats Kasparov in
chess (1997). Statistical
approaches replace rule-based
systems. AI shifted toward
machine learning—systems
that learn from data.
Key milestone: IBM’s Deep Blue
defeated chess champion Garry
Kasparov in 1997.
Advances in:
• Speech recognition
• Computer vision
• Data-driven algorithms
2. Computer Science
• Algorithms and data structures for search and optimization
• Automata theory and computability
• Programming languages: Python, Prolog, Lisp
• Databases for knowledge storage
Cognitive refers to the mental processes of acquiring knowledge and understanding through
thought, experience, and senses, encompassing memory, attention, problem-solving, and
decision-making.
Psychology refers to the study of how the brain works, how people think, and why they act in
certain ways.
• Models of human memory, learning, and reasoning
• Gestalt psychology influencing pattern recognition: . Its core philosophy, often
summarized as "the whole is different than the sum of its parts," posits that the brain
naturally organizes sensory information into patterns, shapes, and meaningful wholes,
rather than collecting isolated elements.
• Cognitive architectures like:
ACT-R (Adaptive Control of Thought-Rational): ACT-R is strongly rooted in cognitive
psychology (modeling human behavior)
SOAR (Security Orchestration, Automation, and Response): rooted in artificial
intelligence (building intelligent agents)
4. Neuroscience
Neuroscience is the scientific study of the nervous system, including the brain, spinal cord,
and neural networks, spanning from molecular levels to behavior. It explores the structure,
function, development, and pathology of the nervous system, aiming to understand how it
regulates emotions, thoughts, behaviors, and body functions.
5. Philosophy
is the systematic study of ideas and issues, a reasoned pursuit of fundamental truths, a quest
for a comprehensive understanding of the world.
• Epistemology: the nature of knowledge and belief
• Ethics: AI safety, bias, fairness
• Philosophy of mind: can machines be conscious?
• Searle's Chinese Room argument challenges strong AI
6. Linguistics
the scientific study of language, focusing on its structure, use, development, and cognitive
basis, rather than just learning to speak multiple languages
Phonetics & Phonology: The study of speech sounds, their physical production, and
patterns.
1. Expert Systems
•
Definition
An expert system is an AI program that simulates the decision-making ability of a human
expert in a specific domain.
Components:
• Knowledge Base → Contains facts and rules
• Inference Engine → Applies logical rules to data
• User Interface → Allows interaction with users
How it Works:
1. User inputs a problem
2. System searches knowledge base
3. Inference engine applies rules
4. System produces a solution
Applications:
• Medical diagnosis (e.g., disease identification)
• Financial advisory systems
• Technical troubleshooting
Advantages:
• Consistent decisions
• Available 24/7
• Reduces need for human experts
Limitations:
• Expensive to develop
• Limited to specific knowledge domain
Semi-supervised learning can be defined as a type of machine learning that shares features
with both supervised and unsupervised learning. In this method, the training is performed on
a small amount of labelled data collected through the proposed label propagation method and
a large number of unlabeled data. This is especially beneficial when labelling data is either
expensive or requires a lot of time.
The components of the model improve the learning from the labelled examples and, in the
same process, enhance its ability to generalize based on the information provided in the
unlabeled data samples. Other areas that semi-supervised learning can be used include image
classification, text categorization, and speech recognition, where it is difficult to get labelled
data.
It works best when unlabeled data looks like the labeled set. If the data shifts, the model may
learn the wrong patterns and must be monitored.
This type of learning is useful in situations like playing games, controlling robots, or
running automated systems, where the AI needs to make smart decisions and adapt to its
surroundings.
Categories of Reinforcement Learning
Reinforcement learning can be categorized into:
• Positive Reinforcement Learning: It is a way to teach AI by rewarding good
behavior. When the AI does something correctly, it gets a reward, which strengthens
the connection between the action and the desired outcome. This makes the AI more
likely to repeat the same behavior in the future because it learns that it leads to a
positive result. Some of the most used examples include offering a treat to the pet
after obedience and offering the player a bonus, for example, after scoring a goal in a
game to ensure that they continue doing the right thing or, in this case, scoring
positive results in the game.
• Negative Reinforcement Learning: Negative Reinforcement Learning is when an AI
learns to do something because it stops a bad or uncomfortable thing from happening.
For example, a student might read to avoid getting a bad grade, or a gamer might
playto avoid losing. This type of learning doesn’t punish the AI but instead encourages
it to repeat the behavior by removing the unpleasantness. It’s like the AI learns to do
something because it makes a bad feeling go away.
Applications of Reinforcement Learning
Some of the applications of reinforcement learning are:
• Autonomous Vehicles: Self-driving cars utilize reinforcement learning so as to move
around and respond to their surroundings. It enables the vehicle to figure out the best
strategy through simulation of other driving situations and in response to feedback in
the form of signals from sensors and the surroundings.
• Robotics: Reinforcement learning opens the way to the acquisition of complex tasks
by robots, for example, through interactive learning as a process based on practice.
This approach is used in robotic grasping, manipulation, and navigation to enable the
robot to increase its performance in real-time.
• Game Playing: Reinforcement learning has been highly successful in game playing
and is especially evident in games such as AlphaGo, where AI programs carry out
many games to come up with a strategy that would better that of human beings.
• Healthcare: Reinforcement learning frameworks work to enhance the plan of
treatment with respect to the patient responses over time so that it may enhance
patient health outcomes in the case of chronic disease management and clinical
decisions.
• Finance and Trading: RL is used in finance for algorithmic trading, portfolio
optimization, and for evaluating risks. These models learn to buy or sell in accordance
with market conditions to maximize profit and, at the same time, minimize the risks.
3. Natural Language Processing (NLP)
•
•
Definition
Natural Language Processing enables computers to understand, interpret, and generate
human language.
Components:
• Syntax analysis
• Semantic analysis
• Speech recognition
Applications:
• Chatbots
• Language translation
• Voice assistants (e.g., Siri)
• Sentiment analysis
Advantages:
• Improves human-computer interaction
• Automates communication
Limitations:
• Language ambiguity
• Context understanding challenges.
4. Gaming
Definition
AI in gaming is used to create intelligent behaviors in non-player characters (NPCs) and
simulate realistic environments.
Applications:
• NPC decision making
• Pathfinding algorithms
• Strategy development
Example:
• Deep Blue defeating a world chess champion
Advantages:
• Realistic gameplay
• Adaptive difficulty levels
Limitations:
• High computational cost
Definition
Artificial Neural Networks are computing systems inspired by the human brain, designed
to recognize patterns and solve complex problems.
Structure:
• Input Layer
• Hidden Layers
• Output Layer
Applications:
• Image recognition
• Speech recognition
• Medical diagnosis
Key Concept:
• Uses weighted connections and activation functions
Advantages:
• High accuracy
• Learns complex patterns
Limitations:
• Requires large data
• Difficult to interpret (black box problem)
6. Computer Vision
•
Definition
Computer Vision enables machines to interpret and understand visual information from
the world.
Applications:
• Facial recognition
• Object detection
• Medical image analysis
• Autonomous vehicles
Techniques:
• Image processing
• Pattern recognition
• Deep learning
Advantages:
• High-speed image analysis
• Improves automation
Limitations:
• Sensitive to image quality
• Requires large datasets
Environment Properties
• Fully vs Partially Observable: Can the agent see the complete state?
• Deterministic vs Stochastic: Does the same action always produce the same result?
• Episodic vs Sequential: Are actions independent or do they depend on past actions?
• Static vs Dynamic: Does the environment change while the agent is thinking?
• Discrete vs Continuous: Are states and actions countable or real-valued?
• Single vs Multi-Agent: Is the agent alone or competing/cooperating with others?
Laws of Logic
• De Morgan's Laws: ¬(P∧Q) ≡ ¬P∨¬Q and ¬(P∨Q) ≡ ¬P∧¬Q
• Contrapositive: P→Q ≡ ¬Q→¬P
• Double Negation: ¬¬P ≡ P
• Commutativity: P∧Q ≡ Q∧P and P∨Q ≡ Q∨P
• Associativity: (P∧Q)∧R ≡ P∧(Q∧R)
• Distributivity: P∧(Q∨R) ≡ (P∧Q)∨(P∧R)
Quantifiers
• Universal Quantifier (∀): 'For all x'. Example: ∀x Student(x) → Works_Hard(x) — 'All
students work hard'
• Existential Quantifier (∃): 'There exists x'. Example: ∃x Loves(John, x) — 'John loves
someone'
• Nested Quantifiers: ∀x ∃y Loves(x, y) — 'Everyone loves someone'
💡 Propositional vs Predicate Logic
Propositional: 'Socrates is mortal' (P)
Predicate: Mortal(Socrates) — can express: ∀x Human(x) → Mortal(x); Human(Socrates) ⊢
Mortal(Socrates)
1. Deductive Inference
Derives specific conclusions from general rules. If the premises are true, the conclusion must
be true.
Form: Premise 1 + Premise 2 → Conclusion
All mammals breathe air. (General rule)
Dogs are mammals. (Specific fact)
∴ Dogs breathe air. (Conclusion — necessarily true)
2. Inductive Inference
Derives general rules from specific observations. Conclusions are probable, not certain.
Observation 1: This crow is black.
Observation 2: That crow is black.
Observation 3: Every crow I've seen is black.
∴ All crows are black. (Probable but not guaranteed)
3. Abductive Inference
Inference to the best explanation. Given an observation, finds the most plausible explanation.
Observation: The ground is wet.
Possible explanations: It rained, a pipe burst, sprinklers ran.
∴ The best explanation is: It rained. (Most plausible)
4. Analogical Inference
Reasoning by drawing parallels between similar situations.
Situation A: Drug X cured disease Y in mice.
Analogy: Mice and humans have similar biology.
∴ Drug X might also cure disease Y in humans.
6. Non-Monotonic Reasoning
Conclusions can be revised when new information is added (unlike deductive logic where
conclusions are fixed).
• Default logic: Assume X unless there is evidence to the contrary
• Example: 'Tweety is a bird → Tweety can fly' (revised if Tweety is a penguin)
7. Probabilistic Inference
Handles uncertainty using probability theory.
• Bayes' Theorem: P(A|B) = P(B|A) × P(A) / P(B)
• Bayesian networks: graphical models of probabilistic relationships
• Used in: spam filters, medical diagnosis, speech recognition
Key ML Concepts
• Training Data: The dataset used to learn patterns
• Features: Input variables used for prediction
• Labels/Targets: Output values the model tries to predict
• Model: Mathematical function mapping inputs to outputs
• Training: Process of adjusting model parameters to minimize error
• Testing: Evaluating model on unseen data
• Overfitting: Model memorizes training data, fails on new data
• Underfitting: Model is too simple to capture the underlying pattern
• Generalization: Ability to perform well on unseen data
💡 ML vs Traditional Programming
Traditional Programming: Data + Rules → Output
Machine Learning: Data + Output → Rules (learns the rules automatically)
2. Unsupervised Learning
The algorithm finds patterns in unlabeled data — no correct answers are provided.
• Clustering: Group similar data points. Examples: customer segmentation, document
grouping
• Dimensionality Reduction: Reduce features while preserving information. Examples: PCA,
t-SNE, autoencoders
• Association Rule Mining: Find co-occurrence patterns. Example: market basket analysis
('people who buy X also buy Y')
• Common algorithms: K-Means, DBSCAN, Hierarchical Clustering, PCA, Apriori,
Autoencoders
4. Semi-Supervised Learning
Uses a small amount of labeled data combined with a large amount of unlabeled data.
• Practical when labeling data is expensive or time-consuming
• Examples: Medical imaging (few labeled scans, many unlabeled ones), web page
classification
5. Self-Supervised Learning
A special case where labels are automatically generated from the input data itself.
• The model predicts part of the input from other parts
• Examples: BERT predicts masked words; GPT predicts the next word
• Enables training on massive amounts of unlabeled data
6. Transfer Learning
A pre-trained model (trained on large datasets) is fine-tuned for a specific task.
• Reduces the need for large task-specific datasets
• Examples: Using ImageNet-trained ResNet for medical imaging; using GPT for customer
service
Installation Steps
• Step 1: Go to [Link] and download the latest stable
Python 3.x release.
• Step 2: Run the installer. On Windows, check 'Add Python to PATH'.
• Step 3: Verify installation:
python --version
pip --version
# Activate (Windows)
myenv\Scripts\activate
# Activate (Mac/Linux)
source myenv/bin/activate
# Install packages
pip install numpy pandas scikit-learn matplotlib jupyter
Jupyter Notebook
• Interactive web-based IDE for writing and running Python code in cells
• Ideal for data exploration, visualization, and AI experiments
pip install jupyter
jupyter notebook # Launch in browser
# Print statement
print("Hello, Artificial Intelligence!")
# String formatting
print(f"Name: {name}, Age: {age}") # f-strings (Python 3.6+)
print("Pi is approximately %.2f" % pi)
# Multiple assignment
x, y, z = 1, 2, 3
a = b = c = 0 # All equal to 0
Python Keywords
Reserved words that cannot be used as variable names: if, else, elif, for, while, break,
continue, def, class, return, import, from, True, False, None, and, or, not, in, is, try, except,
finally, with, as, lambda, yield, pass, raise, del, global, nonlocal, assert
# Floats
pi = 3.14159
sci = 2.5e-3 # Scientific notation
# Complex numbers
c = 3 + 4j
# Strings
s1 = 'Hello'
s2 = "World"
s3 = '''Multi
line'''
# Booleans
is_true = True
is_false = False
# None type
nothing = None
# Type checking
print(type(42)) # <class 'int'>
print(type(3.14)) # <class 'float'>
print(type("hello")) # <class 'str'>
print(type(True)) # <class 'bool'>
Collections
# List — ordered, mutable, allows duplicates
fruits = ["apple", "banana", "cherry"]
[Link]("mango") # Add item
[Link]("banana") # Remove item
fruits[0] = "grape" # Modify item
print(fruits[1:3]) # Slicing
String Operations
s = "Hello, World!"
# Methods
print([Link]()) # HELLO, WORLD!
print([Link]()) # hello, world!
print([Link](", ")) # ['Hello', 'World!']
print([Link]("World", "AI")) # Hello, AI!
print([Link]()) # Remove whitespace
print(len(s)) # Length: 13
print([Link]("He")) # True
print([Link]("World")) # Index: 7
# String slicing
print(s[0:5]) # Hello
print(s[-6:]) # World!
print(s[::-1]) # Reverse string
print(f"Grade: {grade}")
# Ternary (one-line) if
result = "Pass" if score >= 50 else "Fail"
# Nested conditions
x, y = 5, 10
if x > 0:
if y > 0:
print("Both positive")
Loops
# For loop — iterating over sequence
for i in range(5): # 0, 1, 2, 3, 4
print(i)
# While loop
count = 0
while count < 5:
print(count)
count += 1
Exception Handling
try:
num = int(input("Enter a number: "))
result = 100 / num
print(f"Result: {result}")
except ValueError:
print("Invalid input — not a number!")
except ZeroDivisionError:
print("Cannot divide by zero!")
except Exception as e:
print(f"Unexpected error: {e}")
else:
print("No errors occurred")
finally:
print("This always runs")
# Raising exceptions
def validate_age(age):
if age < 0:
raise ValueError("Age cannot be negative")
return age
print(greet("Alice"))
# Default parameters
def power(base, exponent=2):
return base ** exponent
print(power(3)) # 9
print(power(3, 3)) # 27
print(sum_all(1, 2, 3, 4, 5)) # 15
# Higher-order functions
numbers = [1, 2, 3, 4, 5, 6]
evens = list(filter(lambda x: x % 2 == 0, numbers)) # [2,4,6]
squares = list(map(lambda x: x**2, numbers)) # [1,4,9,16,25,36]
# Recursion
def factorial(n):
if n <= 1:
return 1
return n * factorial(n - 1)
print(factorial(5)) # 120
# Constructor
def __init__(self, name, sound):
[Link] = name # Instance variable
[Link] = sound
# Instance method
def speak(self):
return f"{[Link]} says {[Link]}"
# String representation
def __str__(self):
return f"Animal({[Link]})"
# Class method
@classmethod
def get_kingdom(cls):
return [Link]
# Static method
@staticmethod
def breathes():
return True
# Instantiation
dog = Animal("Dog", "Woof")
cat = Animal("Cat", "Meow")
print([Link]()) # Dog says Woof
print(Animal.get_kingdom()) # Animalia
# Inheritance
class Dog(Animal):
def __init__(self, name, breed):
super().__init__(name, "Woof") # Call parent constructor
[Link] = breed
def fetch(self):
return f"{[Link]} fetches the ball!"
# Multiple inheritance
class Pet:
def __init__(self, owner):
[Link] = owner
def get_owner(self):
return [Link]
# Encapsulation
class BankAccount:
def __init__(self, balance):
self.__balance = balance # Private attribute
def get_balance(self):
return self.__balance
@property
def balance(self): # Property decorator
return self.__balance
3.7 Scientific Modules in Python
NumPy — Numerical Computing
import numpy as np
# Arrays
a = [Link]([1, 2, 3, 4, 5])
b = [Link]([[1,2,3],[4,5,6]]) # 2D array
# Properties
print([Link]) # (5,)
print([Link]) # (2, 3)
print([Link]) # int64
# Array creation
zeros = [Link]((3, 3))
ones = [Link]((2, 4))
eye = [Link](3) # Identity matrix
rand = [Link](3, 3) # Random 3x3
seq = [Link](0, 10, 0.5) # Like range but supports floats
lin = [Link](0, 1, 50) # 50 evenly spaced points
# Operations (element-wise)
x = [Link]([1,2,3])
y = [Link]([4,5,6])
print(x + y) # [5 7 9]
print(x * y) # [4 10 18]
print([Link](x, y)) # Dot product: 32
print(x ** 2) # [1 4 9]
# Matrix operations
A = [Link]([[1,2],[3,4]])
print([Link](A)) # Determinant: -2
print([Link](A)) # Inverse
eigenvalues, eigenvectors = [Link](A)
# Statistical functions
data = [Link]([23, 45, 12, 67, 34, 89, 56])
print([Link](data)) # Mean
print([Link](data)) # Standard deviation
print([Link](data)) # Median
print([Link](data), [Link](data))
# Series
s = [Link]([10, 20, 30, 40], index=['a','b','c','d'])
# DataFrame
data = {
'Name': ['Alice', 'Bob', 'Carol', 'David'],
'Age': [25, 30, 35, 28],
'Score': [85, 92, 78, 95]
}
df = [Link](data)
# Exploration
print([Link]()) # First 5 rows
print([Link]()) # Column types and non-null counts
print([Link]()) # Statistical summary
# Selecting data
print(df['Name']) # Select column
print(df[['Name', 'Score']]) # Multiple columns
print([Link][0]) # Row by label
print([Link][1:3]) # Rows by position
print(df[df['Score'] > 80]) # Filter rows
# Data manipulation
df['Grade'] = df['Score'].apply(lambda x: 'A' if x>=90 else 'B')
df.sort_values('Score', ascending=False, inplace=True)
[Link]('Age', axis=1, inplace=True)
# Reading/writing files
# df = pd.read_csv('[Link]')
# df.to_csv('[Link]', index=False)
# df = pd.read_excel('[Link]')
Matplotlib — Visualization
import [Link] as plt
import numpy as np
# Line plot
x = [Link](0, 2*[Link], 100)
[Link](figsize=(10, 4))
[Link](x, [Link](x), label='sin(x)', color='blue')
[Link](x, [Link](x), label='cos(x)', color='red', linestyle=' --')
[Link]('Trigonometric Functions')
[Link]('x')
[Link]('y')
[Link]()
[Link](True)
[Link]()
# Bar chart
categories = ['A', 'B', 'C', 'D']
values = [23, 45, 12, 67]
[Link](categories, values, color=['blue','red','green','orange'])
[Link]('Category Values')
[Link]()
# Scatter plot
x = [Link](100)
y = 2*x + [Link](100)
[Link](x, y, alpha=0.5)
[Link]()
# Histogram
data = [Link](0, 1, 1000)
[Link](data, bins=30, edgecolor='black')
[Link]()
# Subplots
fig, axes = [Link](2, 2, figsize=(10, 8))
axes[0,0].plot(x, [Link](x))
axes[0,1].plot(x, [Link](x))
plt.tight_layout()
[Link]()
# Statistics
data = [2,4,4,4,5,5,7,9]
mean, std = [Link](data), [Link](data)
t_stat, p_value = stats.ttest_1samp(data, 5) # One-sample t-test
# Optimization
def f(x): return (x-3)**2 + 2
result = [Link](f, x0=0)
print(result.x) # [3.] — minimum at x=3
# Integration
result, error = [Link](lambda x: x**2, 0, 1)
print(result) # 0.333...
MODULE 4: DEVELOPING AI PROGRAMS USING PYTHON
Key Features
• Consistent API: All models follow fit() → predict() pattern
• Wide algorithm coverage: classification, regression, clustering, dimensionality reduction
• Preprocessing tools: scaling, encoding, imputation
• Model evaluation: cross-validation, metrics, confusion matrices
• Pipeline support: chain preprocessing and models together
Installation
pip install scikit-learn
Scikit-Learn Ecosystem
Module Purpose
[Link] Built-in datasets (iris, digits, boston, breast_cancer,
wine)
[Link] Scaling (StandardScaler, MinMaxScaler), encoding
(LabelEncoder, OneHotEncoder)
sklearn.model_selection train_test_split, cross_val_score, GridSearchCV,
KFold
sklearn.linear_model LinearRegression, LogisticRegression, Ridge, Lasso
[Link] DecisionTreeClassifier, DecisionTreeRegressor
[Link] RandomForestClassifier,
GradientBoostingClassifier, AdaBoostClassifier
[Link] KNeighborsClassifier, KNeighborsRegressor
sklearn.naive_bayes GaussianNB, MultinomialNB, BernoulliNB,
ComplementNB
[Link] SVC, SVR, LinearSVC
[Link] KMeans, DBSCAN, AgglomerativeClustering
[Link] PCA, NMF, TruncatedSVD
[Link] accuracy_score, confusion_matrix,
classification_report, roc_auc_score,
mean_squared_error
[Link] Pipeline — chain steps together
sklearn.neural_network MLPClassifier, MLPRegressor
# Step 5: Evaluate
y_pred = [Link](X_test)
print(f"Accuracy: {accuracy_score(y_test, y_pred):.2f}")
print(classification_report(y_test, y_pred,
target_names=data.target_names))
Cross-Validation
from sklearn.model_selection import cross_val_score, StratifiedKFold
param_grid = {
'max_depth': [3, 5, 7, None],
'min_samples_split': [2, 5, 10],
'criterion': ['gini', 'entropy']
}
grid_search = GridSearchCV(
DecisionTreeClassifier(random_state=42),
param_grid,
cv=5,
scoring='accuracy',
n_jobs=-1
)
grid_search.fit(X_train, y_train)
print(f"Best parameters: {grid_search.best_params_}")
print(f"Best CV score: {grid_search.best_score_:.3f}")
4.2 Machine Learning with K-Nearest Neighbours (KNN)
K-Nearest Neighbours (KNN) is one of the simplest and most intuitive machine learning
algorithms. It is a non-parametric, instance-based learning algorithm — it makes no
assumptions about the underlying data distribution.
Core Principle
To classify a new data point, KNN finds the K closest training examples (neighbours) in the
feature space and assigns the majority class among those neighbours. For regression, it
averages their values.
Distance Metrics
• Euclidean Distance (most common): √(Σ(xᵢ - yᵢ)²) — straight-line distance
• Manhattan Distance: Σ|xᵢ - yᵢ| — sum of absolute differences
• Minkowski Distance: (Σ|xᵢ - yᵢ|^p)^(1/p) — generalization (p=2: Euclidean, p=1:
Manhattan)
• Cosine Similarity: used for text and high-dimensional data
• Hamming Distance: used for categorical features
Choosing K
• Small K (e.g., K=1): High variance, low bias, sensitive to noise, overfitting
• Large K: Low variance, high bias, smoother boundaries, underfitting
• Rule of thumb: Start with K = √n (n = number of training samples)
• Best practice: Use cross-validation to find optimal K
• Always try odd K for binary classification to avoid ties
💡 Effect of K on Decision Boundaries
K=1: Very jagged boundary — memorizes training data
K=5: Smoother boundary — good balance
K=N (all data): Always predicts the majority class
# Predictions
y_pred = [Link](X_test_scaled)
y_prob = knn.predict_proba(X_test_scaled) # Probabilities
# Evaluation
print(f"\nAccuracy: {accuracy_score(y_test, y_pred) * 100:.2f}%")
print("\nClassification Report:")
print(classification_report(y_test, y_pred,
target_names=iris.target_names))
# Confusion Matrix
cm = confusion_matrix(y_test, y_pred)
print("\nConfusion Matrix:")
print(cm)
KNN Regression
from [Link] import KNeighborsRegressor
from [Link] import fetch_california_housing
from [Link] import mean_squared_error, r2_score
Bayes' Theorem
The theorem describes how to update probabilities based on evidence:
P(Class | Features) = P(Features | Class) × P(Class)
─────────────────────────────────
P(Features)
Where:
P(Class | Features) = Posterior probability (what we want)
P(Features | Class) = Likelihood (probability of features given class)
P(Class) = Prior probability (base rate of class)
P(Features) = Evidence (normalizing constant)
Decision Rule:
Predicted Class = argmax_c [P(Class=c) × ∏ P(fᵢ | Class=c)]
Why 'Naïve'?
The algorithm assumes features are independent given the class. For example, in spam
detection, it assumes the word 'free' and the word 'win' are independent given that an email
is spam. This is rarely true in reality, but the algorithm works surprisingly well despite this
simplification.
# GaussianNB does NOT require feature scaling (it estimates its own
parameters)
gnb = GaussianNB(var_smoothing=1e-9) # var_smoothing adds small value to
avoid zero variance
[Link](X_train, y_train)
y_pred = [Link](X_test)
y_prob = gnb.predict_proba(X_test)
# Cross-validation
scores = cross_val_score(gnb, X, y, cv=10, scoring='accuracy')
print(f"10-Fold CV Accuracy: {[Link]():.3f} ± {[Link]():.3f}")
# Split data
X_train, X_test, y_train, y_test = train_test_split(
emails, labels, test_size=0.3, random_state=42
)
[Link](X_train, y_train)
y_pred = [Link](X_test)
cancer = load_breast_cancer()
X, y = [Link], [Link]
classifiers = {
'Gaussian NB': GaussianNB(),
'Bernoulli NB': BernoulliNB(),
}
Laplace Smoothing
A critical concept in Naïve Bayes: if a feature value never appears in the training data for a
class, its probability is 0 — causing the entire probability to be 0 (zero-frequency problem).
Laplace smoothing (add-one smoothing) adds a small count α to all feature counts to prevent
this.
# Without smoothing: P(word|class) = 0 if word not seen → kills all
probabilities
💡 Key Takeaway
The workflow for any ML problem:
1. Collect and explore data
2. Preprocess (handle missing values, encode, scale)
3. Split into train/test sets
4. Train multiple algorithms
5. Evaluate using cross-validation and metrics
6. Tune hyperparameters (GridSearchCV)
7. Select best model and deploy
— End of AI Study Notes —