Unit 1 Notes
Unit 1 Notes
In contrast, machine learning allows computers to automatically find patterns and make
decisions based on past experiences or data.
The process of machine learning involves feeding large amounts of data into algorithms,
which then learn relationships and patterns within that data.
Once trained, these models can make predictions or classifications on new, unseen data.
For example, a machine learning model can learn to identify whether an email is spam or not
based on examples of past emails.
Machine learning can be broadly classified into three types: Supervised Learning, where
models are trained on labeled data; Unsupervised Learning, where the system finds hidden
patterns in unlabeled data; and Reinforcement Learning, where an agent learns by
interacting with its environment and receiving feedback in the form of rewards or penalties.
Machine learning is widely used in various applications such as image and speech recognition,
recommendation systems, fraud detection, and healthcare diagnosis.
It forms the foundation for many modern technologies that make intelligent predictions and
automate complex tasks.
In traditional programming, a human explicitly writes the rules and logic that a computer must
follow to perform a task. The programmer provides both the input data and a set of predefined
instructions to produce the desired output. This approach works well for simple, rule-based
problems where the logic is clear and can be easily coded, such as performing mathematical
calculations or sorting a list of numbers. However, it becomes difficult to apply when the problem
is complex or when rules are hard to define, such as recognizing faces or detecting spam emails.
In contrast, a machine learning–based approach allows the computer to learn from data rather
than following fixed rules. Here, the programmer provides the system with input data and the
corresponding output (in supervised learning), and the machine automatically learns the
underlying patterns or relationships between them. Once trained, the model can make predictions
or decisions on new, unseen data. This makes machine learning more flexible and powerful for
solving problems involving large amounts of data and complex relationships that are not easily
programmed by humans.
It allows AI systems to analyze data, identify patterns, make decisions, and perform tasks that
typically require human intelligence.
ML acts as the core technique that helps AI systems adapt and evolve over time.
For example, through ML, AI applications like speech recognition, image processing, and natural
language understanding become more accurate with continuous learning from data.
It helps data scientists uncover hidden patterns, make predictions, and automate decision-making
processes.
ML algorithms are used to build predictive models that can forecast future trends, classify data,
and optimize business processes.
Essentially, ML transforms raw data into actionable insights, making it a crucial component of
the data science workflow.
• Image and Speech Recognition: Used in facial recognition systems, voice assistants,
and biometric authentication.
• Natural Language Processing (NLP): Powers chatbots, language translation, and
sentiment analysis.
• Recommendation Systems: Used by platforms like Netflix, Amazon, and YouTube to
suggest content based on user behavior.
• Healthcare: Helps in disease prediction, medical image analysis, and personalized
treatment plans.
• Finance: Used for fraud detection, credit scoring, and algorithmic trading.
• Autonomous Systems: Enables self-driving cars and robotics to make real-time
decisions.
• Business Analytics: Supports demand forecasting, customer segmentation, and process
optimization.
1.2.1 Supervised
1.2.2 Unsupervised
1.2.3 Reinforcement
1.2.1 Definition:
Supervised Learning is a fundamental type of Machine Learning where the model is trained
using labeled data, meaning that each input in the training dataset is paired with the correct
output. The main objective of supervised learning is to enable the system to learn the mapping
between input variables and output labels so that it can make accurate predictions for new,
unseen data.
Working Principle:
First, a dataset containing input features and their corresponding target outputs is collected.
The model is then trained on this data by comparing its predicted output with the actual output
and adjusting its internal parameters to minimize the difference, or error.
Once trained, the model is tested on new data to evaluate its performance and can then be
used to predict outcomes for unknown inputs.
Essentially, supervised learning works under the “teacher-student” concept, where the
algorithm learns from the correct answers provided during training.
Example: Features (like hours studied) and target output (like marks scored).
2. Training the Model: The algorithm learns by comparing its predictions with the actual
outputs and adjusting itself to minimize errors.
3. Testing the Model: Once trained, the model is tested on new data to evaluate its
accuracy.
4. Prediction: After successful training, the model can predict outputs for new inputs where
the correct output is unknown.
Essentially, supervised learning “supervises” the model using known answers during training —
just like a teacher guiding a student.
Supervised learning is broadly divided into two categories: classification and regression.
Classification is a type of supervised learning where the goal is to categorize input data into
predefined classes or groups.
In this approach, the model learns from labeled data, where each input has a specific category
assigned to it.
During training, the algorithm identifies patterns and relationships in the data that help it
distinguish between different classes.
Once trained, the model can predict the class of new, unseen [Link] example, in email filtering,
the model is trained on a dataset containing emails labeled as “spam” or “not spam.” After
learning the characteristics of each type, it can automatically classify new emails into the correct
category. Other examples include handwriting recognition (digits 0–9), disease detection
(infected or healthy), and image classification (cat, dog, bird, etc.).
Classification can be binary (two classes, such as yes/no or true/false) or multiclass (more than
two classes, such as types of flowers or fruits).
Common algorithms used for classification include Logistic Regression, Decision Trees,
Random Forest, K-Nearest Neighbors (KNN), Support Vector Machine (SVM), and Naive
Bayes.
Examples: Email classification (Spam or Not Spam), Disease diagnosis (Healthy or Sick)
Fig. Classification
[Link], on the other hand, is used when the output variable is continuous, such as
predicting house prices, estimating sales revenue, or forecasting temperature.
Regression is another form of supervised learning where the objective is to predict a continuous
numerical value instead of a category.
In regression, the model learns the relationship between input variables and a continuous output
variable by analyzing trends and dependencies in the data.
For instance, regression can be used to predict house prices based on features such as area,
location, and number of rooms, or to forecast sales, stock prices, and temperatures.
The key goal is to estimate how changes in the input variables influence the output value.
Common algorithms used for regression include Linear Regression, Polynomial Regression,
Decision Tree Regression, Random Forest Regression, and Support Vector Regression
(SVR).
Fig. Regression
1. Definition
Unlike supervised learning, the algorithm does not learn from correct answers, but instead
learns from the data distribution itself.
• Unlabeled
• Large-scale
• Complex and high-dimensional
• Is time-consuming
• Is expensive
• Requires domain experts
• Knowledge discovery
• Exploratory data analysis
• Feature extraction
• Pre-processing for supervised models
Example:
• 2 features → 2D space
• 3 features → 3D space
• Euclidean distance
• Manhattan distance
• Cosine similarity
Key idea:
Similar data points should be closer together, dissimilar ones should be far apart.
Based on similarity:
• Clusters
• Associations
• Reduced feature sets
• Cluster labels
• Association rules
• New feature representations
[Link]:
Clustering is the most common technique in unsupervised learning. It involves grouping data
points such that those in the same group (cluster) are more similar to each other than to those in
other groups.
For example, a company can use clustering to segment customers into different groups based on
buying habits or demographics.
It involves grouping a set of data points into clusters so that data points within the same cluster
are more similar to each other than to those in other clusters.
The main objective of clustering is to discover hidden patterns or natural groupings in data
without any predefined labels.
Fig. Clustering
In this process, the algorithm analyzes the features of each data point and measures their
similarity or distance (often using metrics like Euclidean distance).
Based on these similarities, it assigns them to clusters. For example, in marketing, clustering can
be used to segment customers based on their purchasing behavior or preferences.
Similarly, in biology, it can help group genes with similar expression patterns.
Clustering is highly useful for pattern discovery, market segmentation, anomaly detection, and
image compression.
It involves reducing the number of input variables (features) while retaining the most important
information. This simplifies data visualization, speeds up computation, and reduces noise.
Dimensionality Reduction refers to the process of reducing the number of input variables or
features in a dataset while retaining its essential information.
In many real-world applications, datasets have a large number of features, which can make
analysis and visualization difficult.
High-dimensional data can also lead to problems like overfitting and increased computation
time.
Dimensionality reduction helps overcome these issues by simplifying the dataset and
highlighting the most important aspects.
The goal of dimensionality reduction is to transform the data into a lower-dimensional space
where relationships and patterns are easier to observe and interpret.
By projecting the original data onto these axes, PCA reduces the number of features
while retaining as much information as possible. It’s fast, robust and especially effective
when the dataset has linearly correlated features. However, it cannot capture complex non
linear relationships.
It works under the assumption that each class is normally distributed with identical
covariance matrices as it focuses on class separability.
t-SNE is a non linear non linear manifold learning technique mainly used for
visualization. It converts high dimensional pairwise distances into conditional
probabilities that represent similarities between points.
Unlike PCA which decorrelates data by finding orthogonal axes ICA goes further by
maximizing statistical independence often using measures like kurtosis or negentropy.
This makes it particularly useful for blind source separation problems like separating
overlapping audio signals. ICA assumes the source signals are non gaussian and
independent so it’s less effective when this isn’t true.
NMF factorizes a non negative data matrix into two non negative lower rank matrices.
This decomposition enforces a parts based representation because the components must
add up not subtract from each other.
This is useful when the data naturally has non negative features like pixel intensities or
word counts.
It has gained popularity in image processing, topic modeling and bioinformatics because
it produces more interpretable results compared to methods like PCA which may mix
positive and negative components.
• 6. FastICA
FastICA is an optimized and faster version of ICA that uses a fixed point iteration
scheme to efficiently find independent components. It’s widely used when standard ICA
would be too slow specially for large datasets or realtime applications.
It preserves the core idea of maximizing non Gaussianity to extract independent sources
but improves convergence speed and stability. It’s commonly used in signal processing
tasks like EEG analysis and audio source separation where quick and reliable separation
is needed.
Isomap is a non linear algorithm that extends classical Multidimensional Scaling (MDS).
Instead of preserving straight line distances, Isomap computes geodesic distances the
shortest paths along the manifold surface using a neighborhood graph.
Isomap is effective when the data lies on a smooth, non linear manifold but it can be
sensitive to outliers and requires careful tuning of the neighborhood size.
Locally Linear Embedding (LLE) is another non linear manifold learning method that
preserves local relationships within the data. It assumes that each data point can be
reconstructed as a linear combination of its nearest neighbors.
The algorithm first finds these local reconstruction weights in the original space and then
maps the data to a lower dimensional space while preserving the same weights.
This approach unfolds complex manifolds revealing the underlying structure. LLE is
sensitive to the neighborhood size parameter and doesn’t preserve global distances well,
but it’s very good at capturing local geometry.
• 9. Manifold Learning
Manifold Learning is a broader concept that includes methods like Isomap, LLE, Hessian
LLE, Laplacian Eigenmaps, t-SNE and UMAP.
The idea is that high dimensional data often lies on a smooth, lower dimensional
manifold embedded in a higher dimensional space. These techniques aim to uncover and
flatten this manifold, preserving either local or global geometric relationships.
Manifold learning is particularly valuable for visualizing and exploring complex data
structures that cannot be captured by linear methods like PCA.
• 10. Autoencoders
They consist of two main parts: an encoder which maps the input data to a lower
dimensional latent space and a decoder which reconstructs the original data from this
compressed representation.
The network is trained to minimize the difference between the input and the
reconstruction forcing it to learn the most important features. Unlike linear methods like
PCA, autoencoders can capture complex non linear relationships as they use multiple
hidden layers and non linear activation functions.
It works by taking a matrix of pairwise distances and finding a lower dimensional space
like 2D or 3D where these distances are preserved as much as possible.
Unlike PCA, which focuses on maximizing variance and assumes linearity, MDS is more
flexible because it directly uses distances, making it useful for uncovering hidden
structures, clusters or patterns in complex datasets.
In summary, clustering helps group similar data points without prior labels, while
dimensionality reduction simplifies complex datasets by reducing the number of features. Both
techniques are essential in unsupervised learning for exploring, visualizing, and understanding
large and complex data.
1.2.3 Reinforcement Learning (RL): It is a branch of machine learning that focuses on how
agents can learn to make decisions through trial and error to maximize cumulative rewards. RL
allows machines to learn by interacting with an environment and receiving feedback based on
their actions. This feedback comes in the form of rewards or penalties.
Reinforcement Learning revolves around the idea that an agent (the learner or decision-maker)
interacts with an environment to achieve a goal. The agent performs actions and receives
feedback to optimize its decision-making over time.
• Reward: The feedback or result from the environment based on the agent’s action.
Core Components
1. Policy
2. Reward Signal
• Example: For self-driving cars rewards can be fewer collisions, shorter travel time, lane
discipline.
3. Value Function
• Example: A vehicle may avoid reckless maneuvers (short-term gain) to maximize overall
safety and efficiency.
4. Model
• The environment responds by transitioning to a new state and providing a reward (or
penalty).
• The agent updates its knowledge (policy, value function) based on the reward received
and the new state.
• This cycle repeats with the agent balancing exploration (trying new actions)
and exploitation (using known good actions) to maximize the cumulative reward over
time.
In Reinforcement Learning (RL), an agent is the central component and the intelligent
decision-maker that learns how to interact with an environment to achieve a specific goal.
It observes the environment, takes actions, and learns from the outcomes of those actions through
rewards or penalties.
The ultimate goal of the agent is to learn an optimal policy — a strategy that helps it choose the
best possible actions in different situations to maximize the total cumulative reward over time.
1. Role of an Agent
The agent’s main role is to learn by experience. It explores the environment, performs actions,
and receives feedback in the form of rewards.
Based on this feedback, the agent adjusts its behavior to improve future decisions. Over time, it
learns which actions yield the best long-term results, rather than focusing only on immediate
rewards.
Example: In a self-driving car, the agent decides when to accelerate, slow down, or change lanes
based on road conditions and traffic signals.
The agent continuously interacts with the environment through a cycle of observation, action,
and feedback.
The process follows this sequence:
This cycle continues until the agent reaches its goal or the learning process ends. Through
repeated interactions, the agent becomes better at choosing actions that maximize its rewards.
3. Components Associated with the Agent
• Policy (π):
A policy is the decision-making rule that determines which action the agent should take
in a given state. It can be deterministic (always choosing the same action for a state) or
stochastic (choosing actions based on probability).
• Value Function (V):
The value function estimates how good it is for the agent to be in a particular state or to
take a specific action. It helps the agent focus on long-term rewards rather than
immediate ones.
• Reward Function (R):
The reward function defines the feedback system. It tells the agent whether the previous
action was beneficial or not. The agent’s objective is to maximize the sum of these
rewards over time.
4. Types of Agents
Depending on their learning and decision-making approach, agents can be classified into several
types:
• Model-Free Agents:
These agents learn directly from experience without building a model of the environment.
Example: Q-Learning and Deep Q-Network (DQN) agents.
• Model-Based Agents:
These agents build an internal model of the environment to predict outcomes and plan
actions.
Example: Agents using Monte Carlo Tree Search or Policy Iteration.
• Reactive Agents:
These agents make decisions based only on the current state, without considering future
consequences.
• Deliberative Agents:
These agents plan their actions by predicting future states and outcomes based on current
information.
The agent learns through trial and error. Initially, it explores the environment randomly to
gather information.
As it gains experience, it begins to exploit its knowledge — preferring actions that have
previously led to high rewards.
This balance between exploration (trying new actions) and exploitation (using known
successful actions) is critical for effective learning.
6. Example of an Agent in Real Life
• In video games, the AI player acts as the agent that learns to win by maximizing points
or scores.
• In robotics, the robot is the agent that learns to perform tasks like walking, picking
objects, or navigating obstacles.
• In finance, an automated trading system acts as an agent that decides when to buy or sell
stocks to maximize profit.
In Reinforcement Learning (RL), the reward is one of the most crucial components because it
guides the agent’s learning process. It is a numerical feedback signal that the agent receives
from the environment after performing an action. The reward indicates how good or bad the
action was in achieving the overall goal. The main objective of the agent is to maximize the
cumulative reward it earns over time by selecting the best possible actions in various situations.
1. Definition of Reward
A reward is a scalar (single numerical) value provided by the environment to the agent as
feedback for its last action. It reflects the immediate benefit or penalty resulting from that action.
• If the reward is positive, it means the action taken by the agent was beneficial and should
be repeated in similar situations.
• If the reward is negative, it means the action was undesirable and should be avoided in
the future.
Mathematically, the reward at a given time t is represented as Rₜ, and it depends on the current
state, the action taken, and the resulting next state:
This means the reward is determined by the transition from one state to another due to the
agent’s action.
The reward plays a key role in driving the agent’s behavior. It acts as a teaching signal, telling
the agent whether its actions are helping it achieve its goal. Unlike supervised learning, where
the model is given the correct answers (labels), reinforcement learning relies solely on these
rewards to guide learning.
The agent uses these rewards to evaluate the quality of its actions and updates its policy
accordingly to maximize long-term cumulative reward rather than focusing only on short-term
gains.
3. Types of Rewards
a. Immediate Reward:
This is the reward the agent receives immediately after performing an action. It reflects the short-
term result of that particular step.
Example: In a game, the player may earn 10 points for collecting a coin — this is an immediate
reward.
b. Delayed Reward:
Some actions may not give an immediate benefit but lead to a positive outcome later. These are
known as delayed rewards. The agent must learn to balance short-term and long-term rewards to
make optimal decisions.
Example: In chess, moving a piece may not provide an immediate advantage, but it could lead to
a win after several moves.
c. Positive Reward:
A positive value indicates that the action was favorable. It reinforces the behavior and
encourages the agent to repeat similar actions.
Example: A robot receives +5 points for successfully reaching a goal location.
A negative value indicates that the action was poor or led to an undesirable outcome. It
discourages the agent from repeating that behavior.
Example: A self-driving car may receive a -10 reward for colliding with an obstacle.
e. Zero Reward:
Sometimes, the environment provides no feedback for a specific action, meaning it neither helps
nor harms the agent’s progress.
Example: A game might give 0 points for moving without collecting anything or causing harm.
4. Reward Function
The reward function defines the rules by which the environment provides rewards. It specifies
what kind of actions are good or bad and how the agent’s behavior will be evaluated. The design
of this function is critical — a poorly designed reward function can lead the agent to learn
incorrect or suboptimal behaviors.
For instance:
• In a maze-solving problem, the reward function might give:
o +100 for reaching the goal
o -10 for hitting a wall
o -1 for each step taken (to encourage shorter paths)
However, future rewards are often less certain or less valuable than immediate ones. Hence, a
discount factor (γ) is used to reduce the importance of future rewards:
6. Importance of Rewards
• Guides Learning: Rewards are the only form of feedback the agent uses to learn from
the environment.
• Encourages Optimal Behavior: Positive rewards motivate the agent to take beneficial
actions.
• Discourages Wrong Actions: Negative rewards prevent the agent from repeating
mistakes.
• Defines Goals: The design of the reward function sets the goal for the agent’s learning
process.
• Game Playing: The agent earns points for winning and loses points for making mistakes.
• Self-Driving Cars: Rewards for staying in the lane, negative rewards for crashes or
running red lights.
• Robotics: Rewards for successfully completing a task like picking an object or avoiding
obstacles.
• Finance: Rewards for profitable trades, penalties for losses.
[Link] Policy Learning in Reinforcement Learning
In Reinforcement Learning (RL), policy learning is one of the most important concepts. It
defines how an agent makes decisions — in other words, how it chooses actions based on the
current situation (or state) of the environment. The goal of policy learning is to find the best
policy that allows the agent to act in a way that maximizes its total cumulative reward over
time.
1. What is a Policy?
A policy is the strategy or rulebook that an agent follows to decide what action to take in a given
state.
Mathematically, a policy is often denoted as π (pi) and can be written as:
2. Types of Policies
a. Deterministic Policy:
In this type of policy, the agent always performs the same action for a given state.
Mathematically:
a = π(s)
Example: In a simple maze, if the agent is at a corner, it always turns right.
b. Stochastic Policy:
Here, the policy provides a probability distribution over actions. That means the agent might
choose different actions in the same state, each with a certain probability.
Mathematically:
The policy defines the agent’s behavior. While the environment defines the problem, the policy
defines how the agent behaves within that environment.
• It determines the balance between exploration and exploitation (whether the agent
should explore new actions or exploit known good ones).
• It helps in decision-making under uncertainty, since outcomes are not always
predictable.
• It guides the agent toward actions that maximize long-term rewards rather than just
short-term gains.
The process of policy learning involves continuously improving the agent’s decision-making
strategy through experience. The agent observes the results (rewards) of its actions and updates
its policy to perform better in the future.
a. Policy-Based Learning:
In this approach, the agent directly learns the best policy without learning a value function.
Example:
In a self-driving car, a neural network directly maps sensor inputs (state) to steering actions
(policy).
b. Value-Based Learning:
Here, the agent first learns a value function, which estimates how good it is to be in a certain
state or to take a certain action. The policy is then derived from this value function.
Example:
In a game, the agent estimates how valuable each move is and selects the one with the highest
expected reward.
c. Actor-Critic Approach:
Policy learning usually involves two steps that are repeated iteratively:
1. Policy Evaluation:
The agent estimates how good the current policy is — that is, it calculates the expected
returns (rewards) for following that policy.
2. Policy Improvement:
Based on this evaluation, the agent updates its policy to choose better actions in the
future.
Repeating these two steps until convergence results in an optimal policy (π*), which gives the
highest possible reward over time.
These are advanced policy-based techniques where the policy is improved directly using gradient
optimization.
• The idea is to adjust the parameters of the policy function in the direction that increases
the expected reward.
• Common algorithms:
o REINFORCE Algorithm
o Proximal Policy Optimization (PPO)
o Deep Deterministic Policy Gradient (DDPG)
o Advantage Actor-Critic (A2C/A3C)
These methods are widely used in complex environments, such as robotics and game-playing
(e.g., AlphaGo).
• Autonomous Cars:
The policy helps decide when to accelerate, brake, or turn based on road conditions and
nearby vehicles.
• Robotics:
A robot arm learns to pick and place objects — the policy maps sensor readings to
movement commands.
• Games:
In chess or Go, the policy defines which moves to make in a given board position to
maximize the chance of winning.
• Finance:
A trading agent’s policy determines when to buy or sell assets to maximize profit.
What it Common
Typical Strength
Type learns Goal Weaknesses real-world
algorithms s
from uses
Linear/Logisti High Spam
c Reg., accuracy detection,
Labeled Decision with disease
Needs
input → Predict labels Trees, good diagnosis,
Supervised labeled data;
target / values Random labels; price
can overfit
pairs Forest, SVM, direct forecasting,
XGBoost, eval image
Neural Nets metrics classification
Customer
Discover K-Means, Finds
Hard to segmentation,
structure, Hierarchical, hidden
Unlabeled evaluate; anomaly
Unsupervised clusters, DBSCAN, patterns;
data results can be detection,
lower-dim PCA, t-SNE, no labels
subjective topic
features Autoencoders required
modeling
Solves
Interactio sequentia Robotics,
n Learn policy l Sample- game AIs,
Q-learning,
Reinforceme experienc to maximize decision inefficient; ad/bidding
DQN, PPO,
nt e (state, cumulative tasks; reward agents,
SAC, DDPG
action, reward learns design hard autonomous
reward) complex control
policies
Small Reduces Sensitive to Medical
Improve Self-training,
Semi- labeled + labeling label imaging (few
performance consistency
supervised large cost; noise/mistak labels), text
using regularization
unlabeled leverages es classification
What it Common
Typical Strength
Type learns Goal Weaknesses real-world
algorithms s
from uses
unlabeled , pseudo- unlabele
data labeling d data
Leverage
s huge NLP
Contrastive
Unlabeled unlabele pretraining,
Learn learning, Needs
data with d vision
Self- representatio masked careful
constructe corpora; pretraining,
supervised ns useful for prediction pretext task
d pretext strong speech
many tasks (BERT), and compute
tasks pretraine representatio
SimCLR
d ns
features
Fine-tuning
ImageNet
Pretrained Fine-tuning Fast to
Reuse models for
Transfer / on one neural nets, adapt; Domain
knowledge medical
Domain domain, domain reduces mismatch
when labels images,
Adaptation fine-tuned adversarial data can hurt
scarce language
on another nets needs
models for
legal text
Model + Minimize
Uncertainty Industrial
unlabeled labels needed Very Requires
Active sampling, inspection,
pool + by choosing label- human
learning query-by- rare-event
human examples to efficient labeling loop
committee labeling
oracle label
1. Supervised Learning
What it is: learning a mapping from inputs (features) to outputs (labels). The model is trained on
labeled examples.
Evaluation metrics: accuracy, precision, recall, F1, ROC-AUC for classification; RMSE, MAE,
R² for regression.
Real-world examples:
2. Unsupervised Learning
What it is: discovering structure from unlabeled data—no explicit target variable.
Strengths: scales to unlabeled data; good for exploratory analysis and feature extraction.
Real-world examples:
What it is: learning to act in an environment over time to maximize long-term reward via trial
and error.
• Agent observes state → takes action → receives reward and next state.
• Goal is to learn a policy mapping states to actions to maximize discounted cumulative
reward.
• Use value functions, policy gradients, or actor-critic hybrids.
When to use: sequential decision problems where actions influence future states and rewards.
Evaluation signals: episodic reward, success rate, sample efficiency, stability. Safe evaluation
often requires simulation.
Strengths: solves complex decision making and control tasks; learns from interaction.
Weaknesses: needs many interactions (sample inefficient), designing reward shaping is tricky,
safety constraints are hard, simulation often required before real world.
Real-world examples:
Semi-supervised uses a few labeled examples plus many unlabeled ones to improve models.
Methods include pseudo-labeling, consistency regularization, graph-based methods. Great when
labeling is costly—e.g., medical imaging where annotators are experts.
Self-supervised constructs proxy tasks from raw data (masking parts of input, predicting
rotations, contrastive objectives) to learn rich representations without manual labels. Pretrained
models are fine-tuned for many downstream tasks (this is what powers modern NLP and many
vision advances).
Real-world applications:
• BERT, GPT (NLP): self-supervised pretraining on massive text corpora then fine-
tuning.
• SimCLR, CLIP (Vision): contrastive self-supervision for feature learning.
• Medical imaging: semi-supervised pipelines where limited expert labels plus unlabeled
scans produce usable models.
What it is: reuse models/representations trained on large datasets and adapt them to new tasks or
domains with less data.
Why it matters: reduces data/computation needs; often the best practical approach (e.g.,
ImageNet → medical images, BERT → legal text).
Challenges: domain mismatch (covariate shift) can degrade performance; fine-tuning strategies
and learning rates must be chosen carefully.
6. Active learning
What it is: model chooses which unlabeled examples would be most valuable to label next,
minimizing human labeling cost.
When to use: labeling is expensive and labeling budget is limited (industrial inspection, rare
disease datasets).
1. Healthcare
Machine Learning has transformed healthcare by enabling faster and more accurate diagnosis,
personalized treatment, and efficient hospital management.
• Disease Diagnosis: ML models can detect diseases such as cancer, diabetes, and heart
conditions by analyzing medical data like X-rays, MRIs, and lab results.
• Drug Discovery: ML algorithms speed up drug discovery by predicting how certain
chemicals will react in the human body.
• Predictive Analytics: Hospitals use ML to predict patient readmission rates and
treatment outcomes.
• Medical Image Analysis: Deep learning models accurately identify tumors or fractures
in radiology images.
• Wearable Devices: Smart health monitors collect data such as heart rate and oxygen
levels to detect health anomalies early.
Example: IBM Watson Health uses ML to analyze patient data and suggest possible diagnoses
and treatments.
2. Finance
The finance sector heavily relies on ML for risk management, fraud detection, and automation of
financial services.
Example: PayPal uses ML to detect fraudulent transactions and minimize financial losses.
Example: Amazon uses ML-based recommendation systems to suggest products that customers
are likely to buy.
ML models require large amounts of clean and labeled data. Noisy, missing, or biased data can
lead to poor model performance.
2. Overfitting and Underfitting
Overfitting occurs when a model performs well on training data but poorly on new data.
Underfitting happens when the model is too simple to capture the data’s complexity.
3. Lack of Interpretability
Complex models, especially deep learning, are difficult to interpret. It’s often unclear how they
arrive at a particular decision.
Training large ML models requires significant computing power, memory, and time.
ML systems often use sensitive data, leading to ethical issues like data misuse, discrimination,
and privacy violations.
If training data contains biases, ML systems can produce unfair or discriminatory outcomes.
8. Security Threats
Adversarial attacks can trick ML models into making incorrect predictions, creating security
risks.
Before diving into ML algorithms, it’s essential to understand Python fundamentals that are most
relevant to ML projects:
Example:
age = 28
name = "abc"
scores = [88, 92, 79]
2. Control Structures
Example:
for i in range(5):
print("Iteration:", i)
3. Functions
Functions allow code reusability and modularity — crucial in ML for repeating tasks like data
cleaning or feature extraction.
Example:
result = add(5, 3)
Libraries like NumPy and Pandas simplify handling and analyzing data.
import numpy as np
data = [Link]([1, 2, 3, 4, 5])
print("Mean:", [Link](data))
import pandas as pd
df = pd.read_csv("[Link]")
print([Link]())
5. Data Visualization
Example:
import [Link] as plt
x = [1, 2, 3, 4, 5]
y = [2, 4, 6, 8, 10]
[Link](x, y)
[Link]("Simple Line Graph")
[Link]()
model = LinearRegression()
[Link](x, y)
1. Import Libraries
2. Load necessary ML and data handling libraries.
import pandas as pd
import numpy as np
import [Link] as plt
6. Evaluate Model
Use accuracy, precision, recall, or confusion matrix.
7. Visualize Results
Display graphs or performance plots.
Advantages of Using Python in ML
Purpose:
NumPy is a core library for numerical computing in Python. It provides support for large
multidimensional arrays, matrices, and a wide range of mathematical operations.
Key Features:
• Provides the ndarray (N-dimensional array) object for fast numerical operations.
• Offers mathematical, logical, and statistical functions for efficient computation.
• Enables operations like linear algebra, Fourier transforms, and random number
generation.
• Forms the foundation for other libraries like Pandas, Scikit-learn, and TensorFlow.
Example:
import numpy as np
# Creating an array
data = [Link]([1, 2, 3, 4, 5])
# Performing operations
print("Mean:", [Link](data))
print("Square root:", [Link](data))
Purpose:
Pandas is used for data manipulation, cleaning, and analysis. It is built on top of NumPy and
provides two main data structures:
Key Features:
Example:
import pandas as pd
# Reading dataset
df = pd.read_csv("[Link]")
# Viewing data
print([Link]())
# Basic statistics
print([Link]())
3. Matplotlib
Purpose:
Matplotlib is the most widely used library for data visualization in Python.
It helps create static, interactive, and animated plots to better understand data patterns.
Key Features:
• Supports a wide variety of plots (line, bar, histogram, scatter, pie, etc.).
• Highly customizable (titles, labels, colors, legends).
• Useful for exploratory data analysis (EDA).
• Works well with NumPy and Pandas.
Example:
x = [1, 2, 3, 4, 5]
y = [2, 4, 6, 8, 10]
4. Scikit-learn (sklearn)
Purpose:
Scikit-learn is one of the most popular libraries for machine learning algorithms and model
evaluation.
It provides easy-to-use tools for data preprocessing, model training, testing, and
performance analysis.
Key Features:
Example:
# Training data
X = [Link]([[1], [2], [3], [4], [5]])
y = [Link]([2, 4, 6, 8, 10])
# Model
model = LinearRegression()
[Link](X, y)
# Prediction
print("Prediction for 6:", [Link]([[6]]))
import numpy as np
import pandas as pd
data = {
'Salary': [30000, 35000, 40000, 45000, 50000, 55000, 60000, 65000, 70000, 75000]
}
df = [Link](data)
X = df[['Experience']] # Feature
model = LinearRegression()
[Link](X_train, y_train)
y_pred = [Link](X_test)
[Link]('Years of Experience')
[Link]('Salary')
[Link]()
[Link]()