Module - 3
Module - 3
I Semester
Course: Introduction to AI and Applications
Course Instructor
Ms. Divyashree S
Assistant Professor, Dept. of CSE,
EPCET
[Link]@[Link]
3.1 Techniques in AI
Concept
Building an AI system involves reverse-engineering human traits and capabilities into a
machine—essentially enabling computers to think, learn, and act like humans.
To understand how AI works in practice, it is divided into several sub-domains, each focusing
on a specific capability or approach. All sub-domains share a common foundation: processing
large datasets with intelligent algorithms to enable automatic learning.
1. Neural Networks
Neural Networks are designed to work similar to the human brain, where each
neuron (node) processes information and passes it to other neurons.
They help computers recognize relationships and patterns in data to derive meaning
from it.
• A Neural Network is made up of layers of nodes (neurons).
• Each neuron receives inputs, applies weights and biases, processes them, and sends the
output to the next layer.
• The network learns by making multiple passes through the data, adjusting weights
each time to reduce errors and improve accuracy.
1. Input Layer
o The first layer where data enters the network.
o Each input node represents a feature or variable from the
dataset.
2. Hidden Layer(s)
o One or more layers where processing occurs.
o The system applies weights, biases, and activation
functions to inputs to detect patterns. This is where the
learning happens.
3. Output Layer
o The final layer that produces the result or prediction after
processing.
o Outputs can be in the form of a category (e.g., “spam” or
“not spam”) or a value (e.g., “price = ₹500”).
2. Machine Learning (ML)
Machine Learning is a branch of AI that enables computers to analyze data, identify
patterns, and make decisions without human intervention.
How It Works
• ML algorithms learn from experience
instead of following fixed instructions.
• They analyze data, compare results, and
adjust automatically to improve accuracy.
• The process repeats until the system
produces reliable outputs.
Features
• Learns and improves automatically.
• Makes data-driven decisions.
• Saves human time and effort.
• Forms the base for NLP, Deep Learning, and Computer Vision.
How It Works
• Uses deep neural networks with many hidden
layers.
• Each layer processes data from the previous one — this
is called forward propagation.
• If the output is inaccurate, the system adjusts the
weights through backward propagation to improve
performance.
• Learns complex patterns from large datasets using
powerful computing resources.
Key Features
The goal of NLP is to make computers communicate with humans in a natural and
meaningful way, just like people do with each other.
Key Functions
• Reading and processing text or speech.
• Understanding meaning and context.
• Responding appropriately in human language.
Applications
• Chatbots and virtual assistants (e.g., Siri, Alexa)
• Language translation (e.g., Google Translate)
• Speech recognition
• Sentiment analysis
5. Computer Vision
Computer Vision is a branch of AI that enables machines to see, analyze, and understand
images or videos just like humans do.
How It Works
• The system breaks down images into parts, studies each part, and learns patterns.
• It then classifies and interprets new images based on previous learning.
Applications
• Facial recognition for security and surveillance
• Autonomous vehicles (self-driving cars)
• Medical diagnosis using image analysis
• Retail and finance for tracking inventory and preventing fraud
6. Cognitive Computing
Cognitive Computing is a subfield of AI that aims to mimic the human brain by
processing text, speech, images, or objects to produce human-like responses.
Purpose: The goal is to create systems that can think, reason, and respond naturally,
allowing human-like interaction with machines.
Applications
“A computer program is said to learn from experience (E) with respect to some class of tasks
(T) and performance measure (P), if its performance at tasks in T, as measured by P,
improves with experience E.”
Machine Learning algorithms are broadly classified into Supervised and Unsupervised
learning.
This helps the model predict the output for any new input.
Example:
Training a model to identify fruits — after learning what apples and bananas look like, it can
correctly classify new fruit images.
a) Classification
• A Classification Algorithm is a type of supervised machine learning algorithm that is
used to classify data into specific categories or groups.
• It predicts discrete (categorical) outcomes rather than continuous values.
• The algorithm learns from labeled training data, where both inputs and their
corresponding class labels are known.
• During the training phase, the model learns patterns and relationships in the data.
• In the testing or prediction phase, it uses what it learned to assign new data to one of
the predefined classes.
Example
• Identifying a fruit as either an apple or a banana based on its features (like color, shape,
and size).
Real-World Applications
• Medical imaging: Classify whether a tumor is benign or malignant.
• Speech recognition: Identify spoken words or commands.
• Handwriting recognition: Recognize characters or digits.
• Email filtering: Detect whether an email is spam or authentic.
• Credit scoring: Predict if a person is a good or risky borrower.
When to Use Classification
• When data can be tagged, categorized, or separated into distinct classes.
• Suitable for problems where the output is a label (e.g., “Yes/No”, “Spam/Not Spam”,
“Positive/Negative”).
b) Regression
• Regression is a type of supervised machine learning algorithm used to predict
continuous (real-valued) outcomes based on input data.
• Unlike classification algorithms, which predict discrete labels, regression models
predict numerical values.
Examples of Regression Applications
• Predicting the cost of a product
• Estimating the value of a stock
• Forecasting temperature changes
• Predicting power demand fluctuations
Example
• If images of mangoes and
oranges are given to the
algorithm without labels:
o Initially, the system does
not know what a mango or
orange looks like.
o It observes patterns and
groups similar images together
— one cluster for mangoes and
another for oranges.
o However, it cannot name
or label them as “mango” or
“orange” — it only recognizes
similarity.
Learning Mechanism
• The algorithm learns through observation by detecting structures and relationships in
the dataset.
• It automatically forms clusters or associations among data points.
3. Dimensionality Reduction
o Objective: Reduce the number of features or variables in a dataset while
retaining essential information.
o Helps in simplifying large datasets with millions of features.
o Techniques: Principal Component Analysis (PCA), Singular Value
Decomposition (SVD).
o Applications: Data visualization, noise reduction, and speeding up
computations.
Characteristics
• Works without labeled data.
• Uses iterative and exploratory approaches, often involving deep learning.
• Suitable for complex tasks like pattern recognition and feature extraction.
• The algorithm explores data to find hidden relationships without prior clues.
3. Semi-Supervised Learning
• Semi-Supervised Learning (SSL) is a hybrid machine learning approach that combines
elements of both supervised and unsupervised learning.
• It uses a small amount of labeled data and a large amount of unlabeled data for training.
• The goal is to improve model accuracy when labeling large datasets is expensive or
time-consuming
Working Principle
Semi-supervised learning can be implemented using two main approaches:
Advantages
• Improves accuracy compared to purely
unsupervised learning.
• Reduces labeling cost by requiring fewer labeled
examples.
• Utilizes large volumes of unlabeled data
effectively.
• Works well in scenarios where data labeling is
expensive or limited.
Applications
• Speech recognition: Using few transcribed samples with large amounts of raw audio.
• Web content classification: Labeling only a few pages and classifying millions.
• Medical diagnosis: Limited labeled patient data combined with large unlabeled
datasets.
• Image recognition: Annotating a few images while leveraging many unlabeled ones.
• Text classification: Categorizing documents or emails with minimal labeled data.
After several trials, the robot learns the best path to reach the diamond with
o
minimal penalties.
Working of RL Algorithm
1. Input: Initial state from which the agent begins.
2. Output: List of possible actions or decisions for that problem.
3. Process:
o The agent takes an action based on its current state.
o The environment provides feedback (reward or punishment).
o The agent updates its knowledge to improve future decisions.
o This continues iteratively until the agent finds the optimal policy (maximum
total reward).
Mathematical View
• RL problems are modeled as Markov Decision Processes (MDPs) consisting of:
o States (S) – different situations the agent can be in.
o Actions (A) – choices available to the agent.
o Rewards (R) – feedback received after each action.
o Policy (π) – strategy used by the agent to decide actions.
Types of Reinforcement
1. Positive Reinforcement
o Strengthens a behavior by rewarding the agent when it performs correctly.
o Encourages the agent to repeat good behavior.
o Effect: Increases performance and maintains desired actions for a longer period.
o Example: Giving points to a robot for moving closer to a goal.
2. Negative Reinforcement
o Strengthens behavior by removing or avoiding negative outcomes.
o Encourages the agent to act in a way that avoids penalties or losses.
o Example: Stopping a penalty once the robot avoids an obstacle.
This equation is then used to predict the value of y when the values of the predictors are
known.
Where:
• b₀ = intercept
• b₁ = coefficient (slope) of the predictor x
• e = residual error (difference between actual and predicted value)
Method Used:
Ordinary Least Squares (OLS)
OLS selects coefficients 𝑏0 , 𝑏1 such that the sum of squared errors is minimum.
For 10 km:
𝑦 = 11(10) + 30 = 140
For 20 employees:
𝑦 = 10000 × 20 + 20000 = 220000
After 6 months:
𝑦 = 450000(6) − 500000 = 2200000
Adjusted R-square
• Shows how much variation in the data is explained by the model.
• Adjusted for number of predictors.
• Higher Adjusted R-square→ better model
Train–Test Split
• Data is often split in 80:20 ratio
o 80% → Training
o 20% → Testing
• Test data checks predictive performance on unseen data.
k-Fold Cross-Validation
Useful even for small datasets.
Steps:
1. Split data into k subsets.
2. Use one subset as test data, train on remaining k–1 subsets.
3. Record the prediction error.
4. Repeat until each subset has been used as test data.
5. Compute the average of all errors → Cross-validation error.
Steps with Example (k = 5)
Suppose you have a small dataset with 10 records:
Data = [1,2,3,4,5,6,7,8,9,10]
You choose k = 5, so the data will be split into 5 folds (subsets).
Each fold will have 2 records.
Step 1: Split the dataset into k subsets
For k = 5:
• Fold 1: [1, 2]
• Fold 2: [3, 4]
• Fold 3: [5, 6]
• Fold 4: [7, 8]
• Fold 5: [9, 10]
Step 2: Reserve one subset as test data and train on the rest
Example for Iteration 1:
• Test Set → Fold 1: [1, 2]
• Training Set → Folds 2, 3, 4, 5: [3–10]
Step 3: Test the model & record error
Train your machine learning model using training data
and then test it on Fold 1.
The result will give you Error 1.
Step 4: Repeat for all 5 folds
Iteration Test Fold Train Folds Error
1 Fold 1 2,3,4,5 E1
2 Fold 2 1,3,4,5 E2
3 Fold 3 1,2,4,5 E3
4 Fold 4 1,2,3,5 E4
5 Fold 5 1,2,3,4 E5
You get 5 different errors.
Step 5: Calculate average error (Cross-Validation Error)
𝐸1 + 𝐸2 + 𝐸3 + 𝐸4 + 𝐸5
CV Error =
5
This average is called the cross-validation error.
• It tells how well the model performs overall.
• The model with the lowest cross-validation error (e.g., RMSE) is considered the best
model.
Types of Regression
1. Linear Regression
• Definition:
Linear regression is the simplest regression technique used to
predict the value of a dependent variable (Y) based on the
value of an independent variable (X) when the relationship is
linear.
• General Equation:
𝑌 = 𝑏𝑋 + 𝐶
o Y → Dependent variable
o X → Independent variable
o b → Slope of the regression line
o C → Intercept
• Key Points:
o Easy to model and evaluate.
o Useful when the relationship is not complex or data is limited.
o Prone to overfitting if too many features are used.
o Helps in detecting outliers.
o Fast and interpretable.
2. Logistic Regression
• Definition:
Logistic regression is used when the
dependent variable is binary, such as 0/1,
yes/no, true/false.
• Usage:
Used to calculate the probability of an
event (success or failure).
• How it Works:
o It applies a logit function to convert
linear output into a probability
between 0 and 1.
o Best suited for categorical data.
• Example Applications:
o Spam vs. not spam
o Disease detection (positive/negative)
3. Ridge Regression
• Definition:
Ridge regression is used to handle multicollinearity (high correlation between
predictors) and overfitting in multiple regression.
• How it Works:
o Adds a penalty term (L2 regularization) to shrink large coefficients.
o Reduces model complexity and variance.
• Key Point:
A small bias is introduced, but the overall model performance improves.
5. Polynomial Regression
• Definition:
Polynomial regression fits a curved line to data that has a non-linear relationship
between the dependent and independent variables.
• Equation:
𝑌 = 𝑏0 + 𝑏1 𝑋 + 𝑏2 𝑋 2 + ⋯ + 𝑏𝑛 𝑋 𝑛
• Uses:
o Works well for curvilinear data patterns.
o Typically applied with least squares fitting.
• Example:
Predicting growth curves, price trends, temperature
variations.
6. Stepwise Regression
• Definition:
A technique to build predictive models by automatically adding or removing
variables step-by-step.
• Methods:
o Forward Selection: Add variables one by one; stop when no improvement
occurs.
o Backward Elimination: Start with all variables; remove one at a time.
o Bidirectional Elimination: Combination of both methods.
• Benefit:
Helps identify an optimal set of predictors without manual selection.
7. ElasticNet Regression
• Definition:
ElasticNet is a combination of Ridge (L2) and Lasso (L1) regression.
• Key Points:
o Useful when the number of predictors is greater than the number of
observations.
o Handles correlated predictors effectively (grouping effect).
o Often used in:
▪ Support Vector Machines
▪ Document classification
▪ Metric learning
• Advantage:
Combines the feature selection ability of Lasso and the stability of Ridge.
Basic Idea
• Similar objects belong to the same class.
• For an unknown instance, the algorithm:
o Measures similarity with training samples.
o Assigns the class of the nearest neighbours.
• Classification is done using majority voting.
Working of K-NN
1. Store all training samples.
2. Select the value of K (number of neighbours).
3. Calculate the distance between the new instance and each training sample.
4. Identify the K nearest neighbours.
5. Assign the class that appears most frequently among the K neighbours (mode).
Distance Measure
Commonly used distance:
• Euclidean Distance
𝑑 = √(𝑥2 − 𝑥1 )2 + (𝑦2 − 𝑦1 )2
• EC Score = 2
Coordinates of New Student = (8, 2)
Step 5: Classification
Since the minimum distance is with Academically Sound, the new student is classified as:
Academically Sound
Decision Tree
• A Decision Tree is a supervised learning technique used in data mining and machine
learning.
• It provides explicit rules for prediction and classification.
• Works well with heterogeneous data (numerical + categorical).
• Represents decisions in the form of a tree structure:
▪ Nodes → questions/conditions
▪ Edges/Branches → decision rules
▪ Leaves → final outcomes
• After assignining all the leaf nodes we calculate : Error rate of tree = sum of error rates
of all leaf nodes.
Output Nature
Purpose of Pruning
• Removes unnecessary branches from the decision tree.
• Prevents the creation of very small nodes with no statistical significance.
• Improves generalization, accuracy, and simplicity of the model.
Role of Cross-Validation
• Uses cross-validation technique to evaluate performance.
• Calculates error rates for all possible sub-trees.
• Compares these error rates and selects the best sub-tree with minimum error.
Binary Tree
• A tree in which each node has at most two child nodes.
• Most decision tree algorithms generate trees in binary form.
Example
• Information Gain (IG) at a node = −10 (loss of 10).
• Further split gives IG = +20.
• A simple decision tree stops splitting at −10.
• In pruning, overall gain is considered:
−10 + 20 = +10
• Since the total gain is positive, both leaf nodes are retained.
Key Terminology
1. Root node: This is the node that performs the first split.
2. Terminal nodes/Leaves: These nodes predict the outcome.
3. Branches: They are depicted by arrows that connect nodes and shows the flow from question
to answer. Technically, a branch is a sub sec tion of entire tree
4. Splitting: This is the process of dividing a node into two or more sub nodes. In a decision
tree, splitting done until a user-defined stopping criteria is reached. For example, the
programmer may specify that the algorithm should stop once the number of items per node
becomes less than 30.
5. Decision node: This is a sub-node that splits into further sub-nodes
6. Terminal or Leaf node: It is a sub-node that does not split further.
7. Parent node: A node which splits into sub-nodes is called a parent node of the sub-nodes (or
child of the parent node).
Random Forests
Random Forest is a powerful and versatile machine learning technique that, like decision
trees, can be used for both classification and regression problems. However, it generally
provides better performance than a single decision tree.
Clustering Techniques
Clustering is an unsupervised learning technique used to group
similar data objects into clusters.
• Objects in the same cluster → more similar
• Objects in different clusters → dissimilar
Clustering helps identify meaningfulness (insights) and
usefulness (preprocessing for further tasks).
Applications
• Healthcare: Group patients based on treatment
response
• Business: Cluster customers by purchase behaviour for
targeted marketing
1. Partitional Clustering
Concept
• Divides data into non-overlapping clusters
• Each object → belongs to only one cluster
• User specifies k clusters
• Clusters formed iteratively
• Algorithms are nondeterministic (different results on each run)
Examples
• k-means
• k-medoids
Advantages
1. Works well for spherical-shaped clusters
2. Scalable in terms of computation
Limitations
1. Poor performance for complex or irregular cluster shapes
2. Does not work well with clusters of different densities
Department of CSE 2025-2026 P a g e 23 | 40
Introduction to AI and Applications(25ET15)
2. Hierarchical Clustering
Concept
Builds clusters in a tree-like structure (dendrogram).
Two approaches:
(a) Agglomerative (Bottom-Up)
• Start with each point as a single cluster
• Merge the most similar points step-by-step
• End with one cluster
(b) Divisive (Top-Down)
• Start with all data as one cluster
• Split least similar points repeatedly
• End with individual points
Cluster formation is done by cutting the dendrogram at a chosen depth (gives k clusters).
Hierarchical clustering is deterministic → same output on every run.
Advantages
1. Shows relationships among data objects
2. Results are easy to interpret
Limitations
1. Computationally expensive
2. Highly affected by noise and outliers
3. Density-Based Clustering
Concept
Clusters are formed based on high-density regions separated by low-density areas.
• No need to specify k
• Uses a distance threshold to decide cluster membership
Examples
• DBSCAN
• OPTICS
Advantages
1. Works well for non-spherical cluster shapes
2. Effective even with noise and outliers
Limitations
1. Not suitable for high-dimensional data
2. Difficulty in identifying clusters with varying densities
K-Means Algorithm
What is K-Means?
• K-Means is an unsupervised machine learning technique used to divide a dataset into
k clusters.
• It does not use labeled data; instead, it identifies patterns by grouping similar
observations.
• A cluster is a group of data points that are:
o Similar within the group (intra-cluster similarity)
o Different from other groups (inter-cluster dissimilarity)
Consider a bank clustering customers based on income (X-axis) and debt (Y-axis).
Properties
1. High similarity within a cluster
o All points inside a cluster should be similar.
o Helps in tasks like targeted marketing.
2. High dissimilarity between clusters
o Different clusters must be as far apart as possible.
Components:
• Intra-cluster distance: distance between points and centroid (should be small)
• Inter-cluster distance: distance between centroids of different clusters (should be
large)
Dunn Index = (Minimum inter-cluster distance) / (Maximum intra-cluster distance)
• Higher Dunn Index = Better clusters
• Numerator should be large (clusters far apart)
• Denominator should be small (clusters tight and compact)
Why DBSCAN?
• K-Means limitations:
o Must pre-define k (number of clusters).
o Sensitive to initialization and outliers.
o Forms only spherical clusters.
o Every point is forced into some cluster.
• DBSCAN advantages:
o No need to specify k.
o Can detect arbitrarily shaped clusters.
o Identifies noise/outliers.
o Less sensitive to small changes in data.
Key Parameters
1. eps (ε):
o Radius used to find neighboring points.
o Chosen using k-distance graph (look for “elbow”).
2. minPts:
o Minimum number of points required to form a dense region.
o Rule of thumb:
▪ minPts ≥ D + 1 (D = dimensions)
▪ For noisy/large datasets: minPts ≈ 2 × D
o Minimum useful value: 3.
Important Concepts
1. Core Point
• Has ≥ minPts points within distance ε.
2. Border Point
• Not a core point but lies within ε of a core point.
3. Noise Point
• Neither core nor border; insufficient neighbors.
Parameters
1. Density Reachability
• A point q is density-reachable from p if:
o q lies within ε of p and
o p is a core point.
2. Density Connectivity
• Points p and q are density-connected if both are density-reachable from a common
point.
Department of CSE 2025-2026 P a g e 27 | 40
Introduction to AI and Applications(25ET15)
In classification:
• X = features
• Y = class
Dependent Events
Events are dependent when the occurrence of one affects the probability of the other.
✔️ P(A and B) = P(A) × P(B|A)
or
✔️ P(A and B) = P(B) × P(A|B)
Example: Drawing cards without replacement
We want: one Queen and one King.
• P(Queen first) = 4/52
• After drawing one card, only 51 cards left
• P(King | Queen) = 4/51
So,
P(Queen and King) = (4/52) × (4/51)
Since removing one card changes the next probability → Events are dependent.
Neural Network
• A Neural Network (NN) or Artificial Neural Network (ANN) is a machine-learning
algorithm inspired by the human brain.
• It learns from examples and consists of many interconnected nodes called neurons.
• Information flows non-linearly and is processed in parallel.
• NN adjusts weights (internal parameters) to improve its predictions.
• Neural Networks are especially useful for tasks easy for humans but hard for
machines, such as pattern recognition.
Applications
• Optical character recognition (OCR)
• Facial recognition, object detection
• Pattern matching
Applications
Neural Networks are used in:
1. Pattern Recognition
• Facial recognition
• Fingerprint identification
• Object detection
2. Anomaly Detection
• Detect unusual or abnormal patterns
• Used in fraud detection, intrusion detection
3. Time Series Prediction
• Stock market forecasting
• Weather prediction
4. Natural Language Processing (NLP)
• Text classification
• Named Entity Recognition (NER)
• POS tagging
• Speech recognition
• Spell checking
1. Threshold-based output:
If (x1 + x2 + x3 > threshold) → output = 1; else 0
2. Weights:
Importance of inputs.
Example: w3 > w1 means x3 is more important.
3. Bias:
Helps shift the decision boundary for more flexibility.
4. Training Iteration / Epoch:
One complete cycle of forward + backward propagation.
Gradient Descent
Gradient Descent is a method used to reduce error in a neural network by updating weights.
Imagine this:
You are on top of a hill (high error).
You want to reach the bottom (low error).
You take small steps downward each time.
These steps = updating weights
Direction = gradient
Reaching bottom = minimum error
Scenario 1
• Three hyperplanes A, B, and C are drawn.
• B and C separate the two classes better than A.
• Not all separating lines are optimal.
Scenario 2
• All three hyperplanes separate the classes.
• The hyperplane with maximum margin is selected.
• Hyperplane C has the highest margin → best decision boundary.
• Low margin → higher chance of misclassification.
Scenario 3
• Hyperplane A is chosen.
• It maximizes margin and minimizes classification error.
Scenario 4
• One data point (star) lies inside the opposite class (circle).
• Perfect linear separation is difficult in this case.
2. Kernel Trick
o Transforms data from low-dimensional space to high-dimensional space.
o Common kernels:
▪ Gaussian RBF
▪ Polynomial
▪ Sigmoid
Tuning Parameters
• Cost (C):
o Large C → low bias, high variance (risk of overfitting).
o Small C → high bias, low variance.
• Gamma (for RBF kernel):
o Controls the influence of a single training point.
o Small gamma → underfitting.
• Parameter selection is done using cross-validation and grid search.
How SVM Works
1. Select an optimal hyperplane with maximum margin.
2. Apply a penalty (C) for misclassification.
3. Use kernel functions for non-linearly separable data.
Data Standardization
• SVM is distance-based; hence feature scaling is mandatory.
• Common methods:
o Z-score normalization
o Min–Max scaling
Advantages
• Works well with high-dimensional data.
• Effective for non-linear problems using kernels.
• Memory efficient (uses only support vectors).
• Performs well for text and image classification.
• Free from multicollinearity issues.
Disadvantages
• Computationally expensive for large datasets.
• Does not directly provide probability estimates.
• Linear SVM behaves similar to logistic regression for linearly separable data.
Support Vector Machine (SVM) is widely used in real-world applications due to its high
accuracy and ability to handle high-dimensional and non-linear data.
• Bioinformatics
Used to classify proteins, genes, and cancer data. Kernel functions help measure
similarity between protein sequences.
• Texture Classification
SVM classifies images based on texture, such as smooth or rough surfaces.
• Speech Recognition
Applied to acoustic data for speech recognition systems, especially helpful for
assistive technologies.
• Steganography Detection
Used to detect hidden messages in digital images, important in security and forensic
applications.