Unit3 - Understanding Supervised Learning
Unit3 - Understanding Supervised Learning
Contents
Understanding Supervised Learning................................................................................. 2
Overview and Concepts of Supervised Learning........................................................... 2
Classification: ........................................................................................................... 2
Regression:............................................................................................................... 3
Difference between Classification and Regression ....................................................... 4
Components (Process) of Supervised Machine Learning: ............................................. 5
Features ................................................................................................................... 5
Labels: ...................................................................................................................... 6
Dataset .......................................................................................................................... 6
Training Data, Test Data, validation Data ................................................................. 8
Overfitting, Underfitting ............................................................................................ 10
What is Underfitting? ............................................................................................. 10
What is Overfitting? ............................................................................................... 10
Python Code for Simple Linear Regression ................................................................. 11
Cost/Loss functions: ................................................................................................... 12
Regression Cost Functions ......................................................................................... 13
Mean Squared Error (MSE)..................................................................................... 13
Mean Absolute Error (MAE) ................................................................................... 15
Root Mean Square Error (RMSE) ............................................................................ 16
Understanding R2 ................................................................................................... 17
Classification: ............................................................................................................. 18
Types of Classification ............................................................................................ 18
Classification Algorithms ........................................................................................ 19
Logistic Regression in Machine Learning .................................................................... 20
Types of Logistic Regression ................................................................................... 21
Assumptions of Logistic Regression ........................................................................ 21
Understanding Sigmoid Function ........................................................................... 22
Python Code for Classification(Binary Logistic Regression – Single Input) .............. 23
Confusion Matrix:................................................................................................... 24
Metrics based on Confusion Matrix Data ............................................................... 24
Example of above Metrics: ..................................................................................... 26
Classification:
▪ Classification is a type of supervised machine learning where algorithms learn
from the data to predict an outcome or event in the future.
▪ For example: A bank may have a customer dataset containing credit history,
loans, investment details, etc. and they may want to know if any customer will
default. In the historical data, we will have Features and Target.
▪ Features will be attributes of a customer such as credit history, loans,
investments, etc.
▪ Target will represent whether a particular customer has defaulted in the past
(normally represented by 1 or 0 / True or False / Yes or No).
Regression:
▪ Regression is a type of supervised machine learning where algorithms learn from
the data to predict continuous values such as sales, salary, weight, or
temperature.
▪ For example: A dataset containing features of the house such as lot size, number
of bedrooms, number of baths, neighbourhood, etc. and the price of the house.
▪ A Regression algorithm can be trained to learn the relationship between the
features and the price of the house.
▪ There are many machine learning algorithms that can be used for regression
tasks.
▪ Some of them are:
• Linear Regression
• Multiple Linear Regression
• Ridge Regression
• Lasso Regression
• Polynomial Regression
• Decision Tree Regressor
• K Nearest Neighbor Regressor
• Random Forest Regressor
The output variable must be either The output variable has to be a discrete
continuous nature or real value. value.
They are used with continuous data. They are used with discrete data.
Features
▪ A feature is an individual measurable property or characteristic of the
phenomenon you are observing.
▪ In simple terms, these are the inputs or variables used to make a prediction.
▪ They are also known as independent variables, predictors, or attributes.
▪ Features are selected and pre-processed to ensure they are in a format the
computer can understand (often converting text to numbers).
➢ Characteristics of Features
• Measurable: Features are quantifiable properties that can be measured
and recorded.
• Independent: Each feature should ideally be independent of the others,
providing unique information to the model.
• Varied Types: Features can be numerical (e.g., age, height), categorical
(e.g., gender, color), or even text-based (e.g., reviews, comments).
Shri [Link] college of CS and BM Page | 5
Data Analytics using Python Unit – 3 Understanding Supervised Learning
➢ Examples of Features
• In a dataset predicting house prices, features might include the number of
bedrooms, square footage, and location.
• For a spam email classifier, features could be the presence of certain
keywords, the length of the email, and the sender's address.
Labels:
▪ A label, also known as the target variable or dependent variable, is the output
that the model is trained to predict.
▪ In supervised learning, labels are the known outcomes that the model learns to
associate with the input features during training.
➢ Characteristics of Labels
• Dependent: Labels depend on the input features and are the result of the
model's prediction.
• Categorical or Numerical: Labels can be categorical (e.g., spam or not
spam) or numerical (e.g., price of a house).
➢ Examples of Labels
• In a house price prediction model, the label would be the actual price of
the house.
• For a spam email classifier, the label would be whether the email is spam
or not.
Dataset
▪ A dataset is a structured collection of related data, usually organized in rows and
columns that represents information about a specific category or domain.
▪ It forms the foundation for many operations, techniques and models used across
industries.
➢ Importance of Dataset:
Some reasons why datasets are important in analysis and machine learning
are:
• Analysis: Provide the raw material required for analysis and decision
making.
• Training Machine Learning Models: Enable the training and testing of
machine learning and AI models.
• Discover Patterns and Correlations: Help uncover patterns, correlations
and insights across domains.
• Innovation: Support research and development in industries like
healthcare, finance and education.
• Evaluation and Standards: Allow reproducibility and benchmarking in
academic and professional projects.
➢ Types of Datasets
There are various types of datasets available out there. Some of them are:
• Numerical Dataset: Contains numeric data points that can be analysed
using mathematical or statistical methods. For example, temperature
dataset.
• Categorical Dataset: Represents discrete categories or groups such as
color, gender, occupation or sports.
• Time Series Dataset: Records data over a period of time to track trends or
changes. For example, stock prices.
• Ordered Dataset: Contains ranked or ordinal data where the order matters
but not the exact difference between values. Example can be customer
reviews, survey ratings or movie rankings.
• Image Dataset: Consists of images used for classification, recognition or
analysis tasks. For example, medical imaging for disease detection.
• Web Dataset: Collected from APIs or web sources, usually stored in
structured formats like JSON for further analysis.
• File based Dataset: Stored in files such as CSV, Excel (.xlsx) or text files for
easy access and manipulation.
➢ Properties of Dataset
Here are the key properties that define a dataset:
• Center of Data: Refers to the "middle" value of a dataset, usually measured
using mean, median or mode. It helps identify where most of the values lie
and gives a sense of the average data point.
Shri [Link] college of CS and BM Page | 7
Data Analytics using Python Unit – 3 Understanding Supervised Learning
• Skewness of Data: This indicates how symmetrical the data distribution
is. A perfectly symmetrical distribution like a normal distribution has a
skewness of 0 while positive or negative skewness indicates a tilt in one
direction.
• Spread: This describes how much the data points vary from the
center. Common measures include standard deviation or variance, which
quantify how far individual points deviate from the average.
• Outliers: These are data points that fall significantly outside the overall
pattern. Identifying outliers can be important as they might influence
analysis results and require further investigation.
• Correlation: It shows how strongly variables are related. A positive
correlation means both increase together, a negative correlation means
they move in opposite directions and no correlation means no clear
relationship.
• Probability distribution: Understanding the distribution like
normal, uniform, binomial helps us predict how likely it is to find certain
values within the data and choose appropriate statistical methods for
analysis.
➢ Features of a Dataset
Some possible features of a dataset are:
• Numerical Features: These may include numerical values such as height,
weight and so on. These may be continuous over an interval or discrete
variables.
• Categorical Features: These include multiple classes or categories such as
gender, colour and so on.
• Size of the Data: It refers to the number of entries and features it contains
in the file containing the Dataset.
• Data Entries: These refer to the individual values of data present in the
Dataset.
• Target Variable: This is the main feature in a dataset that we want to
predict or explain using the other features.
➢ Training Data:
• The training set is the portion of the dataset used to fit the machine
learning model.
• During training, the algorithm learns patterns, relationships and
parameters (such as weights in neural networks or coefficients in
regression models) directly from this data.
• The model repeatedly adjusts itself to minimize the training error using
optimization techniques like gradient descent.
▪ The model has full access to the labels and features in this dataset.
▪ Learning happens exclusively on the training set.
▪ Performance on training data does not reflect real-world
performance.
➢ Validation Data:
• The validation set is a separate subset of data used to tune model
hyperparameters and make design decisions during training.
• Unlike the training set, it is not used to update model weights directly.
• Instead, it provides an unbiased estimate of model performance during
development.
▪ Used during model selection and optimization
▪ Helps detect overfitting early
▪ Often involved in techniques like early stopping
➢ Test Data:
• The testing set is a completely independent subset used to evaluate the
final model’s performance after all training and tuning are complete.
• It simulates how the model will perform on unseen, real-world data and
provides the most reliable estimate of generalization.
▪ Used only once (or very sparingly)
▪ No model decisions should be based on test results
▪ Represents real deployment conditions
Shri [Link] college of CS and BM Page | 9
Data Analytics using Python Unit – 3 Understanding Supervised Learning
❖ Overfitting, Underfitting
▪ Machine learning models should learn useful patterns from training data.
▪ When a model learns too little or too much, we get underfitting or overfitting.
▪ Underfitting means that the model is too simple and does not cover all real
patterns in the data.
▪ Overfitting means that the model learns not just the underlying pattern, but also
noise or random quirks in the training data. model memorizes training data.
▪ A good model finds the right spot, it is complex enough to capture real patterns,
but not so complex that it “memorizes” noise
What is Underfitting?
▪ Underfitting happens when the model fails to learn important patterns.
▪ It performs poorly on both training and testing data.
▪ Underfitting happens due to:
• Model is too simple
• Very high regularization
• Features are weak or missing
• Not enough training
• High bias
▪ Example: Trying to predict house prices, which depend on size, location, age, etc.,
using only the number of rooms. The model is too simple (high bias) and will likely
make poor predictions for most houses.
What is Overfitting?
▪ Overfitting happens when the model learns too much from the training data,
including noise and outliers.
▪ It performs very well on training data but poorly on test data.
▪ Overfitting happens due to:
• Model too complex
• Too many features
• Very little data
Shri [Link] college of CS and BM Page | 10
Data Analytics using Python Unit – 3 Understanding Supervised Learning
• No regularization
• High variance
▪ Example: Creating a highly complex polynomial regression model that perfectly
passes through every single data point in your house price training set. This model
might have near-zero error on the training data, but it will perform terribly on
new houses because it has learned the noise specific to the training set (high
variance).
❖ Cost/Loss functions:
▪ The loss function quantifies how much a model‘s prediction deviates from the
ground truth for one particular object.
▪ So, when we calculate loss, we do it for a single object in the training or test sets.
▪ The term cost is often used interchangeably with loss. However, the cost function
measures the model’s error over a group of data points, while the loss function
measures the error for a single data instance.
▪ In machine learning, a cost function tells you how wrong your model’s predictions
are compared to the true values.
▪ A high cost means the model is making large errors, a low cost means it is doing
well.
▪ The lower the cost, the better the model is at predicting reality
▪ Formula:
▪ Where:
• The Cost Function Shape (Parabola): When you plot the errors, they form
a smooth U-shaped Parabola.
▪ The Global Minimum: The bottom of this parabola represents the
point of lowest error (the "Best Fit" line).
▪ Smoothness: Unlike a "V" shape, the parabola is smooth at the
bottom, making it perfectly differentiable.
• Sensitivity to Outliers: Because of the squaring, MSE penalizes large errors
heavily.
▪ A mistake of 10 results in a penalty of 100.
▪ A mistake of 2 results in a penalty of only 4.
• The Pull Effect: The model is so "scared" of these large penalties that it will
actually shift its line toward outliers to minimize that squared error, even if
it makes the predictions for normal data points less accurate.
➢ Working of RMSE:
• Mathematical Operation: Square Root of the Mean Squared Error (MSE)
▪ Purpose: It "undoes" the squaring process to return the error value
to the original units of your data (e.g., if you are predicting salary in
Dollars, RMSE gives you the error in Dollars, whereas MSE gives it in
"Squared Dollars").
▪ Always Positive: Because it involves squaring and then a square root,
RMSE will always be a positive number
➢ What is R-Squared ?
• R-squared (R^2), also known as the Coefficient of Determination, is a
statistical measure that represents the goodness of fit of a regression
model.
• The value of R-square lies between 0 to 1.
• Where we get R-square equals 1 when the model perfectly fits the data and
there is no difference between the predicted value and actual value.
• However, we get R-square equals 0 when the model does not predict any
variability in the model and it does not learn any relationship between the
dependent and independent variables.
❖ Classification:
▪ Classification is a supervised machine learning technique used to predict labels or
categories based on input data.
▪ The goal is to assign each data point to a predefined class, such as spam vs. non-
spam emails or diseased vs. healthy patients.
▪ A classification model might be trained on dataset of images labeled as either
dogs or cats and it can be used to predict the class of new and unseen images as
dogs or cats based on their features such as color, texture or shape.
Types of Classification
▪ When we talk about classification in machine learning, we are talking about the
process of sorting data into categories based on specific features or
characteristics.
▪ Following are the types:
1. Binary Classification
• In binary classification, the goal is to sort the data into two distinct
categories.
• Think of it like a simple choice between two options.
• Imagine a system that sorts emails into either spam or not spam.
3. Multi-Label Classification
• In multi-label classification single piece of data can belong to multiple
categories at once.
• Unlike multiclass classification where each data point belongs to only one
class, multi-label classification allows datapoints to belong to multiple
classes.
• A movie recommendation system could tag a movie as both action and
comedy. The system checks various features (like movie plot, actors or
genre tags) and assigns multiple labels to a single piece of data, rather than
just one.
Classification Algorithms
▪ There are various types of classifiers algorithms. Some of them are :
1. Linear Classifiers:
• Linear classifier models create a linear decision boundary between classes.
• They are simple and computationally efficient.
Shri [Link] college of CS and BM Page | 19
Data Analytics using Python Unit – 3 Understanding Supervised Learning
• Some of the linear classification models are as follows:
▪ Logistic Regression
▪ Support Vector Machines having kernel = 'linear'
▪ Single-layer Perceptron
▪ Stochastic Gradient Descent (SGD) Classifier
2. Non-linear Classifiers:
• Non-linear models create a non-linear decision boundary between classes.
• They can capture more complex relationships between input features and
target variable.
• Some of the non-linear classification models are as follows:
▪ K-Nearest Neighbours
▪ Kernel SVM
▪ Naive Bayes
▪ Decision Tree Classification
▪ Ensemble learning classifier
▪ Random Forests
2. Precision
• Precision focus on the quality of the model’s positive predictions.
• It tells us how many of the "positive" predictions were actually correct.
Shri [Link] college of CS and BM Page | 24
Data Analytics using Python Unit – 3 Understanding Supervised Learning
• It is important in situations where false positives need to be minimized such
as detecting spam emails or fraud. The formula of precision is:
3. Recall
• Recall measures how good the model is at predicting positives.
• It shows the proportion of true positives detected out of all the actual
positive instances.
• High recall is essential when missing positive cases has significant
consequences like in medical tests.
4. F1-Score
• F1-score combines precision and recall into a single metric to balance their
trade-off.
• It provides a better sense of a model’s overall performance particularly for
imbalanced datasets.
• It is helpful when both false positives and false negatives are important
though it assumes precision and recall are equally important but in some
situations, one might matter more than the other.
• Type 2 error:
▪ This occurs when the model fails to predict a positive instance even
though it is actually positive. This is also known as a false negative.
▪ Type 2 Errors impact the recall of a model which measures how well
the model identifies all actual positive cases.
Shri [Link] college of CS and BM Page | 25
Data Analytics using Python Unit – 3 Understanding Supervised Learning
▪ A Type II Error is a "Miss." It happens when the model predicts that
nothing is happening (Negative), but in reality, something important
is happening (Positive).
1. Precision (Exactness)
• Question: "Of all the people the model predicted as having the disease,
how many actually had it?"
• Logic: It looks at the Predicted Disease column.
• Calculation: 4/(4+1)
• Meaning: When the model says a patient is sick, it is right 80% of the time.
High precision means fewer "False Alarms" (Type I Errors).
• Calculation: 4/(4 + 2)
• Meaning: The model caught 67% of the total sick people. Low recall is
dangerous in medicine because it means you missed 33% of the sick
patients (Type II Errors).
• Meaning: An F1-Score of 0.73 shows a decent balance, but the low recall is
pulling it down.
• Calculation: (4+3)/10
• Meaning: The model is correct 70% of the time across the whole dataset.