Unit 3 DataScience
Unit 3 DataScience
Basic Concept
In supervised learning, the dataset contains input-output pairs (X, Y).
X represents independent variables (features), and Y represents the dependent variable (label).
The model learns a relationship between X and Y from training data.
Labeled Data
Labeled data means that the correct output is already known for each input.
Example:
Hours Studied → Exam Result (Pass/Fail)
The algorithm learns how study hours influence the result.
A) Classification
In classification, the output variable is categorical.
Examples:
• Spam / Not Spam
• Disease / No Disease
• Pass / Fail
• Image classification (Cat/Dog)
Types of Classification:
• Binary Classification (two classes)
• Multi-class Classification (more than two classes)
• Multi-label Classification (multiple labels per instance)
Common Algorithms:
• Linear Regression
• Logistic Regression
• Decision Tree
• K-Nearest Neighbors (KNN)
• Support Vector Machine (SVM)
B) Regression
In regression, the output variable is continuous (real-valued).
Examples:
• House price prediction
• Temperature prediction
• Salary estimation
• Stock price forecasting
Common Algorithms:
• Linear Regression
• Polynomial Regression
• Support Vector Regression
• Random Forest Regression
• Neural Networks
Mathematical Representation
Supervised learning assumes:
Y = f(X) + ε
Where f(X) is the true function and ε is random noise.
The goal is to approximate f(X) using training data.
Summary:
Supervised Learning uses labeled data to train models for classification and regression tasks.
It focuses on learning patterns, minimizing error, and making accurate predictions on new
data.
First Steps in Supervised Learning
Supervised learning follows a structured pipeline. The quality of the final model depends heavily
on how carefully the initial steps are performed. Below is a detailed academic explanation of
each step.
Step 1: Problem Definition
Problem definition is the most critical step in supervised learning.
1.1 Identify the Objective
Clearly define:
What do you want to predict?
Is it a classification problem or a regression problem?
Example 1:
Predict whether a student will pass or fail
→ Classification problem
Example 2:
Predict house price
→ Regression problem
1.2 Identify Input Features (X)
Features are measurable properties used to make predictions.
Example (Student Performance Prediction):
Feature Description
Study Hours Number of hours studied
Attendance Percentage attendance
Internal Marks Mid-term score
These are independent variables.
1.3 Identify Target Variable (Y)
The output variable we want to predict.
Example:
Pass / Fail (Classification)
Final Exam Score (Regression)
1.4 Define Evaluation Metric
Before building the model, decide:
Accuracy? (for classification)
MSE or RMSE? (for regression)
Without clear metrics, model performance cannot be measured properly.
Step 2: Data Collection
Data is the foundation of supervised learning. High-quality data leads to high-quality models.
2.1 Sources of Data
Surveys
Sensors (IoT devices)
Databases
APIs
Web scraping
Public datasets (e.g., Kaggle, UCI Repository)
2.2 Data Quantity
More data generally improves performance because:
It reduces variance
Improves generalization
However, quality is more important than quantity.
2.3 Data Relevance
Collected data must:
✔ Be relevant to the problem
✔ Represent real-world scenarios
✔ Avoid bias
Example:
If predicting rainfall in India, data from Europe may not be relevant.
Step 3: Data Preprocessing
Raw data is rarely clean. Preprocessing ensures the model can learn effectively.
3.1 Handling Missing Values
Missing values can be handled by:
Removing rows
Replacing with mean/median
Using predictive imputation
Example:
If Age is missing:
Replace with average age of dataset.
3.2 Handling Outliers
Outliers are extreme values that distort model learning.
Example:
Salary values: 20k, 30k, 40k, 10,000k
The last value is an outlier.
Techniques:
Z-score method
IQR method
3.3 Feature Scaling
Some algorithms (like SVM, kNN) require scaling.
Common scaling methods:
Normalization (Min-Max Scaling)
Standardization (Z-score Scaling)
Example:
Age range: 18–60
Salary range: 20,000–2,00,000
Without scaling, salary dominates learning.
3.4 Encoding Categorical Variables
Algorithms require numerical input.
Example:
Gender:
Male → 0
Female → 1
Techniques:
Label Encoding
One-Hot Encoding
3.5 Feature Selection
Remove irrelevant features to:
Reduce overfitting
Improve accuracy
Reduce computation time
Step 4: Dataset Splitting
Splitting ensures proper evaluation and avoids overfitting.
4.1 Training Set (70%)
Used to:
Learn model parameters
Fit the model
The model sees this data during training.
4.2 Validation Set (15%)
Used to:
Tune hyperparameters
Select best model
Example:
Choosing:
Value of C in SVM
Number of trees in Random Forest
4.3 Test Set (15%)
Used to:
Evaluate final model performance
Provide unbiased performance estimate
Important:
The test set must not be used during training.
Why Dataset Splitting is Important?
If we train and test on the same data:
Model may memorize patterns
Performance appears high
Poor real-world performance
This problem is called Overfitting.
Alternative: Cross-Validation
Instead of fixed 70-15-15 split, we can use:
k-Fold Cross-Validation
Advantages:
✔ Better performance estimate
✔ Uses entire dataset efficiently
Complete Example
Problem: Predict loan approval.
Step 1: Define problem → Classification
Step 2: Collect data → Income, Credit Score, Age
Step 3: Preprocess data → Handle missing values, scale features
Step 4: Split dataset → 70% train, 15% validation, 15% test
Step 5: Train model
Step 6: Evaluate accuracy
Supervised Learning Algorithms
1. Linear Regression
Definition:
Linear Regression is a supervised learning algorithm used to predict continuous numerical
values. It assumes a linear relationship between input and output.
The relationship is represented by:
y=mx+b
Where
x = input variable
y = predicted output
m = slope
b = intercept
Example
Predict house price based on house size.
House Size ([Link]) Price (₹ Lakhs)
1000 30
1500 45
2000 60
The model learns the relationship between size and price.
If a new house has 1800 [Link], the model predicts its price based on the learned line.
Applications
• House price prediction
• Sales forecasting
• Temperature prediction
2. Logistic Regression
Definition
Logistic Regression is used for classification problems where the output belongs to specific
categories.
It predicts the probability of belonging to a class.
Example
Email spam detection.
Email Message Label
“Win money now” Spam
“Meeting at 5 PM” Not Spam
The model learns patterns from these emails.
If a new email arrives:
“Congratulations! You won a prize”
The algorithm calculates probability:
Spam probability = 0.9
Since it is high, the email is classified as Spam.
Applications
Spam detection
Disease prediction
Fraud detection
3. Decision Tree
Definition
A Decision Tree is a tree-structured model used for classification and regression.
It splits data based on decision rules.
Example
Suppose we want to decide whether to play cricket.
Weather Play Cricket
Sunny No
Rainy No
Cloudy Yes
Decision Tree:
Weather?
| | |
Sunny Rainy Cloudy
| | |
No No Yes
The model uses conditions to make decisions.
Applications
• Loan approval
• Medical diagnosis
• Customer classification
4. Random Forest
Definition
Random Forest is an ensemble algorithm that combines many decision trees.
Each tree makes a prediction, and the final prediction is based on majority voting.
Example
Predict whether a patient has a disease.
Tree Prediction
Tree 1 Disease
Tree 2 No Disease
Tree 3 Disease
Tree 4 Disease
Final result → Disease (majority vote).
Applications
• Medical diagnosis
• Credit scoring
• Stock market prediction
5. Support Vector Machine (SVM)
Definition
Support Vector Machine is used mainly for classification problems.
It separates data into classes using a boundary called a hyperplane.
Example
Classifying fruits using weight.
Weight Fruit
120g Apple
150g Apple
250g Orange
270g Orange
SVM finds the best boundary that separates apples and oranges.
New fruit weight = 240g
The model classifies it as Orange.
Applications
• Image classification
• Face recognition
• Text classification
6. K-Nearest Neighbors (KNN)
Definition
KNN is a simple algorithm that classifies data based on the nearest neighbors.
It checks the k closest data points and assigns the majority class.
Example
Suppose we classify a fruit based on weight and color.
Nearby fruits:
Fruit Color
Apple Red
Apple Red
OrangeOrange
If most nearby fruits are apples, the new fruit is also classified as Apple.
Applications
• Recommendation systems
• Pattern recognition
• Image classification
Final Summary
Algorithm Example
Linear Regression Predict house price
Logistic Regression Spam email detection
Decision Tree Loan approval
Random Forest Disease prediction
SVM Image classification
KNN Product recommendation
In simple words
Linear Regression → Predict numbers
Logistic Regression → Predict categories
Decision Tree → Rule-based decisions
Random Forest → Many trees combined
SVM → Best separating boundary
KNN → Check nearest data points
Introduction
In supervised learning, we cannot train and evaluate a model using the same data.
If we use the same dataset for both training and testing, the model may simply memorize
the data instead of learning real patterns. To properly evaluate a machine learning model,
the dataset is divided into three parts: Training Set, Validation Set, and Test Set.
This division allows us to measure how well the model performs on unseen data and
ensures that the model generalizes well to new situations.
Training Set
The training set is the portion of the dataset used to train the machine learning model.
During this stage, the algorithm analyzes the input data and learns the relationship
between the input features and the output labels.
Example:
From this data, the model learns that students who study more hours
are more likely to pass the exam.
Validation Set
The validation set is used to evaluate the model during training and to tune the model.
It helps in selecting the best algorithm and adjusting important parameters
called hyperparameters.
Example:
Since Model B has the highest validation accuracy, it is selected as the best model.
The validation set works like a practice test before the final exam.
Test Set
The test set is used to evaluate the final performance of the trained model.
This dataset is completely new and has never been used during training or validation.
Example:
If the predicted results match the actual results, the model is considered accurate.
Accuracy Formula:
The test set acts like the final exam for the machine learning model.
Without proper data splitting, the model may perform well during training
but fail when it encounters new real-world data.
Proper dataset splitting ensures that the model learns meaningful patterns
and can make accurate predictions on unseen data.
Real-Life Analogy
Machine learning training can be compared to preparing for an exam.
This process ensures that the student (or model) truly understands the
concepts and can perform well when faced with new questions.
Summary
Training, validation, and test datasets are essential components of
supervised learning.
By dividing the dataset in this way, machine learning models can learn
patterns effectively and perform well on new unseen data.
Learning Curves
Learning Curves in Machine Learning
Introduction
Learning curves are graphical representations used in machine learning to understand how well a model
learns from training data. They show the relationship between the amount of training data used and the
performance of the machine learning model. By analyzing learning curves, researchers and students can
identify whether a model is learning properly or facing problems such as underfitting or overfitting.
This axis represents the amount of data used to train the model. Initially the model is trained with a small
number of examples, and gradually more data is added.
This axis represents how well the model performs. Sometimes the graph shows error rate, and sometimes
it shows accuracy. Lower error means better performance.
The training error shows how well the model performs on the training data itself. When the model is
trained on a small amount of data, the training error is usually low because the model can easily
memorize the data.
The validation error shows how well the model performs on new unseen data (validation dataset). This
helps to measure the generalization ability of the model.
Example:
Suppose we try to predict student marks using only one simple rule when many factors like study time,
attendance, and practice affect marks. The model becomes too simple and cannot learn the real pattern.
Example:
If a model memorizes exact answers from training questions instead of learning the concept, it will fail
when new questions appear.
Conclusion
Learning curves are an important diagnostic tool in machine learning. They help researchers understand
whether a model is underfitting, overfitting, or learning properly. By analyzing learning curves, we can
decide how to improve the model, such as adding more data, choosing a better algorithm, or adjusting
model complexity.
.
Learning Model Generalization
Learning model generalization refers to the ability of a machine learning model to perform
accurately on new, unseen data after being trained on a dataset. Instead of memorizing the
training data, the model should learn the general patterns and relationships within the data.
A model with good generalization:
• Learns the true patterns in the training data.
• Makes accurate predictions on new data.
• Avoids memorizing noise or specific examples.
1. Meaning of Generalization
Generalization means the model can apply its learned knowledge to different but similar
situations.
For example, if a model is trained to recognize handwritten digits, it should correctly identify
digits written by new people whose handwriting it has never seen before.
If the model only works well on the training examples but fails on new examples, then it does
not generalize well.
2. Why Generalization is Important
In real-world applications, the data used during training is only a small sample of all possible
data. Therefore, the model must be able to predict correctly for future data.
Examples:
• Spam detection: classify new emails as spam or not spam.
• Medical diagnosis: predict diseases for new patients.
• Weather prediction: forecast future weather conditions.
Without generalization, a model is not useful in practical applications.
Overfitting
Overfitting occurs when the model learns the training data too well, including noise and small
fluctuations.
Characteristics:
• Very low training error
• High testing error
• Poor performance on new data
Example:
A very deep decision tree that memorizes all training samples.
Here:
• Students have lower height and weight
• Adults have higher height and weight
SVM will plot these data points on a graph and draw a line that separates Students and Adults.
The algorithm chooses the line that maximizes the gap between the two groups.
3. Hyperplane
A hyperplane is the decision boundary used by SVM to separate different classes.
Example:
If we represent height and weight on a graph:
• One side of the line → Students
• Other side → Adults
Mathematically, a hyperplane can be represented as:
w⋅x+b=0w \cdot x + b = 0w⋅x+b=0
Where:
• w = weight vector
• x = input feature vector
• b = bias term
This equation defines the separating boundary.
4. Support Vectors
Support vectors are the data points that lie closest to the decision boundary (hyperplane).
These points are very important because:
• They define the position of the hyperplane
• If support vectors change, the hyperplane also changes
• Other distant points do not significantly affect the boundary
In simple words:
Support vectors are the critical training samples that determine the classifier.
5. Margin
The margin is the distance between the hyperplane and the nearest data points from each
class.
SVM tries to maximize this margin.
Why maximize margin?
• Larger margin → better generalization
• Less chance of misclassification
So SVM is also called a maximum margin classifier.
6. Types of SVM
1. Linear SVM
Used when data can be separated by a straight line.
Example:
Two groups of points clearly separated.
2. Non-Linear SVM
Used when data cannot be separated by a straight line.
Example:
Data points are mixed in circular patterns.
To solve this, SVM uses something called the Kernel Trick, which transforms data into a higher
dimension where separation becomes easier.
Common kernels:
• Linear Kernel
• Polynomial Kernel
• Radial Basis Function (RBF)
• Sigmoid Kernel
7. Advantages of SVM
• Works well with high-dimensional data
• Effective for small datasets
• Good generalization ability
• Robust to overfitting when margin is maximized
8. Disadvantages of SVM
• Training time can be slow for very large datasets
• Choosing the right kernel can be difficult
• Less effective when data contains a lot of noise
9. Applications of SVM
Support Vector Machines are widely used in many real-world applications:
1. Spam Email Detection
Classifies emails as spam or not spam.
2. Face Recognition
Identifies and verifies human faces in images.
3. Text Classification
Used in tasks such as sentiment analysis and document categorization.
4. Image Classification
Classifies images into categories such as animals, objects, or scenes.
5. Bioinformatics
Used for gene classification and protein analysis.
Random Forest
Random Forest is a supervised machine learning algorithm used for classification and
regression problems. It belongs to the category of ensemble learning methods.
Ensemble learning means combining multiple models to improve the overall performance of
the system.
Instead of using a single decision tree, Random Forest builds many decision trees and
combines their predictions to produce a more accurate and stable result.
1. Basic Idea of Random Forest
A decision tree may sometimes make incorrect predictions because it learns from only one view
of the data. Random Forest solves this problem by:
• Creating multiple decision trees
• Training each tree on different subsets of the data
• Combining the results of all trees
The final prediction is made using majority voting (for classification) or average prediction
(for regression).
This approach reduces overfitting and improves prediction accuracy.
2. How Random Forest Works
Random Forest follows several steps during training and prediction.
Step 1: Random Sampling of Data (Bootstrap Sampling)
From the original dataset, random subsets of data are selected.
Each subset may contain different samples from the original dataset.
This process is called bootstrapping.
Step 2: Build Multiple Decision Trees
For each subset of data:
• A decision tree is constructed.
• Each tree learns patterns independently.
Additionally, during tree construction, the algorithm randomly selects a subset of features at
each split instead of considering all features.
This increases diversity among the trees.
Step 3: Each Tree Makes a Prediction
When new input data is given:
• Every decision tree in the forest makes its own prediction.
Since each tree was trained on slightly different data, their predictions may differ.
Healthcare:
Disease diagnosis and medical prediction.
Finance:
Fraud detection and credit scoring.
E-commerce:
Product recommendation systems.
Image Processing:
Face recognition and object detection.
EXAMPLES
SVM finds the best separating line (hyperplane) between the two groups.
Support vectors are the points closest to that line.