Introduction To Machine LearningG
Introduction To Machine LearningG
Machine learning (ML) allows computers to learn and make decisions without being
explicitly programmed. It involves feeding data into algorithms to identify patterns and
make predictions on new data. It is used in various applications like image recognition,
speech processing, language translation, recommender systems, etc. In this article, we
will see more about ML and its core concepts.
Machine Learning Foundations
Foundations
Logic and reasoning: Ancient Greek philosophers like Aristotle introduced concepts of
logical reasoning that influenced the development of AI and machine learning.
Neural networks: In 1943, Walter Pitts and Warren McCulloch published the first
mathematical model of a neural network, providing a framework for how artificial
neurons could mimic human thought.
Biological inspiration: Donald Hebb's 1949 book, "The Organization of Behavior,"
proposed a theory of how brain cells communicate, which became a foundational concept
for modifying the relationships between nodes in artificial neural networks.
Probability and statistics: Mathematical concepts like Bayes' Theorem (1812) and Least
Squares were developed in the 18th and 19th centuries, providing the statistical and
mathematical underpinnings for machine learning algorithms.
It also includes exploring the data to understand patterns and creating new features from
existing ones.
Data Collection
Data Collection in ML
After defining the problem, the next step is collecting data from various sources to train
the model.
Sources of Data:
Data pre-processing, also known as data wrangling, is the process of cleaning raw data to
improve the accuracy and performance of the machine learning model. Since raw data is
often messy and unstructured, it is important to fix issues like missing values, duplicate
data, invalid data, and noise before using it for analysis. This step makes the data more
clean, consumable, and useful for building a better model.
Analyzing Data
After cleaning the data, the next step is to visualize and explore it. Tools like Power BI
and Tableau are used to find patterns and trends. This helps in making better choices for
feature engineering and model selection.
Model Development
Model Selection
Choosing the right model depends on the data characteristics, problem complexity and
desired outcomes. This step directly affects the performance and results of the model.
Model Training
The algorithm is fed with pre-processed data to learn patterns and relationships.
Consistently adjusting parameters improves prediction rate and accuracy, making the
model reliable in real-world scenarios.
Model Evaluation
The model is evaluated using metrics like accuracy, precision, recall and F1 score. If
performance is not satisfactory, hyper-parameters are tuned to improve accuracy. If still
not satisfied, we go back to model selection and retrain the model.
Model Deployment
The trained model is integrated into real-world systems and made available to users.
Before deploying, two things are checked:
The model is continuously monitored for issues and performance. If an issue is found, the
model is retrained with new data or architecture is modified. If the issue cannot be solved,
it becomes a new problem statement and the ML life cycle starts again.
Applications
Healthcare Diagnostics
Fraud Detection in Finance
Product Recommendations
Speech and Language Processing
Autonomous Vehicles
Overview of ML
Solving Complex Problems ML learns from data and predicts outcomes for complex tasks
like image recognition, speech recognition and language translation.
Handling Large Data ML quickly processes huge amounts of data and provides valuable
insights and real-time predictions like fraud detection and personalized recommendations.
Self-Improvement ML models get smarter over time with more data like voice assistants
learning accents and self-driving cars improving decisions.
A machine learns by finding patterns in data and improving without being explicitly
programmed. Here is how:
ML system design follows an iterative lifecycle with core phases to ensure the system is
reliable, scalable and delivers real-world value
Problem Definition
Define what the system needs to do (spam detection, price prediction etc.)
Model Development
Model Deployment
Applications
Limitations
Supervised Learning
Supervised learning algorithms or methods are the most commonly used ML algorithms.
This method or learning algorithm takes the data sample i.e. the training data and its
associated output i.e. labels or responses with each data sample during the training
process.
The main objective of supervised learning algorithms is to learn an association between
input data samples and corresponding outputs after performing multiple training data
instances.
For example, we have
x: Input variables and
Y: Output variable
Now, apply an algorithm to learn the mapping function from the input to output as
follows −
Y=f(x)
Now, the main objective would be to approximate the mapping function so well that even
when we have new input data (x), we can easily predict the output variable (Y) for that
new input data.
It is called supervised because the whole process of learning can be thought as it is being
supervised by a teacher or supervisor. Examples of supervised machine learning
algorithms includes Decision tree, Random Forest, KNN, Logistic Regression etc.
Based on the ML tasks, supervised learning algorithms can be divided into the following
two broad classes −
Classification
Regression
Classification
The key objective of classification-based tasks is to predict categorial output labels or
responses for the given input data. The output will be based on what the model has
learned in the training phase. As we know the categorial output responses means
unordered and discrete values, hence each output response will belong to a specific class
or category. We will discuss Classification and associated algorithms in detail in the
upcoming chapters also.
Classification Models
Followings are some common classification models −
Logistic Regression
Decision Trees
Random Forest
K-nearest Neighbour
Support Vector Machine
Naive Bayes
Linear Discriminant Analysis
Neural Networks
Regression
The key objective of regression-based tasks is to predict output labels or responses, which
are continuous numeric values, for the given input data. The output will be based on what
the model has learned in its training phase. Basically, regression models use the input data
features (independent variables) and their corresponding continuous numeric output
values (dependent or outcome variables) to learn specific associations between inputs and
corresponding outputs. We will discuss regression and associated algorithms in detail in
further chapters.
Regression Models
Followings are some common regression models −
Linear Regression
Ridge regression
Decision Trees
Random Forest
K-nearest Neighbour
Neural Network Regression
Unsupervised Learning
Clustering
Clustering methods are one of the most useful unsupervised ML methods. These
algorithms used to find similarity as well as relationship patterns among data samples and
then cluster those samples into groups having similarity based on features. The real-world
example of clustering is to group the customers by their purchasing behavior.
Clustering Models
Followings are some common clustering models −
K-Means Clustering
Hierarchical Clustering
Mean-shift Clustering
DBSCAN Clustering
HDBSCAN Clustering
BIRCH Clustering
Affinity Propagation
Agglomerative Clustering
Association
Another useful unsupervised ML method is Association which is used to analyze large
dataset to find patterns which further represents the interesting relationships between
various items. It is also termed as Association Rule Mining or Market basket
analysis which is mainly used to analyze customer shopping patterns.
Association Models
Followings are some common association models −
Apriori Algorithm
Eclat algorithm
FP-growth algorithm
Dimensionality Reduction
This unsupervised ML method is used to reduce the number of feature variables for each
data sample by selecting set of principal or representative features. A question arises here
is that why we need to reduce the dimensionality? The reason behind is the problem of
feature space complexity which arises when we start analyzing and extracting millions of
features from data samples. This problem generally refers to curse of dimensionality.
PCA (Principal Component Analysis), K-nearest neighbors and discriminant analysis are
some of the popular algorithms for this purpose.
Dimensionality Reduction Models
Followings are some common dimensionality Reduction models −
Principal Component Analysis(PCA)
Autoencoders
Singular value decomposition (SVD)
Anomaly Detection
This unsupervised ML method is used to find out the occurrences of rare events or
observations that generally do not occur. By using the learned knowledge, anomaly
detection methods would be able to differentiate between anomalous or a normal data
point. Some of the unsupervised algorithms like clustering, KNN can detect anomalies
based on the data and its features.
Semi-supervised Learning
Semi-supervised learning algorithms or methods are neither fully supervised nor fully
unsupervised. They basically fall between the two i.e. supervised and unsupervised
learning methods. These kinds of algorithms generally use small supervised learning
component i.e. small amount of pre-labeled annotated data and large unsupervised
learning component i.e. lots of unlabeled data for training. We can follow any of the
following approaches for implementing semi-supervised learning methods −
The first and simple approach is to build the supervised model based on small amount of
labeled and annotated data and then build the unsupervised model by applying the same
to the large amounts of unlabeled data to get more labeled samples. Now, train the model
on them and repeat the process.
The second approach needs some extra efforts. In this approach, we can first use the
unsupervised methods to cluster similar data samples, annotate these groups and then use
a combination of this information to train the model.
Reinforcement Learning
Reinforcement learning methods are different from previously studied methods and very
rarely used also. In this kind of learning algorithms, there would be an agent that we want
to train over a period of time so that it can interact with a specific environment. The agent
will follow a set of strategies for interacting with the environment and then after
observing the environment it will take actions regards the current state of the
environment. The following are the main steps of reinforcement learning methods −
Step 1 − First, we need to prepare an agent with some initial set of strategies.
Step 2 − Then observe the environment and its current state.
Step 3 − Next, select the optimal policy regards the current state of the environment and
perform important action.
Step 4 − Now, the agent can get corresponding reward or penalty as per accordance with
the action taken by it in previous step.
Step 5 − Now, we can update the strategies if it is required so.
Step 6 − At last, repeat steps 2-5 until the agent got to learn and adopt the optimal
policies.
Linear Regression
Linear regression is a type of algorithm that tries to find the linear relation between input
features and output values for the prediction of future events. This algorithm is widely
used to perform stock analysis, weather forecasting and others.
K-Nearest Neighbors
The k-Nearest Neighbors (kNN) is a statistical technique that can be used for solving
classification and regression problems. This algorithm classifies or predicts values for
new data by mathematically calculating the nearest distance with other points in training
data.
Let us discuss the case of classifying an unknown object using kNN. Consider the
distribution of objects as shown in the image given below −
The diagram shows three types of objects, marked in red, blue and green colors. When
you run the kNN classifier on the above dataset, the boundaries for each type of object
will be marked as shown below −
Now, consider a new unknown object you want to classify as red, green or blue. This is
depicted in the figure below.
As you see it visually, the unknown data point belongs to a class of blue objects.
Mathematically, this can be concluded by measuring the distance of this unknown point
with every other point in the data set. When you do so, you will know that most of its
neighbors are blue in color. The average distance between red and green objects would
definitely be more than the average distance between blue objects. Thus, this unknown
object can be classified as belonging to blue class.
The kNN algorithm can also be used for regression problems. The kNN algorithm is
available as ready-to-use in most of the ML libraries.
Decision Trees
A Decision tree is a tree-like structure used to make decisions and analyze the possible
consequences. The algorithm splits the data into subsets based on features, where each
parent node represents internal decisions and the leaf node represents final prediction.
A simple decision tree in a flowchart format is shown below −
You would write a code to classify your input data based on this flowchart. The flowchart
is self-explanatory and trivial. In this scenario, you are trying to classify an incoming
email to decide when to read it.
In reality, the decision trees can be large and complex. There are several algorithms
available to create and traverse these trees. As a Machine Learning enthusiast, you need
to understand and master these techniques of creating and traversing decision trees.
Naive Bayes
Naive Bayes is used for creating classifiers. Suppose you want to sort out (classify) fruits
of different kinds from a fruit basket. You may use features such as color, size, and shape
of fruit; for example, any fruit that is red in color, round in shape, and about 10 cm in
diameter may be considered an Apple. So to train the model, you would use these features
and test the probability that a given feature matches the desired constraints. The
probabilities of different features are then combined to arrive at the probability that a
given fruit is an Apple. Naive Bayes generally requires a small number of training data
for classification.
Logistic Regression
Logistic regression is a type of statistical algorithm that estimates the probability of
occurrence of an event.
Look at the following diagram. It shows the distribution of data points in the XY plane.
From the diagram, we can visually inspect the separation of red and green dots. You may
draw a boundary line to separate out these dots. Now, to classify a new data point, you
will just need to determine on which side of the line the point lies.
Support Vector Machines
Support Vector Machines (SVM) algorithm can be typically used for both classification
and regression. For classification tasks, the algorithm creates a hyperplane to separate
data into classes. While for regression, the algorithm tries to fit a regression line with
minimal error.
Look at the following distribution of data. Here the three classes of data cannot be
linearly separated. The boundary curves are non-linear. In such a case, finding the curve's
equation becomes a complex job.
The Support Vector Machines (SVM) come in handy in determining the separation
boundaries in such situations.
Random Forest
Random forest is also a supervised learning algorithm that is flexible for classification
and regression. This algorithm is a combination of multiple decision trees which are
merged to improve the accuracy of prediction .
The following diagram illustrates how the Random Forest Algorithm works −
Gradient Boosting
Gradient boosting combines weak learners(decision trees), to create a strong model. It
builds new models that correct errors of the previous ones. The goal of this algorithm is to
minimize the loss function. It can be efficiently used for classification and regression
tasks.
Advantages of Supervised Learning
Supervised learning algorithms are one of the most popular among the machine learning
models. Some benefits are:-
The goal in supervised learning is well-defined, which improves the prediction accuracy.
Models trained using supervised learning are effective at predicting and classification
since they use labeled datasets.
It can be highly versatile, i.e., applied to various problems, like spam detection, stock
prices, etc.
Disadvantages of Supervised Learning
Though supervised learning is the most used, it comes with certain challenges too. Some
of them are:
Supervised learning requires a large amount of labeled data for the model to train
effectively. It is practically very difficult to collect such huge data; it is expensive and
time-consuming.
Supervised learning cannot predict accurately if the test data is different from the training
data.
Accurately labeling the data is complex and requires expertise and effort.
Applications of Supervised learning
Supervised learning models are widely used in many applications in various sectors,
including the following-
Image recognition − A model is trained on a labeled dataset of images, where each
image is associated with a label. The model is fed with data, which allows it to learn
patterns and features. Once trained, the model can now be tested using new, unseen data.
This is widely used in applications like facial recognition and object detection.
Predictive analytics − Supervised learning algorithms are used to train labeled historical
data, allowing the model to learn patterns and relations between input features and output
to identify trends and make accurate predictions. Businesses use this method to make
data-driven decisions and enhance strategic planning.
What is Unsupervised Machine Learning?
Unsupervised learning, also known as unsupervised machine learning, is a type of
machine learning that learns patterns and structures within the data without human
supervision. Unsupervised learning uses machine learning algorithms to analyze the data
and discover underlying patterns within unlabeled data sets.
Unlike supervised machine learning, unsupervised machine learning models are trained
on unlabeled dataset. Unsupervised learning algorithms are handy in scenarios in which
we do not have the liberty, like in supervised learning algorithms, of having pre-labeled
training data and we want to extract useful patterns from input data.
We can summarize unsupervised learning as −
a machine learning approach or type that
uses machine learning algorithms
to find hidden patterns or structures
within the data without human supervision.
There are many approaches that are used in unsupervised machine learning. Some of the
approaches are association, clustering, and dimensionality reduction. Some examples of
unsupervised machine learning algorithms include K-means clustering, K-nearest
neighbors, etc.
In regression, we train the machine to predict a future value. In classification, we train the
machine to classify an unknown object in one of the categories we define. In short, we
have been training machines so that it can predict Y for our data X. Given a huge data set
and not estimating the categories, it would be difficult for us to train the machine using
supervised learning. What if the machine can look up and analyze the big data running
into several Gigabytes and Terabytes and tell us that this data contains so many distinct
categories?
As an example, consider the voters data. By considering some inputs from each voter
(these are called features in AI terminology), let the machine predict that there are so
many voters who would vote for X political party and so many would vote for Y, and so
on. Thus, in general, we are asking the machine given a huge set of data points X, What
can you tell me about X?. Or it may be a question like What are the five best groups we
can make out of X?. Or it could be even like What three features occur together most
frequently in X?.
This is exactly what Unsupervised Learning is all about.
How does Unsupervised Learning Work?
In unsupervised learning, machine learning algorithms (called self-learning algorithms)
are trained on unlabeled data sets i.e, the input data is not categorized. Based on the tasks,
or machine learning problems such as clustering, associations, etc. and the data sets, the
suitable algorithms are chosen for the training.
In the training process, the algorthims learn and infer their own rules on the basis of the
similarities, patterns and differences of data points. The algorithms learn without any
labels (target values) or pre-training.
The outcome of this training process of algorithm with data sets is a machine learning
model. As the data sets are unlabeled (no target values, no human supervision), the model
is unsupervised machine learning model.
Now the model is ready to perform the unsupervised learning tasks such as clustering,
association, or dimensionality reduction.
Unsupervised learning models is suitable complex tasks, like organizing large datasets
into clusters.
Unsupervised Machine Learning Methods
Unsupervised learning methods or approaches are broadly categorized into three
categories − clustering, association, and dimensionality reduction. Let us discuss these
methods briefly and list some related algorithms −
Clustering
Clustering is a technique used to group a set of objects or data points into clusters based
on their similarities. The goal of this technique is to make sure that the data points within
the same cluster should have more similarities than those in other clusters.
Clustering is sometimes called unsupervised classification because it produces the same
result as classification does but without having predefined classes.
Clustering is one of the popular unsupervised learning approaches. There are several
unsupervised learning algorithms used for clustering like −
K-Means Clustering − This algorithm is used to assign data points to one among the K
clusters based on its distance from the center of the cluster. After assigning each data
point to a cluster, new centroids are recalculated. This is an iterative process until the
centroids no longer change. This shows that the algorithm is efficient and the clusters are
stable.
Mean Shift Algorithm − It is a clustering technique that identifies clusters by finding high
data density areas. It is an iterative process, where mean of each data point is shifted
towards the densest area of the data.
Gaussian Mixture Models − It is a probabilistic model that is a combination of multiple
Gaussian distributions. These models are used to determine which determination a given
data belongs to.
Association Rule Mining
This is rule based technique that is used to discover associations between parameters in
large dataset. It is popularly used for Market Basket Analysis, allows companies to make
decisions and recommendation engines. One of the main algorithms that is used for
Association Rule Mining is the Apriori algorithm.
Apriori Algorithm
Apriori algorithm is a technique used in unsupervised learning to identify data points that
are frequently repeated and discover association rules within transactional data.
Dimensionality Reduction
As the name suggests, dimensionality reduction is used to reduce the number of feature
variables for each data sample by selecting set of principal or representative features.
A question arises here is that, why we need to reduce the dimensionality? The reason
behind this is the problem of feature space complexity which arises when we start
analyzing and extracting millions of features from data samples. This problem generally
refers to "curse of dimensionality". Some popular algorithms in unsupervised learning
that are used for dimensionality reduction are −
Principle Component Analysis
Missing Value Ratio
Singular Value Decomposition
Autoencoders
Algorithms for Unsupervised Learning
Algorithms are very important part in machine learning model training. A machine
learning algorithm is a set of instructions that a program follows to analyze the data and
produce the outcomes. For specific tasks, suitable machine learning algorithms are
selected and trained on the data.
Algorithms used in unsupervised learning generally fall under one of the three categories
− clustering, association, or dimensionality reduction. The following are the most used
unsupervised learning algorithms −
K-Means Clustering
Hierarchical Clustering
Mean-shift Clustering
DBSCAN Clustering
HDBSCAN Clustering
BIRCH Clustering
Affinity Propagation
Agglomerative Clustering
Apriori Algorithm
Eclat algorithm
FP-growth algorithm
Principal Component Analysis(PCA)
Autoencoders
Singular value decomposition (SVD)
Advantages of Unsupervised Learning
Unsupervised learning has many advantages that make it particularly purposeful in
various tasks −
No labeled data required − Unsupervised learning doesn't require a labeled dataset for
training, which makes it easier and cheaper to use.
Discovers hidden patterns − It helps in recognizing patterns and relationships in large
data, which can lead to gaining insights and efficient decision-making.
Suitable for complex tasks − It is efficiently used for various complex tasks like
clustering, anomaly detection, and dimensionality reduction.
Disadvantages of Unsupervised Learning
While unsupervised learning has many advantages, some challenges can occur too while
training the model without human intervention. Some of the disadvantages of
unsupervised learning are:
Difficult to evaluate − Without labeled data and predefined targets, it would be difficult
to evaluate the performance of unsupervised learning algorithms.
Inaccurate outcomes − The outcome of an unsupervised learning algorithm might be
less accurate, especially if the input data has noise and also since the data is not labeled,
the algorithms do not know the exact output.
Applications of Unsupervised Learning
Unsupervised learning provides a path for businesses to identify patterns in large volumes
of data. Some real-world applications of unsupervised learning are:
Customer Segmentation − In business and retail analysis, unsupervised learning is used
to group customers into segments based on their purchases, past activity, or preferences.
Anomaly Detection − Unsupervised learning algorithms are used in anomaly detection to
identify unusual patterns, which is crucial for fraud detection in financial transactions and
network security.
Recommendation Engines − Unsupervised learning algorithms help to analyze large
customer data to gain valuable insights and understand patterns. This can help in target
marketing and personalization.
Natural Language Processing− Unsupervised learning algorithms are used for various
applications. For example, google used to categorize articles in the news section.
What is Anomaly Detection?
This unsupervised ML method is used to find out occurrences of rare events or
observations that generally do not occur. By using the learned knowledge, anomaly
detection methods would be able to differentiate between anomalous or normal data
points.
Some of the unsupervised algorithms, like clustering and KNN, can detect anomalies
based on the data and its features.
Supervised Vs. Unsupervised Learning
Supervised learning algorithms are trained using labeled data. But there might be cases
where data might not be labeled, so how do you gain insights from data that is unlabeled
and messy? Well, to solve these types of cases, unsupervised learning is used.
Fraud Detection
Machine learning is widely used in the finance industry for fraud detection. Fraud
detection is a process of using a machine learning model to monitor transactions and
understand patterns in the dataset to identify fraudulent and suspicious activities.
Machine learning algorithms can analyze vast amounts of transactional data to detect
patterns and anomalies that may indicate fraudulent activity, helping to prevent financial
losses and protect customers.
Algorithmic Trading
Machine learning algorithms are used to identify complex patterns in the large dataset to
discover trading signals which might not be possible for humans.
Some other applications of machine learning in the finance sector are as follows −
Stock market analysis and forecasting
Credit risk assessment and management
Security analysis and portfolio optimization
Asset evaluation and management
E-commerce and Retail
Machine learning is used to enhance the business in e-commerce and retail sector through
recommendation systems and target advertising which improve user experience. Machine
learning makes the process of marketing easy by performing repetitive tasks. Some tasks
where Machine learning is applied are:
Recommendation Systems
Recommendation systems are used to provide personalized recommendations to users
based on their past behavior and preferences and previous interaction with the website.
Machine learning algorithms are used to analyze user data and generate recommendations
for products, services, and content.
Demand Forecasting
Companies use machine learning to understand the future demand for their product or
services based on various factors like market trends, customer behavior and historical
data regarding sales.
Customer Segmentation
Machine learning can be used to segment customers into particular groups with similar
characteristics. The purpose of customer segmentation is to understand customer behavior
and target them with personalized experience.
Automotive Sector
Who would have thought of a car that would move independently without driving?
Machine learning enabled manufacturers to improve the performance of existing products
and vehicles. One massive innovation is the development of autonomous vehicles also
called drive less vehicles which can sense its environment and drive for itself passing the
obstacles without human assistance. It uses machine learning algorithms for continuous
analysis of the surroundings and predicting possible outcomes.
Computer Vision
Computer vision is an application of machine learning that uses algorithms and neural
networks to teach computers to derive meaningful information from digital images and
videos. Computer vision is applied in face recognition, to diagnose diseases based on
MRI scans, and autonomous vehicles.
Object detection and recognition
Image classification and recognition
Faicial recognition
Autonomous vehicles
Object segmentation
Image reconstruction
Manufacturing and Industries
Machine learning is also used in manufacturing and industries to keep a check on the
working conditions of machinery. Predictive Maintenance is used to identify defects in
operational machines and equipment to avoid unexpected outages. This detection of
anomalies would also help with regular maintenance.
Predictive maintenance is a process of using machine learning algorithms to predict
when maintenance will be required on a machine, such as a piece of equipment in a
factory. By analyzing data from sensors and other sources, machine learning algorithms
can detect patterns that indicate when a machine is likely to fail, enabling maintenance to
be performed before the machine breaks down.
Healthcare Sector
Machine learning has also found many applications in the healthcare industry. For
example, machine learning algorithms can be used to analyze medical images and detect
diseases such as cancer or to predict patient outcomes based on their medical history and
other factors.
Some applications of machine learning in healthcare are discussed below −
Medical Imaging and Diagnostics
Machine learning in medical imaging is used to analyze the patterns in the image that
indicate the presence of a particular disease.
Drug Discovery
Machine learning techniques are used to analyze vast datasets, to predict the biological
activity of compounds, and to identify potential drugs for a disease by analyzing its
chemical structures.
Disease Diagnosis
Machine learning may also be used to identify some types of diseases. Breast cancer,
heart failure, Alzheimer's disease, and pneumonia are some examples of such diseases
that can be identified using machine learning algorithms.
These are just a few examples of the many applications of machine learning. As machine
learning continues to evolve and improve, we can expect to see it used in more areas of
our lives, improving efficiency, accuracy, and convenience in a variety of industries.
Tools overview for machine learning
Machine Learning (ML) has become a cornerstone in the software industry,
revolutionizing everything from predictive analytics to automation. With the growing
demand for intelligent systems, various tools have emerged to assist developers, data
scientists, and organizations build efficient machine-learning models.
TensorFlow
PyTorch
Scikit-learn
Keras
Apache Spark (MLlib)
[Link]
RapidMiner
Weka
Microsoft Azure Machine Learning
Google Cloud AI Platform
TensorFlow
TensorFlow, developed by Google, is one of the most popular open-source machine
learning frameworks. It provides comprehensive libraries for building and deploying deep
learning models, making it suitable for large-scale machine learning projects.
Key Features:
Supports both high-level and low-level APIs
Flexible architecture for deployment on CPUs, GPUs, and TPUs
TensorFlow Lite for mobile and IoT devices
TensorFlow Extended (TFX) for production ML pipelines
Use Cases:
Image recognition
natural language processing (NLP)
deep neural networks
PyTorch
PyTorch is another widely-used open-source machine learning library, particularly
favored in academic and research circles. Developed by Facebook's AI Research lab, it is
known for its flexibility and ease of use.
Key Features:
Dynamic computational graph (eager execution) for greater flexibility
Strong integration with Python
Extensive support for deep learning models
TorchScript for transitioning models from research to production
Use Cases:
Research in neural networks
Computer Vision
Reinforcement Learning
Scikit-learn
Scikit-learn is a powerful Python library that provides simple and efficient tools for data
mining, machine learning, and data analysis. It is particularly useful for beginners in
machine learning due to its user-friendly interface.
Key Features:
Simple API for a wide variety of algorithms
Extensive documentation and user community
Supports preprocessing, clustering, regression, and classification
Model evaluation metrics and cross-validation techniques
Use Cases:
Predictive analytics
Data Classification
Clustering
Keras
Keras is a high-level deep learning API written in Python, and it is tightly integrated with
TensorFlow. It is designed to be easy to use, modular, and extensible, allowing
developers to quickly prototype machine learning models.
Key Features:
User-friendly API with minimalistic design
Support for multiple backends (TensorFlow, Theano, CNTK)
Ability to run seamlessly on CPUs and GPUs
Built-in support for training and evaluating neural networks
Use Cases:
Neural networks for classification
Regression
Forecasting
Apache Spark (MLlib)
Apache Spark is an open-source distributed computing system that is widely used for big
data processing. Its machine learning library, MLlib, is designed for scalable and fault-
tolerant machine learning.
Key Features:
Distributed and parallelized processing of large datasets
Built-in algorithms for classification, clustering, and regression
Support for various data sources, including HDFS and cloud storage
Integration with Hadoop and Kubernetes
Use Cases:
Big data analytics
Large-scale machine learning
Distributed Computing
[Link]
[Link] is an open-source machine learning platform that offers both an enterprise and a
community version. It is known for its autoML capabilities, making it easier for non-
experts to build robust models.
Key Features:
Automated machine learning (H2O AutoML)
Supports gradient boosting machines, deep learning, and generalized linear models
Scalable for distributed processing
Easy integration with Spark, Python, and R
Use Cases:
Financial services
Healthcare
Marketing analytics
RapidMiner
RapidMiner is a robust data science platform that provides an integrated environment for
machine learning, data preparation, model validation, and deployment. Its drag-and-drop
interface makes it highly accessible to users without coding experience.
Key Features:
No-code and low-code environments for model creation
Extensive library of pre-built machine learning models
Strong capabilities for data preprocessing and visualization
Integration with Python, R, and deep learning frameworks
Use Cases:
Predictive maintenance
Customer analytics
Fraud detection
Weka
Weka, developed by the University of Waikato in New Zealand, is a collection of
machine learning algorithms for data mining tasks. It’s primarily used for educational and
research purposes but is also effective in production systems.
Key Features:
Wide range of algorithms for classification, regression, and clustering
Data preprocessing tools
GUI-based environment for ease of use
Java API for integration into software applications
Use Cases:
Academic research
Text mining
Educational machine learning
1300 240
1500 320
1700 330
1830 295
1550 256
2350 409
1450 319
In the above data, the target House Price is the dependent variable represented by X, and
the feature, Square Feet, is the independent variable represented by Y. The input features
(X) are used to predict the target label (Y). So, the independent variables are also known
as predictor variables, and the dependent variable is known as the response variable.
So lets define linear regression in machine learning as follows:
In machine learning, linear regression uses a linear equation to model the relationship
between a dependent variable (Y) and one or more independent variables (Y).
The main goal of the linear regression model is to find the best-fitting straight line (often
called a regression line) through a set of data points.
Line of Regression
A straight line that shows a relation between the dependent variable and independent
variables is known as the line of regression or regression line.
Line of Regression
In simple linear regression, a line of regression is a straight line that best fits the data
points and is used to show the relationship between a dependent variable and an
independent variable.
Graphical Representation
The following graph depicts the simple linear regression model −
In the above image, the straight line represents the simple linear regression line where
Ŷ is the predicted value, and Y is dependent variable (target) and X is independent
variable (input).
Simple Linear Regression Model
A simple linear regression model in machine learning can be represented as the following
mathematical equation −
Y=w0+w1X+ϵ
Where
Y is the dependent variable (target).
X is the independent variable (feature).
w0 is the y-intercept of the line.
w1 is the slope of the line, representing the effect of X on Y.
ε is the error term, capturing the variability in Y not explained by X.
1.1 39343
1.3 46205
1.5 37731
2 43525
2.2 39891
2.9 56642
3 60150
3.2 54445
3.2 64445
3.7 57189
3.9 63218
4 55794
4 56957
4.1 57081
4.5 61111
4.9 67938
5.1 66029
5.3 83088
5.9 81363
6 93940
6.8 91738
7.1 98273
7.9 101302
8.2 113812
8.7 109431
9 105582
9.5 116969
9.6 112635
10.3 122391
10.5 121872
Output
0 1.1 39343.0
1 1.3 46205.0
2 1.5 37731.0
3 2.0 43525.0
4 2.2 39891.0
Lets check if the dataset is linear or not
[Link](X, y, color="green")
[Link]("Salary vs Experience")
[Link]("Years of Experience")
[Link]("Salary (INR)")
[Link]()
Output
The above graph shows that the dependent and independent variables are linearly
dependent. So we can apply the simple linear regression on the dataset to find the best
relation between these variables.
Split the dataset into training and testing sets
The training set and test set will then be divided into two groups. We will use 80%
observations for the training set and 20% observations for the test set out of the total 30
observations we have. So there will be 24 observation in training set and 6 observation in
test set. We divide our dataset into training and test sets so that we can use one set to train
and the other to test our model.
# Split the dataset into training and testing sets
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2)
Here, X_train represents the input feature of the training data and y_train represents the
output variable (target variable).
Step 2: Model Training (Fitting the Simple Linear Regression to Training Set)
The next step is fitting our model with the training dataset. We will use scikit-learn's
LinearRegression class to train a simple linear regression model on the training data. The
code for this is as follows −
from sklearn.linear_model import LinearRegression
# Create a linear regression object
regressor= LinearRegression()
[Link](X_train, y_train)
The fit() method is used to fit the linear regression object (regressor) to the training data.
The model learns the relation between the predictor variable (X_train), and the target
variable (y_train).
Step 3: Model Testing
Once the model is trained, we can use it to make predictions on the test data. The code for
this is as follows −
y_pred = [Link](X_test)
df = [Link]({'Actual Values':y_test, 'Predicted Values':y_pred})
print(df)
Output
Actual Values Predicted Values
0 60150.0 54093.648425
1 93940.0 82416.119864
2 57081.0 64478.554619
3 116969.0 115459.003211
4 56957.0 63534.472238
5 121872.0 124899.827024
The above output shows actual values and predicted values of Salary in the test set.
Here, X_test represents the input feature of the test data and y_pred represents the
predicted output variable (target variable).
Similarly, you can test the model with training data.
y_pred = [Link](X_train)
df = [Link]({'Real Values':y_test, 'Predicted Values':y_pred})
print(df)
Output
Real Values Predicted Values
0 57189.0 60702.225094
1 64445.0 55981.813188
2 63218.0 62590.389857
3 122391.0 123011.662261
4 91738.0 89968.778915
5 43525.0 44652.824612
6 61111.0 68254.884145
7 56642.0 53149.566044
8 66029.0 73919.378433
9 83088.0 75807.543195
10 46205.0 38044.247943
11 109431.0 107906.344160
12 98273.0 92801.026059
13 37731.0 39932.412705
14 54445.0 55981.813188
15 39891.0 46540.989374
16 101302.0 100353.685109
17 55794.0 63534.472238
18 81363.0 81472.037483
19 39343.0 36156.083180
20 113812.0 103185.932253
21 67938.0 72031.213670
22 112635.0 116403.085592
23 105582.0 110738.591304
Step 4: Model Evaluation
We need to evaluate the performance of the model to determine its accuracy. We will use
the mean squared error (MSE), root mse (RMSE), mean average error (MAE), and the
coefficient of determination (R^2) as evaluation metrics. The code for this is as follows −
from [Link] import mean_squared_error
from [Link] import mean_absolute_error
from [Link] import r2_score
Homoscedasticity
For all observations, the variance of the residual errors is similar across the value of each
independent variable.
Normality of Errors
The residuals (errors) are normally distributed. The residuals are differences between the
actual and predicted values.
No Multicollinearity
The independent variables are not highly correlated with each other. Linear regression
models assume that there is very little or no multi-collinearity in the data.
No Autocorrelation
There is no correlation between residuals. This ensures that the residuals (errors) are
independent of each other.
Fixed Independent Variables
The values of independent variables are fixed in all repeated samples.
Violations of these assumptions can lead to biased or inefficient estimates. It is essential
to validate these assumptions to ensure model accuracy.
Implementing Multiple Linear Regression in Python
To implement multiple linear regression in Python using Scikit-Learn, we can use the
same Linear Regression class as in simple linear regression, but this time we need to
provide multiple independent variables as input.
Step 1: Data Preparation
We use the dataset named [Link] with 50 examples. It contains four predictor
(independent) variables and a target (dependent) variable. The following table represents
the data in [Link] file.
[Link]
R&D Marketing
Administration State Profit
Spend Spend
New
165349.2 136897.8 471784.1 192261.8
York
New
144372.4 118671.9 383199.6 182902
York
New
120542.5 148719 311613.3 152211.8
York
New
114523.6 122616.8 261776.2 129917
York
New
94657.16 145077.6 282574.3 125370.4
York
New
86419.7 153514.1 0 122776.9
York
New
78389.47 153773.4 299737.3 111313
York
73994.56 122782.8 303319.3 Florida 110352.3
New
77044.01 99281.34 140574.8 108552
York
New
72107.6 127864.6 353183.8 105008.3
York
New
65605.48 153032.1 107138.4 101004.6
York
New
61136.38 152701.9 88218.23 97483.56
York
New
46014.02 85047.44 205517.6 96479.51
York
New
20229.59 65947.93 185265.1 81229.06
York
38558.51 82982.09 174999.3 California 81005.76
New
15505.73 127382.3 35534.17 69758.98
York
New
1000.23 124153 1903.93 64926.08
York
New
542.05 51743.15 0 35673.41
York
You can create a CSV file and store the above data points in it.
We have our dataset as [Link] file. We will use it to understand the implementation of
the multiple linear regression in Python.
We need to import libraries before loading the dataset.
# import libraries
import numpy as np
import [Link] as plt
import pandas as pd
Load the dataset
We load our dataset as a Pandas Data frame named <string>dataset. Now let's create a list
of independent values (predictors) and put them in a variable called X.</string>
The independent values are 'R&D Spend', 'Administration', 'Marketing Spend'. We are not
using the independent variable 'State' for sake of simplicity.
We put the dependent variable values to a variable y.
# load dataset
dataset = pd.read_csv('[Link]')
X = dataset[['R&D Spend', 'Administration', 'Marketing Spend']]
y = dataset['Profit']
Let's check first five examples (rows) of input features (X) and target (y) −
[Link]()
Output
R&D Spend Administration Marketing Spend
0 165349.20 136897.80 471784.10
1 162597.70 151377.59 443898.53
2 153441.51 101145.55 407934.54
3 144372.41 118671.85 383199.62
4 142107.34 91391.77 366168.42
[Link]()
Output
Profit
192261.83
191792.06
191050.39
182901.99
166187.94
Split the dataset into training and test sets
Now, we split the dataset into a training set and a test set. Both the X(independent values)
and y (dependent values) are divided into two sets - training and test. We will use 20% for
the test set. In such a way out of 50 feature vectors (observations/ examples), there will be
40 feature vectors in training set and 10 feature vectors in test set.
# Split the dataset into training and test sets
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2)
Here X_train and X_test represent input features in training set and test set,
where y_train and y_test represent target values (output) in traning and test set.
Step 2: Model Training
The next step is to fit our model with training data. We will use linear_model class
from sklearn module. We use the Linear Regression() method of linear_model class to
create a linear regression object, here we name it as regressor.
# Fit Multiple Linear Regression to the Training set
from sklearn.linear_model import LinearRegression
regressor = LinearRegression()
[Link](X_train, y_train)
The regressor object has fit() method. The fit() method is used to fit the linear regression
object, regressor to the training data. The model learns the relation between the predictor
variable (X_train), and the target variable (y_train).
Step 3: Model Testing
Now our model is ready to use for prediction. Let's test our regressor model on test data.
We use predict() method to predict the results for the test set. It takes input features
(X_test) and return the redicted values.
y_pred = [Link](X_test)
df = [Link]({'Real Values':y_test, 'Predicted Values':y_pred})
print(df)
Output
Real Values Predicted Values
23 108733.99 110159.827849
43 69758.98 59787.885207
26 105733.54 110545.686823
34 96712.80 88204.710014
24 108552.04 114094.816702
39 81005.76 84152.640761
44 65200.33 63862.256006
18 124266.90 129379.514419
47 42559.73 45832.902722
17 125370.37 130086.829016
You can compare the actual values and predicted values.
Step 4: Model Evaluation
We now evaluate our model to check how accurate it is. We will use mean square error
(MSE), root mean square error (RMSE), mean absolute error (MAE), and R2-score
(Coefficient of determination).
from [Link] import mean_squared_error, root_mean_squared_error,
mean_absolute_error, r2_score
# Assuming you have your true y values (y_test) and predicted y values (y_pred)
mse = mean_squared_error(y_test, y_pred)
rmse = root_mean_squared_error(y_test, y_pred)
mae = mean_absolute_error(y_test, y_pred)
r2 = r2_score(y_test, y_pred)
print("Mean Squared Error (MSE):", mse)
print("Root Mean Squared Error (RMSE):", rmse)
print("Mean Absolute Error (MAE):", mae)
print("R-squared (R2):", r2)
Output
Mean Squared Error (MSE): 72684687.6336162
Root Mean Squared Error (RMSE): 8525.531516193943
Mean Absolute Error (MAE): 6425.118502810154
R-squared (R2): 0.9588459519573707
You can examine the above metrics. Our model shows an R-squared score of around
0.96, which means that 96% of data points are scattered around the fitted regression line.
Another interpretation is that 96% of the variation in the output variables is explained by
the input variables.
Step 5: Model Prediction for New Data
Let's use our regressor model to predict profit values based on R&D Spend,
Administration and Marketing Spend.
['R&D Spend','Administration','Marketing Spend']=[166343.2, 136787.8, 461724.1]
// predict profit when R&D Spend is 166343.2, Administration is 136787.8 and
Marketing Spend is 461724.1
new_data =[[166343.2, 136787.8, 461724.1]]
profit = [Link](new_data)
print(profit)
Output
[193053.61874652]
The model predicts the profit value is approximately 192090.567 for the above three
values.
Model Parameters (Coefficients and Intercept)
The model parameters (intercept and coefficients) describe the relation between a
dependent variable and the independent variables.
Our regression model for the above use case,
Y=w0+w1X1+w2X2+w2X2
w0 is intercept and w1,w2,w3 are coefficients of X1,X2,X3 respectively.
Here,
X1 represents R&D Spend,
X2 represents Administration, and
X3 represents Marketing Spend.
Let's first compute the intercept and coefficients.
print("coefficients: ", regressor.coef_)
print("intercept: ", regressor.intercept_)
Output
coefficients: [ 0.81129358 -0.06184074 0.02515044]
intercept: 54946.94052163202
The above output shows the following -
w0 = 54946.94052163202
w1 = 0.81129358
w2 = -0.06184074
w3 = 0.02515044
Result Explanation
We have calculated intercept (w0) and coefficients (w1, w2, w3).
The coefficients are as follows -
R&D Spend: 0.81129358
Administration: -0.06184074
Marketing Spend: 0.02515044
This shows that if R&D Spend is increased by 1 USD, the Profit will increase by
0.81851334 USD.
The result shows that when Administration spend is increased by 1 USD, the Profit will
decrease by 0.03124763 USD.
And when Marketing Spend increases by 1 USD, the Profit increases by 0.02042286
USD.
Let's verify the result,
In step 5, we have predicted Profit for new data as 193053.61874652
Here,
new_data =[[166343.2, 136787.8, 461724.1]]
Profit = 54946.94052163202+ 0.81129358*166343.2 - 0.06184074* 136787.8 +
0.02515044 * 461724.1
Profit = 193053.616257
Which is approximately the same as model prediction. Why approximately? Because of
residual error.
residual error = 193053.61874652 - 193053.616257
residual error = 0.00248952
Applications of Multiple Linear Regression
The following are some commonly used applications of multiple linear regression −
Application Description
Challenge Description
The model fits the training data too closely, leading to poor
Overfitting
performance on new, unseen data.
Missing Data Missing data can lead to biased and inaccurate results.
Simple Linear
Feature Multiple Linear Regression
Regression
Independent
One Two or more
Variables
Model
y = w1x + w0 y=w0+w1x1+w2x2+ ... +wpxp
Equation
Complexity Less complex More complex due to multiple variables
Model
Easier to interpret More complex to interpret due to
Interpretatio
coefficients multiple variables
n
-4.662262677 41.84298632
-4.316559447 34.66111954
-4.213984765 39.38300088
-3.949661089 37.53984488
-3.578553716 32.28453119
-3.455711698 30.00113848
-3.108440121 22.63540128
-3.081303324 25.36502221
-2.672460827 19.22697005
-2.652286793 20.27967918
-2.651498033 13.2758285
-2.288263998 18.12399121
-2.11186969 11.21829447
-1.818937609 10.01286785
-1.66034773 12.61518115
-1.326378983 10.95773134
-1.173123268 6.68912264
-0.773330043 9.392968661
-0.673752802 5.210162615
-0.149634867 4.673642541
-0.036156498 0.328625517
-0.033895286 0.897603187
0.008607699 3.165600008
0.149244574 1.931416029
0.688780908 2.576782245
0.693598873 4.625689458
0.874905029 0.789973651
1.024180814 2.313806358
1.240711619 1.292360811
1.359812674 0.953115312
1.740000012 3.782570136
1.850551926 4.857987801
1.999310369 8.943823209
2.075100597 8.170734936
2.31859124 7.412094028
2.471945997 10.33663062
2.784836463 15.99661997
2.831760211 12.56823739
2.959932091 21.34291574
3.020874314 20.11441346
3.211366144 22.8394055
3.270044068 16.98327874
3.316072519 25.14208223
3.335932412 26.10474041
3.610778478 28.91218793
3.704057438 17.84395652
4.130867961 34.53074274
4.133533788 27.69838335
4.899031514 41.51482194
Note − Create a CSV file with the above data and save it as ice_cream_selling_data.csv.
Import Python libraries and packages for data preparation
Let's first import libraries and packages required in the data preparation step. We use
Python pandas for reading CSV files. We use NumPy to convert the pandas data frame to
NumPy array. Input and output features are NumPy arrays. We
use preprocessing package from the Scikit-learn library for preprocessing related tasks
such as transforming input feature to polynomial features.
import numpy as np
import pandas as pd
import [Link] as plt
from [Link] import PolynomialFeatures
Load the dataset
Load the ice_cream_selling_data.csv as a pandas dataframe. Learn more about data
loading here.
data = pd.read_csv('/ice_cream_selling_data.csv')
[Link]()
Output
Temperature (C) Ice Cream Sales (units)
0 -4.662263 41.842986
1 -4.316559 34.661120
2 -4.213985 39.383001
3 -3.949661 37.539845
4 -3.578554 32.284531
Let's create independent variable (X) and the dependent variable (y).
X = [Link][:, 0].[Link](-1, 1)
y = [Link][:, 1].values
Visualize the original datapoints
Let's visualize the original data points to get some insight.
# Visualize the original data points
[Link](X, y, color="green")
[Link]("Original Data")
[Link]("Temperature (C)")
[Link]("Ice Cream Sales (units)")
[Link]()
Output
The above graph shows a parabolic curve (polynomial with degree 2) that will fit the
datapoints.
So the relationship between the dependent variable ("Ice Cream Sales (units)") and
independent variable ("Temperature (C)") can be modeled using polynomial regression
of degree 2.
Create a polynomial features object
Now, let's create a polynomial feature object with degree 2. We will
use PolynomialFeatures class from [Link] module to create the feature
object.
degree = 2 # Degree of the polynomial
poly_features = PolynomialFeatures(degree=degree)
Let's now transform the input data to include polynomial features
X_poly = poly_features.fit_transform(X)
Here X_poly is transformed polynomial features of original input features (X). The
transformed data is of (49, 3) shape.
Step 2: Model Training
We have created polynomial features. Now, let's build out the model. We
use LinearRegression class from sklearn.linear_model module. As we already discussed,
Polynomial regression is a special type of linear regression.
Let's create a linear regression object lr_model and train (fit) the model with data.
from sklearn.linear_model import LinearRegression
lr_model = LinearRegression()
#Now, fit the model (linear regression object) on the data
lr_model.fit(X_poly, y)
So far, we have trained our regression model lr_model
Step 3: Model Prediction and Testing
Now, we can use our model to predict the output. Before going to predict for new data,
let's predict for the existing data.
# Generate predictions
y_pred = lr_model.predict(X_poly)
df = [Link]({'Actual Values':y, 'Predicted Values':y_pred})
print(df)
Output
Actual Values Predicted Values
0 41.842986 46.564507
1 34.661120 40.600548
2 39.383001 38.915089
3 37.539845 34.749272
4 32.284531 29.331940
5 30.001138 27.649735
6 22.635401 23.192862
7 25.365022 22.863178
8 19.226970 18.222266
9 20.279679 18.009098
10 13.275828 18.000794
11 18.123991 14.418541
12 11.218294 12.853070
13 10.012868 10.504868
14 12.615181 9.364587
15 10.957731 7.264266
16 6.689123 6.437055
17 9.392969 4.683654
18 5.210163 4.337906
19 4.673643 3.116139
20 0.328626 2.983983
21 0.897603 2.981829
22 3.165600 2.944811
23 1.931416 2.869446
24 2.576782 3.251711
25 4.625689 3.259923
26 0.789974 3.630683
27 2.313806 4.026226
28 1.292361 4.744891
29 0.953115 5.213321
30 3.782570 7.055902
31 4.857988 7.690948
32 8.943823 8.616039
33 8.170735 9.118494
34 7.412094 10.874961
35 10.336631 12.092557
36 15.996620 14.843721
37 12.568237 15.287199
38 21.342916 16.539614
39 20.114413 17.156188
40 22.839406 19.171090
41 16.983279 19.818497
42 25.142082 20.335157
43 26.104740 20.560474
44 28.912188 23.826884
45 17.843957 24.998282
46 34.530743 30.764287
47 27.698383 30.802396
48 41.514822 42.821195
You can compare the predicted values with actual values.
Step 4: Evaluating Model Performance
To evaluate the model performance, the best metric is the R-squared score (Coefficient of
determination). It measures the proportion of the variance in the dependent variable that is
predictable from the independent variables.
from [Link] import r2_score
# get the predicted values for test dat
y_pred = lr_model.predict(X_poly)
r2 = r2_score(y, y_pred)
print(r2)
Output
0.9321137090423877
The r2_score is the most common metric used to evaluate a regression model. The high
score indicates a better fit of the model with data. 1 represent perfect fit and 0 represents
no relation between the predicted values and actual values.
Result Explanation − You can examine the above metrics. Our model shows an R-
squared score of around 0.932, which means that approximately 93% of data points are
scattered around the fitted regression curve. Another interpretation is that 93% of the
variation in the output variables is explained by the input variables.
Step 5: Visualize the polynomial regression results
Let's visualize the regression results for better understanding. We use the pyplot module
from the Matplotlib library to plot the graph.
import [Link] as plt
# Visualize the polynomial regression results
[Link](X, y, color="green")
[Link](X, y_pred, color='red', label=f'Polynomial Regression (degree={degree})')
[Link]("Temperature (C)")
[Link]("Ice Cream Sales (units)")
[Link]()
[Link]('Polynomial Regression')
[Link]()
Output
The above graph shows that the polynomial regression with degree 2 fits well with the
original data. The polynomial curve (parabola), in red color, represents the best-fit
regression curve. This regression curve is used to predict the value. The graph also shows
that the predicted values are close to the actual values.
Step 5: Model Prediction for New Data
Up to now, we have predicted the values in the dataset. Let's use our regression model to
predict new, unseen data.
Let's take the Temperature (C) as 1.9929C and predict the units of Ice Cream Sales.
# Predict a new value
X_new = [Link]([[1.9929]]) # Example value to predict
X_new_poly = poly_features.transform(X_new)
y_new_pred = lr_model.predict(X_new_poly)
print(y_new_pred)
Output
[8.57450466]
The above result shows that the predicted value of Ice cream sales is 8.57450466.
Ridge Regression
Overfitting occurs when a model becomes too complex and fits the noise in the training
data, leading to poor generalization on new data. Ridge regression combats overfitting
by adding a penalty term (L2 regularization) to the ordinary least squares (OLS)
objective function.
Imagine your model is overreacting to tiny details in the data (like memorizing noise).
Ridge regression "calms it down" by shrinking the model's weights (coefficients) toward
zero. Think of it like adjusting a volume knob to get the perfect sound level—not too
loud (overfitting), not too quiet (underfitting).
This penalty discourages the model from using large values for the coefficients (the
numbers multiplying the features). It forces the model to keep these coefficients
small. By making the coefficients smaller and closer to zero, ridge regression simplifies
the model and reduces its sensitivity to random fluctuations or noise in the data. This
makes the model less likely to overfit and helps it perform better on new, unseen data,
improving its overall accuracy and reliability.
For Example - We are predicting house prices based on multiple features such as
square footage, number of bedrooms, and age of the house:
Price=1000 Size−500⋅Age+Noise
Price=800⋅Size−300⋅Age+Less Noise
As lambda increases the model places more emphasis on shrinking the coefficients of
highly correlated features, making their impact smaller and more stable. This reduces
the effect of multicollinearity by preventing large fluctuations in coefficient estimates
due to correlated predictors.
Ridge regression allows control over the bias-variance trade-off. Increasing the value of
λ increases the bias but reduces the variance, while decreasing λ does the opposite. The
goal is to find an optimal λ that balances bias and variance, leading to a model that
generalizes well to new data.
Bias: Measures the error introduced by approximating a real-world problem, which may
be complex, by a simplified model. In ridge regression, as the regularization parameter
k increases, the model becomes simpler, which increases bias but reduces variance.
Variance: Measures how much the ridge regression model's predictions would vary if
we used different training data. As the regularization parameter k decreases, the model
becomes more complex, fitting the training data more closely, which reduces bias but
increases variance.
Irreducible Error: Represents the noise in the data that cannot be reduced by any
model.
As k increases, the bias increases, but the variance decreases. The optimal value
of k balances this tradeoff, minimizing the MSE.
Selection of the Ridge Parameter in Ridge Regression
Choosing an appropriate value for the ridge parameter k is crucial in ridge regression, as
it directly influences the bias-variance tradeoff and the overall performance of the
model. Several methods have been proposed for selecting the optimal ridge parameter,
each with its own advantages and limitations. Methods for Selecting the Ridge
Parameter are:
Cross-Validation
Cross-validation is a common method for selecting the ridge parameter by dividing data
into subsets. The model trains on some subsets and validates on others, repeating this
process and averaging the results to find the optimal value of k.
K-Fold Cross-Validation: The data is split into K subsets, training on K-1 folds and
validating on the remaining fold. This is repeated K times, with each fold serving as the
validation set once.
Leave-One-Out Cross-Validation (LOOCV) A special case of K-fold where K equals
the number of observations, training on all but one observation and validating on the
remaining one. It’s computationally intensive but unbiased.
Generalized Cross-Validation (GCV)
Stability selection improves ridge parameter robustness by subsampling data and fitting
the model multiple times. The most frequently selected parameter across all subsamples
is chosen as the final estimate.
Practical Considerations for Selecting Ridge Parameter
Tradeoff Between Bias and Variance: The choice of the ridge parameter k involves a
tradeoff between bias and variance. A larger k introduces more bias but reduces
variance, while a smaller k reduces bias but increases variance. The optimal k balances
this tradeoff to minimize the mean squared error (MSE) of the model.
Computational Efficiency: Some methods for selecting k, such as cross-validation and
empirical Bayes methods, can be computationally intensive, especially for large
datasets. Generalized cross-validation and analytical methods offer more
computationally efficient alternatives.
Interpretability: The interpretability of the selected ridge parameter is also an
important consideration. Methods that provide explicit criteria or formulas for
selecting k can offer more insight into the relationship between the data and the model.
Read about Implementation of Ridge Regression from Scratch using Python.
Applications of Ridge Regression
Forecasting Economic Indicators: Ridge regression helps predict economic factors
like GDP, inflation, and unemployment by managing multicollinearity between
predictors like interest rates and consumer spending, leading to more accurate forecasts.
Medical Diagnosis: In healthcare, it aids in building diagnostic models by controlling
multicollinearity among biomarkers, improving disease diagnosis and prognosis.
Sales Prediction: In marketing, ridge regression forecasts sales based on factors like
advertisement costs and promotions, handling correlations between these variables for
better sales planning.
Climate Modeling: Ridge regression improves climate models by eliminating
interference between variables like temperature and precipitation, ensuring more
accurate predictions.
Risk Management: In credit scoring and financial risk analysis, ridge regression
evaluates creditworthiness by addressing multicollinearity among financial ratios,
enhancing accuracy in risk management.
Advantages and Disadvantages of Ridge Regression
Advantages:
Bias Introduction: The introduction of bias can lead to underestimation of the true
effects of the predictors.
Parameter Selection: Choosing the optimal ridge parameter k can be challenging and
computationally intensive.
Not Suitable for Variable Selection: Ridge regression does not perform variable
selection, meaning all predictors remain in the model, even those with negligible
effects.
Lasso Regression in Machine learning
What is Lasso Regression?
Lasso Regression is a regression method based on Least Absolute
Shrinkage and Selection Operator and is used in regression analysis for variable
selection and regularization. It helps remove irrelevant data features and prevents
overfitting. This allows features with weak influence to be clearly identified as the
coefficients of less important variables are shrunk toward zero.
In this guide, we will understand the core concepts of lasso regression as well as how it
works to mitigate overfitting.
Table of Content
Understanding Lasso Regression
Bias-Variance Tradeoff in Lasso Regression
When to use Lasso Regression
Advantages of Lasso Regression
Disadvantages
One of the main disadvantages of MAE is that it is not differentiable at zero. Many
optimization algorithms tend to use differentiation to find the optimum value for
parameters in the evaluation metric.
It can be challenging to compute gradients in MAE.
Mean Bias Error (MBE)
In “Mean Bias Error,” bias reflects the tendency of a measurement process to
overestimate or underestimate a parameter. It has a single direction, positive or negative.
Positive bias implies an overestimated error, while negative bias implies an
underestimated error. Mean Bias Error (MBE) calculates the mean difference between
predicted and actual values, quantifying overall bias without considering absolute values.
Similar to MAE, MBE differs in not taking the absolute value. Caution is needed with
MBE, as positive and negative errors can cancel each other out.
Relative root mean square error Absolute Error is calculated by dividing the total
absolute error by the absolute difference between the mean and the actual value.
The formula for RAE is:
𝛾 represents the required quantile. The quantiles values are selected based on how we
want to weigh the positive and the negative errors.
In the loss function above, 𝛾 has a value between 0 and 1. When there is an
underestimation, the first part of the formula will dominate and for overestimation, the
second part will dominate. The chosen value of quantile(𝛾) gives different penalties for
over-prediction and under prediction. When 𝛾 = 0.5, underestimation and overestimation
are penalized by the same factor and the median is obtained. When the value of 𝛾 is
larger, overestimation is penalized more than underestimation. For example, when 𝛾 =
0.75 the model will penalize overestimation and it will cost three times as much as
underestimation. Optimization algorithms based on gradient descent learn from the
quantiles instead of the mean.
Model Evaluation
Once we have identified the right models, we must rank each one according to how well
it does the job. The most common method is to split the dataset into two parts.
Training Set: The data used to train a machine learning model by learning patterns and
relationships.
Testing Set: This checks how well a model performs over new, unseen data.
We use k-fold cross-validation to further improve the evaluation. In k-fold cross-
validation, the data is split into k subsets. The model is trained on k-1 subsets and tested
on the remaining one, repeating the process k times. This way, our evaluation is not
biased by a particular train-test split.
Different machine learning problems require different evaluation metrics.
For Regression Problems: We make use of Mean Squared Error (MSE), Mean Absolute
Error (MAE) and R-squared.
For Classification Problems: We make use of Accuracy, Precision, Recall and F1-score.
After evaluating the models, we compare them to identify the one that satisfies
performance and computational efficiency.
Model Selection Techniques in Machine Learning
Grid Search
One of the simplest and most commonly used model selection techniques is grid search.
In this approach, systematically different combinations of hyperparameters are tried and
that gives the best performance chosen. It can be effective, but the main drawback will be
computationally intensive, especially for complex models and many parameters.
Random Search
Similar to grid search, random search doesn't check all possible combinations. Instead, it
randomly chooses a subset of the hyperparameter combinations. The random search
method often runs much faster than the grid search method and yet achieves equally good
results.
Bayesian Optimization
Bayesian optimization is a smarter approach to model selection. Instead of just randomly
searching for the best hyperparameters, it uses probability models to predict which
parameters are likely to perform best and focuses on evaluating those. This method is
efficient and often finds better results than grid or random search.
Cross-Validation Based Selection
This method involves using cross-validation to evaluate multiple models and selecting the
one with the best average performance. Instead of relying on a single train-test
split, cross-validation divides the dataset into multiple parts and trains the model on
different subsets. This helps to ensure that the model’s performance is not just due to a
specific split of data. By averaging the results from different splits, we get how well the
model will perform on new, unseen data. This approach reduces the risk of overfitting and
helps in selecting a good model.
Bagging
What is Bagging?
Bagging is a machine learning ensemble method aimed at improving the reliability
and accuracy of predictive models. It involves generating several subsets of the training
data using random sampling with replacement. These subsets are then used to train
multiple base models, such as decision trees or neural networks.
When making predictions, the outputs from these base models are combined, often
through averaging (for regression) or voting (for classification), to produce the final
prediction. Bagging reduces overfitting by creating diversity among the models and
enhances overall performance by lowering variance and increasing robustness.
Implementation Steps of Bagging
Here’s a general outline of implementing Bagging:
Dataset Preparation: Clean and preprocess your dataset. Split it into training and test
sets.
Bootstrap Sampling: Randomly sample from the training data with replacement to create
multiple bootstrap samples. Each sample typically has the same size as the original
dataset.
Model Training: Train a base model (e.g., decision tree, neural network) on each
bootstrap sample. Each model is trained independently.
Prediction Generation: Use each trained model to predict the test data.
Combining Predictions: Aggregate the predictions from all models using methods like
majority voting for classification or averaging for regression.
Evaluation: Assess the ensemble’s performance on the test data using metrics like
accuracy, F1 score, or mean squared error.
Hyperparameter Tuning: Adjust the hyperparameters of the base models or the
ensemble as needed, using techniques like cross-validation.
Deployment: Once satisfied with the ensemble’s performance, deploy it to make
predictions on new data.
Understanding Ensemble Learning
To increase performance overall, ensemble learning integrates the predictions of several
models. By combining the insights from multiple models, this method frequently
produces forecasts that are more accurate than those of any one model alone.
Popular ensemble methods include:
Bagging: Involves training multiple base models on different subsets of the training data
created through random sampling with replacement.
Boosting: A sequential method where each model focuses on correcting the errors of its
predecessors, with popular algorithms like AdaBoost and XGBoost.
Random Forest: An ensemble of decision trees, each trained on a random subset of
features and data, with final predictions made by aggregating individual tree predictions.
Stacking: Combines the predictions of multiple base models using a meta-learner to
produce the final prediction.
Benefits of Bagging
Variance Reduction: By training multiple models on different data subsets, Bagging
reduces variance, leading to more stable and reliable predictions.
Overfitting Mitigation: The diversity among base models helps the ensemble generalize
better to new data.
Robustness to Outliers: Aggregating multiple models’ predictions reduces the impact
of outliers and noisy data points.
Parallel Training: Training individual models can be parallelized, speeding up the
process, especially with large datasets or complex models.
Versatility: Bagging can be applied to various base learners, making it a flexible
technique.
Simplicity: The concept of random sampling with replacement and combining
predictions is easy to understand and implement.
Applications of Bagging
Bagging, also known as Bootstrap Aggregating, is a versatile technique used across many
areas of machine learning. Here’s a look at how it helps in various tasks:
Classification: Bagging combines predictions from multiple classifiers trained on
different data splits, making the overall results more accurate and reliable.
Regression: In regression problems, bagging helps by averaging the outputs of multiple
regressors, leading to smoother and more accurate predictions.
Anomaly Detection: By training multiple models on different data subsets, bagging
improves how well anomalies are spotted, making it more resistant to noise and outliers.
Feature Selection: Bagging can help identify the most important features by training
models on different feature subsets. This reduces overfitting and improves model
performance.
Imbalanced Data: In classification problems with uneven class distributions, bagging
helps balance the classes within each data subset. This leads to better predictions for less
frequent classes.
Building Powerful Ensembles: Bagging is a core part of complex ensemble methods like
Random Forests and Stacking. It trains diverse models on different data subsets to
achieve better overall performance.
Time-Series Forecasting: Bagging improves the accuracy and stability of time-series
forecasts by training on various historical data splits, capturing a wider range of patterns
and trends.
Clustering: Bagging helps find more reliable clusters, especially in noisy or high-
dimensional data. This is achieved by training multiple models on different data subsets
and identifying consistent clusters across them.
Differences Between Bagging and Boosting
Conclusion
Elevate your machine learning skills with our ‘Mastering Bagging Techniques ‘
course! Learn how to leverage this powerful ensemble method to boost model
performance, reduce overfitting, and tackle real-world challenges with
confidence—enroll today and unlock your full potential!
Ensemble Methods in Machine learning
Ensemble methods combine multiple machine learning models to improve overall
accuracy and reliability. They work by aggregating the predictions of "weak learners" to
create a single, more powerful "strong learner" that is less prone to individual model
errors. The three main types are bagging, boosting, and stacking, which differ in how they
combine models.
In machine learning, a model is trained to make predictions or classify data based on
patterns in a dataset. However, a single model can sometimes have limitations, such as
overfitting, where the model performs well on training data but poorly on new data.
Ensemble methods offer a solution by combining multiple models to improve accuracy
and reduce errors. By using the strengths of different models together, ensemble methods
create a more reliable and robust prediction system than any single model on its own.
What are Ensemble Methods?
Ensemble methods are techniques in machine learning that combine the predictions of
multiple models to improve overall accuracy. The idea is simple: rather than relying on a
single model, ensemble methods leverage the strengths of several models to create a more
powerful prediction system.
By combining different models, ensemble methods address some of the limitations of
individual models. For example, if one model has a tendency to overfit or underperform
on certain data points, the ensemble can balance out these weaknesses and make more
accurate predictions. In essence, ensemble methods help create a “team” of models,
working together for better results.
Why Use Ensemble Learning?
Ensemble learning offers several benefits that make it popular in machine learning:
Improved Accuracy and Generalization – By combining multiple models, ensemble
methods often achieve higher accuracy than individual models, making predictions more
reliable.
Reduced Variance and Overfitting – Ensembles help reduce overfitting by balancing
out the weaknesses of individual models. This makes ensemble models perform better on
new, unseen data.
Robustness to Noise in Data – Ensemble methods are more resilient to noisy or complex
data. With multiple models contributing to the final prediction, they can better handle
variations and inconsistencies in the data.
Types of Ensemble Models
Ensemble models combine the predictions of multiple individual models to improve
accuracy and stability. Here’s a breakdown of popular ensemble methods, each offering
unique ways to enhance model performance:
Bagging (Bootstrap Aggregation)
Concept: Bagging creates multiple versions of the original dataset by randomly sampling
data with replacement. Each subset is used to train a different model, which reduces
variance and enhances stability.
How It Works: Multiple models (usually decision trees) are trained independently on
different subsets of the data. The predictions are then averaged (for regression) or voted
on (for classification) to make the final decision.
Boosting
Concept: Boosting aims to build a strong model by training models sequentially. Each
new model focuses on correcting the errors of the previous ones, progressively reducing
bias.
How It Works: Models are trained one after another, with each new model adjusting to
the errors of its predecessors. By focusing on misclassified data points, boosting creates a
robust model.
Popular Examples:
AdaBoost: Adjusts weights for misclassified points, emphasizing harder-to-
classify examples.
Gradient Boosting: Uses gradient descent to minimize error, popular for complex
tasks.
Implementation: In Python, use AdaBoostClassifier, GradientBoostingClassifier,
or libraries like XGBoost and LightGBM for optimized boosting algorithms.
Stacking
Concept: Stacking combines multiple models by using a meta-model (or “super learner”)
to integrate their outputs. This meta-model learns from each individual model’s
predictions to make a final, optimized prediction.
How It Works: The base models generate predictions on the training data, and the meta-
model then learns from these predictions to make a final decision. Stacking leverages the
strengths of diverse models to increase accuracy.
Popular Example: Combining decision trees, logistic regression, and support vector
machines with a meta-model (such as linear regression) to produce the final result.
Implementation: Use StackingClassifier or StackingRegressor from scikit-learn to stack
models effectively.
Voting
Concept: Voting aggregates predictions from multiple models, making a final decision
based on a majority or weighted vote.
How It Works: In hard voting, the final class is determined by majority vote, while soft
voting takes the average probabilities of each class. This method is commonly used in
classification tasks where predictions from models like logistic regression, k-nearest
neighbors, and decision trees are combined.
Popular Example: Hard voting for discrete class predictions or soft voting for
probability-based outcomes.
Implementation: Use the VotingClassifier in scikit-learn, which supports both hard and
soft voting.
Weighted Ensemble
Concept: Weighted ensembles assign varying importance to models based on their
accuracy or reliability, giving more influence to models that perform better.
How It Works: Each model is assigned a weight proportional to its accuracy. The final
prediction is then a weighted combination, with higher-performing models contributing
more to the outcome.
Popular Example: Custom ensembles where models with greater accuracy receive
higher weights to boost overall performance.
Implementation: Weighted ensembles can be created using custom code or by specifying
weights in scikit-learn’s VotingClassifier.
Main Challenge for Developing Ensemble Models?
While ensemble methods are powerful, they come with their own set of challenges that
can impact model development and usability:
Increased Computational Cost – Ensemble models often require multiple individual
models, which can significantly increase computation time and resources. Training and
deploying these models can be more resource-intensive compared to single models,
especially for large datasets.
Interpretability – Ensemble models, particularly complex ones like Random Forests or
stacked models, can be difficult to interpret. Unlike simpler models, it’s challenging to
understand how each individual model contributes to the final decision, which can make
the ensemble harder to explain to stakeholders.
Complexity in Implementation – Implementing ensemble models can be technically
challenging, especially when combining different types of models. Ensuring that each
model works together efficiently requires careful design and tuning, which may be
difficult for beginners or small teams.
Risk of Overfitting with Complex Ensembles – Although ensembles are designed to
reduce overfitting, overly complex ensembles can still overfit if not properly tuned. When
too many models are combined without careful evaluation, there’s a risk of creating a
model that performs well on training data but poorly on new data.
Conclusion
Ensemble methods combine multiple models to improve accuracy and robustness, making
them effective in complex machine learning tasks. Techniques like bagging, boosting, and
stacking help address limitations of single models, enhancing performance.
While ensembles come with challenges like higher computational costs and reduced
interpretability, these can be managed with careful tuning. Ensemble methods will
continue to play a vital role in advancing machine learning, enabling reliable and high-
performance models across various fields.
Unit III - Supervised Learning – II: Classification – Logistic Regression – Decision Tree
Regression and Classification – Random Forest Regression and Classification – Support
Vector Machine Regression and Classification - Evaluating Classification Models.
Decision Tree
The Decision Tree algorithm is a hierarchical tree-based algorithm that is used to classify
or predict outcomes based on a set of rules. It works by splitting the data into subsets
based on the values of the input features. The algorithm recursively splits the data until it
reaches a point where the data in each subset belongs to the same class or has the same
value for the target variable. The resulting tree is a set of decision rules that can be used
to make predictions or classify new data.
Nave Bayes
The Nave Bayes algorithm is a classification algorithm based on Bayes' theorem. The
algorithm assumes that the features are independent of each other, which is why it is
called "naive." It calculates the probability of a sample belonging to a particular class
based on the probabilities of its features. For example, a phone may be considered as
smart if it has touch-screen, internet facility, good camera, etc. Even if all these features
are dependent on each other, but all these features independently contribute to the
probability of that the phone is a smart phone.
Random Forest
Random Forest is a machine learning algorithm that uses an ensemble of decision trees to
make predictions. The algorithm was first introduced by Leo Breiman in 2001. The key
idea behind the algorithm is to create a large number of decision trees, each of which is
trained on a different subset of the data. The predictions of these individual trees are then
combined to produce a final prediction.
Applications of Classification in Machine Learning
Some of the most important applications of classification algorithms are as follows −
Speech Recognition
Handwriting Recognition
Biometric Identification
Document Classification
Image Classification
Spam Filtering
Fraud Detection
Facial Recognition
Building a Classication Model in Machine Learning
Let us now take a look at the steps involved in building a classification model −
Data Preparation
The first step is to collect and preprocess the data. This involves cleaning the data,
handling missing values, and converting categorical variables to numerical values.
Feature Extraction/Selection
The next step is to extract or select relevant features from the data. This is an important
step because the quality of the features can greatly impact the performance of the model.
Some common feature selection techniques include correlation analysis, feature
importance ranking, and principal component analysis.
Model Selection
Once the features are selected, the next step is to choose an appropriate classification
algorithm. There are many different algorithms to choose from, each with its own
strengths and weaknesses. Some popular algorithms include logistic regression, decision
trees, random forests, support vector machines, and neural networks
Model Training
After selecting a suitable algorithm, the next step is to train the model on the labeled
training data. During training, the model learns the mapping function between the input
features and the target variable. The model parameters are adjusted iteratively to
minimize the difference between the predicted outputs and the actual outputs.
Model Evaluation
Once the model is trained, the next step is to evaluate its performance on a separate set of
validation data. This is done to estimate the model's accuracy and generalization
performance. Common evaluation metrics include accuracy, precision, recall, F1-score,
and area under the receiver operating characteristic (ROC) curve.
Hyperparameter Tuning
In many cases, the performance of the model can be further improved by tuning its
hyperparameters. Hyperparameters are settings that are chosen before training the model
and control aspects such as the learning rate, regularization strength, and the number of
hidden layers in a neural network. Grid search, random search, and Bayesian optimization
are some common techniques used for hyperparameter tuning.
Model Deployment
Once the model has been trained and evaluated, the final step is to deploy it in a
production environment. This involves integrating the model into a larger system, testing
it on realworld data, and monitoring its performance over time.
Introduction to Logistic Regression
Logistic regression is a supervised learning classification algorithm used to predict the
probability of a target variable. The nature of target or dependent variable is dichotomous,
which means there would be only two possible classes.
In simple words, the dependent variable is binary in nature having data coded as either 1
(stands for success/yes) or 0 (stands for failure/no).
Mathematically, a logistic regression model predicts P(Y=1) as a function of X. It is one
of the simplest ML algorithms that can be used for various classification problems such as
spam detection, Diabetes prediction, cancer detection etc.
Next, we will define sigmoid function, loss function and gradient descend as follows −
class LogisticRegression:
def __init__(self, lr=0.01, num_iter=100000, fit_intercept=True, verbose=False):
[Link] = lr
self.num_iter = num_iter
self.fit_intercept = fit_intercept
[Link] = verbose
def __add_intercept(self, X):
intercept = [Link](([Link][0], 1))
return [Link]((intercept, X), axis=1)
def __sigmoid(self, z):
return 1 / (1 + [Link](-z))
def __loss(self, h, y):
return (-y * [Link](h) - (1 - y) * [Link](1 - h)).mean()
def fit(self, X, y):
if self.fit_intercept:
X = self.__add_intercept(X)
Now, initialize the weights as follows −
[Link] = [Link]([Link][1])
for i in range(self.num_iter):
z = [Link](X, [Link])
h = self.__sigmoid(z)
gradient = [Link](X.T, (h - y)) / [Link]
[Link] -= [Link] * gradient
z = [Link](X, [Link])
h = self.__sigmoid(z)
loss = self.__loss(h, y)
if([Link] ==True and i % 10000 == 0):
print(f'loss: {loss} \t')
With the help of the following script, we can predict the output probabilities −
def predict_prob(self, X):
if self.fit_intercept:
X = self.__add_intercept(X)
return self.__sigmoid([Link](X, [Link]))
def predict(self, X):
return self.predict_prob(X).round()
Next, we can evaluate the model and plot it as follows −
model = LogisticRegression(lr=0.1, num_iter=300000)
preds = [Link](X)
(preds == y).mean()
[Link](figsize=(10, 6))
[Link](X[y == 0][:, 0], X[y == 0][:, 1], color='g', label='0')
[Link](X[y == 1][:, 0], X[y == 1][:, 1], color='y', label='1')
[Link]()
x1_min, x1_max = X[:,0].min(), X[:,0].max(),
x2_min, x2_max = X[:,1].min(), X[:,1].max(),
xx1, xx2 = [Link]([Link](x1_min, x1_max), [Link](x2_min, x2_max))
grid = np.c_[[Link](), [Link]()]
probs = model.predict_prob(grid).reshape([Link])
[Link](xx1, xx2, probs, [0.5], linewidths=1, colors='red');
Output
Accuracy of Logistic Regression model is: 95.6884561891516
A Decision Tree is a supervised learning algorithm that makes decisions by splitting data
into branches based on feature conditions, forming a tree-like structure.
Works for both Classification (predicting categories) and Regression (predicting continuous
values)
Component Description
Root Node Top node — best splitting feature for entire dataset
Internal
A feature with a condition/split
Node
Branch /
Outcome of a condition (yes/no, ≤, >)
Edge
Goal
How It Works
At each node, split data to maximize class purity leaves should contain mostly one class.
Splitting Criteria
Gini Impurity
Gini(t) = 1 − Σ p(i|t)²
Information Gain:
IG(split) = Entropy(parent) − Σ (nᵢ/n) × Entropy(childᵢ)
Example:
After split:
Chi-Square (CHAID)
Traverse the tree from root → leaf based on feature values. Leaf node returns the majority
class of training samples in that leaf.
Goal
How It Works
Splits data to minimize variance/error in output values — leaves should have similar
target values.
Variance Reduction
Variance Reduction = Var(parent) − Σ (nᵢ/n) × Var(childᵢ)
Prediction in Regression
Traverse tree → reach leaf node. Leaf node returns the mean of all training target values
in that leaf.
Condition Description
Min samples per split Node won't split if fewer than n samples
A fully grown tree memorizes training data — performs poorly on unseen data.
Why It Happens
Solution: Pruning
Pruning Techniques
Set max_depth
Set min_samples_split
Set min_samples_leaf
Set min_impurity_decrease
Numerical Features
Categorical Features
Split
Algorithm Tree Type Splits Notes
Criterion
Information
ID3 Classification Multiway Only categorical features
Gain
Decision Boundary
Classification
Regression
Split measure
criterion gini / mse
(gini/entropy/mse)
Advantages
Disadvantages
Feature Importance
Evaluation Metrics
Classification Tree
Metric Formula
Precision TP / (TP+FP)
Recall TP / (TP+FN)
F1 Score 2 × (P×R)/(P+R)
Metric Formula
RMSE √MSE
R² 1 − SS_res/SS_tot
Penalizes extra
Adjusted R²
features
Random Forest is a supervised ensemble learning algorithm that builds multiple decision
trees and combines their outputs for a final prediction.
Proposed by Leo Breiman in 2001
"A forest of random decision trees is stronger than any single tree"
High variance – over fits easily Averaging multiple trees reduces variance
Core Concepts
Steps:
Why it works: Each tree sees a slightly different dataset → diversity → reduced variance
when combined.
Why it works: Prevents strong features from dominating every tree → decorrelates trees
→ better ensemble.
The ~36.8% samples NOT used in a bootstrap sample = OOB samples for that tree.
OOB error = average prediction error on OOB samples across all trees
Goal
Each tree casts one vote for a class → Majority Vote wins.
T₁ → Spam
T₂ → Not Spam
T₃ → Spam
T₄ → Spam
T₅ → Not Spam
Final → Spam (3 votes vs 2)
Probability Estimation
Goal
T₁ → ₹45L
T₂ → ₹48L
T₃ → ₹44L
T₄ → ₹47L
T₅ → ₹46L
Final → (45+48+44+47+46)/5 = ₹46L
Variance Reduction
Class label /
Tree output Numeric value
probabilities
Step 1 - Set Parameters Choose: number of trees (B), max features per split, max depth,
etc.
Step 4 - OOB Evaluation Use samples not in Dᵢ to estimate error of tree Tᵢ.
Regression → mean
Importance(f) = Σ over all trees Σ over all nodes using f (weighted impurity decrease)
Fast to compute
Biased toward high-cardinality features
Hyperparameters
Whether to use
bootstrap True
bootstrap
Parameter Description
Handle imbalanced
class_weight
classes
Effect of n_estimators
Single Deep
Random Forest
Tree
Low (averaging
Variance High
reduces it)
Key insight: Each tree has low bias (deep, complex) but high variance. Averaging B
uncorrelated trees reduces variance by factor of B without increasing bias.
Imbalanced Classes
Use class_weight='balanced'
High Dimensionality
Categorical Features
Proximity Matrix
Uses:
Clustering
Evaluation Metrics
Metric Description
Metric Description
R² Variance explained
Advantages
Disadvantages
Rotation Forest
Real-World Applications
Domain Application
What is SVM?
Support Vector Machine is a supervised learning algorithm used for both classification
and regression tasks.
Core idea: Find the optimal hyperplane that best separates or fits data
Core Intuition
Imagine two groups of points on a table. You can draw many lines separating them SVM
finds the line that is farthest from both groups simultaneously maximizing the safety
margin.
Key Terminology
Term Definition
Hyper-plane Decision boundary separating classes (line in 2D, plane in 3D, hyper-plane in nD)
Support Vectors Data points closest to the hyper-plane they define and support the margin
Hyper-plane Equation
w·x+b=0
b = bias
Margin Hyper-planes
Positive hyper-plane: w · x + b = +1
Negative hyper-plane: w · x + b = −1
Classification Rule
ŷ = sign(w · x + b)
ŷ = +1 → Class 1
ŷ = −1 → Class −1
SVM: Classification
Optimization Problem:
Real data is noisy and not perfectly separable. Soft margin introduces slack variables ξᵢ.
Optimization Problem:
C Parameter (Regularization)
C Value Effect
Dual Formulation
SVM optimization is often solved in dual form using Lagrange multipliers αᵢ:
Maximize: Σαᵢ − ½ Σᵢ Σⱼ αᵢαⱼ yᵢyⱼ (xᵢ · xⱼ) Subject to: 0 ≤ αᵢ ≤ C and Σαᵢyᵢ = 0
Key insight: Only support vectors have αᵢ > 0 — rest are zero. This leads directly to the
Kernel Trick.
Instead of computing φ(x) explicitly, use a kernel function that computes the dot product
in the transformed space directly.
2D non-separable data
↓ Kernel φ(x)
3D linearly separable data
↓ Find hyperplane
Project back to 2D → non-linear boundary
Kernel Functions
Linear Kernel
K(xᵢ, xⱼ) = xᵢ · xⱼ
Polynomial Kernel
Sigmoid Kernel
Laplacian Kernel
Robust to outliers
Custom Kernels
Kernel Comparison
Decision
Kernel Parameters When to Use
Boundary
Linearly separable,
Linear Linear C
high-dim
Polynomia
Curved C, d, γ, r Interactions matter
l
General purpose
RBF Smooth non-linear C, γ
default
Neural-net-like
Sigmoid S-shaped C, γ, r
problems
Instead of finding a hyper-plane that separates classes, SVR finds a hyper-plane that best
fits the data within a tube of width ε.
ε-Insensitive Tube
ε-tube
───────────────── f(x) + ε (upper boundary)
─ ─ ─ ─ ─ ─ ─ ─ f(x) (regression line)
───────────────── f(x) − ε (lower boundary)
Points INSIDE tube → zero loss
Points OUTSIDE tube → penalized
SVR Parameters
Parameter Effect
Key Parameter C C, ε
L = max(0, |y − f(x)| − ε)
Multiclass SVM
One-vs-Rest (OvR)
One-vs-One (OvO)
Decision Function
Classification
f(x) = w · x + b = Σ αᵢ yᵢ K(xᵢ, x) + b
SVM doesn't natively output probabilities Platt scaling fits a sigmoid on top:
Hyperparameters
Regularization — margin vs
C SVC, SVR 0.01 to 1000
error trade-off
(x − min) / (max −
MinMaxScaler When distribution unknown
min)
Advantages
Disadvantages
Real-World Applications
Domain Application
Finds a boundary enclosing the training data new points outside = anomalies
Used for:
Intrusion detection
A model with 99% accuracy can still be completely useless (class imbalance)
Accuracy
Problem: 95% of emails are not spam → predicting "not spam" always gives 95%
accuracy completely useless model.
Answers: "Of all real negatives, how many did I correctly reject?"
Specificity = 1 − FPR
F1 Score
F-Beta Score
FDR = 1 − Precision
Precision and Recall are in direct conflict improving one hurts the other.
Decision Threshold
AUC interpretation: Probability that the model ranks a random positive higher than a
random negative.
Advantages of AUC-ROC:
Threshold-independent
Precision
|●────────
| \
| \ ← Good Model
0.5 | \
| ●
|_____________
0.0 0.5 1.0
Recall
Range: 0 (perfect) to ∞
+1 Perfect prediction
Random
0
prediction
−1 Perfectly wrong
Advantages:
Cohen's Kappa
Measures agreement between predicted and actual labels, correcting for chance.
Po = observed accuracy
Interpretatio
Kappa n
Almost
> 0.8
perfect
0 Random
Macro Average metric across classes equally Equal importance to all classes
Calibration
"If my model predicts 70% for 100 samples → ~70 should actually be positive"
Calibration Methods
K-Fold Cross-Validation
K=5:
Fold 1: [Test][Train][Train][Train][Train]
Fold 2: [Train][Test][Train][Train][Train]
Fold 3: [Train][Train][Test][Train][Train]
Fold 4: [Train][Train][Train][Test][Train]
Fold 5: [Train][Train][Train][Train][Test]
─────────────────────────────────
Average accuracy, F1, AUC...
Stratified K-Fold
Leave-One-Out (LOO)
K = n (each sample is test once)
Computationally expensive
Problem
Dataset: 950 negative, 50 positive → predicting all negative = 95% accuracy (useless).
Resampling Strategies
CLUSTERING
Clustering is an unsupervised machine learning technique used to group similar
data points together without using labelled data. It helps discover hidden
patterns or natural groupings in datasets by placing similar data points into the
same cluster.
Types of Clustering
Hard Clustering
Hard clustering assigns each data point to exactly one cluster. A data point
cannot belong to multiple clusters, making the grouping clear and easy to
interpret.
Example
If customers are divided into two clusters, each customer belongs completely to
either Cluster 1 or Cluster 2. A customer cannot belong to both clusters at the
same time.
Common Uses
Market segmentation: Businesses group customers with similar buying
behaviour to design targeted marketing strategies.
Customer grouping: Companies organize customers into clear categories for
better service and analysis.
Document clustering: Documents with similar topics or keywords are grouped
together for easier organization.
Limitation
Cannot represent overlapping groups: Hard clustering cannot handle
situations where a data point may logically belong to multiple groups.
Soft Clustering
Soft clustering allows a data point to belong to multiple clusters with different
probabilities. Instead of assigning a strict cluster, it gives a degree of
membership to each cluster.
Example
A data point may belong 70% to Cluster 1 and 30% to Cluster 2, indicating
that it shares characteristics with both groups.
Use Cases
Overlapping class boundaries: Useful when data points cannot be clearly
separated into distinct groups.
Customer personas: Helps represent customers who share traits with multiple
behavioral groups.
Medical diagnosis: Patients may show symptoms related to multiple conditions.
Benefits
Captures ambiguity: Represents uncertainty when cluster boundaries are not
clear.
Models gradual transitions: Allows smooth transitions between clusters instead
of strict separation.
Clustering Methods
Centroid based Clustering
Centroid based clustering group data points around central points called
centroids. Each cluster is represented by a central point (centroid or medoid),
and data points are assigned to the nearest center.
Algorithms:
K-means: Iteratively assigns points to nearest centroid and recalculates
centroids to minimize intra cluster variance.
K-medoids: Similar to K-means but uses actual data points (medoids) as
centers, robust to outliers.
Advantages:
Fast and scalable for large datasets.
Simple to implement and interpret.
Limitations:
Requires choosing number of clusters in advance
Sensitive to initialization and outliers.
Not suitable for non-spherical clusters.
Density based clustering identifies clusters as regions where data points are
densely packed together. Points in low density areas are treated as noise.
Algorithms:
DBSCAN: Groups points with sufficient neighbors; labels sparse points as
noise.
OPTICS: Extends DBSCAN to handle varying densities.
Advantages:
Handles clusters of varying shapes and sizes.
Does not require cluster count upfront.
Effective in noisy datasets.
Limitations:
Difficult to choose parameters like epsilon and min points.
Less effective for varying density clusters (except OPTICS).
Approaches:
Agglomerative: Starts with each point as a cluster and merges them step by
step.
Divisive: Starts with one cluster and splits it into smaller clusters.
Advantages:
Provides a full hierarchy, easy to visualize
No need to specify number of clusters upfront
Limitations
Computationally intensive for large datasets
Merging/splitting decisions are irreversible
Choosing parameters can be difficult
Distribution-based Clustering
Distribution based clustering assumes that data points come from a mixture of
probability distributions. Each cluster is modelled as a statistical distribution.
Algorithm:
Gaussian Mixture Model (GMM): Fits data as a weighted mixture of Gaussian
distributions, assigns data points based on likelihood
Advantages:
Works well for clusters that are not perfectly circular.
Provides probabilistic memberships
Suitable for overlapping clusters
Limitations:
Requires specifying number of components
Computationally more expensive
Sensitive to initialization
Fuzzy Clustering
Algorithm:
Fuzzy C-Means: Similar to K-means but with fuzzy memberships updated
iteratively
Advantages:
Models data ambiguity explicitly
Useful for complex or imprecise data
Limitations:
Choosing fuzziness parameter can be tricky
Slightly higher computational cost
Applications
Customer Segmentation: Group customers based on behaviour or
demographics.
Anomaly Detection: Detect unusual activities in finance, security or sensor
data.
Image Segmentation: Divide images into meaningful regions for computer
vision tasks.
Recommendation Systems: Group similar users or items for personalized
suggestions.
Market Basket Analysis: Identify products frequently purchased together.
K means Clustering
K-Means Clustering groups similar data points into clusters without needing
labelled data. It is used to uncover hidden patterns when the goal is to
organize data based on similarity.
To achieve this we will use the K-means algorithm. "k" represents the number
of groups or clusters we want to classify our items into.
The algorithm will categorize the items into " k" groups or clusters of similarity.
To calculate that similarity we will use the Euclidean distance as a
measurement. The algorithm works as follows:
Initialization: We begin by randomly selecting k cluster centroids.
Assignment Step: Each data point is assigned to the nearest centroid, forming
clusters.
Update Step: After the assignment, we recalculate the centroid of each cluster
by averaging the points within it.
Repeat: This process repeats until the centroids no longer change or the
maximum number of iterations is reached.
The goal is to partition the dataset into k clusters such that data points within
each cluster are more similar to each other than to those in other clusters.
import numpy as np
import [Link] as plt
from [Link] import make_blobs
Output:
scaler = StandardScaler()
X = scaler.fit_transform(X)
k=3
clusters = {}
[Link](23)
Output:
[Link](X[:,0],X[:,1])
[Link](True)
for i in clusters:
center = clusters[i]['center']
[Link](center[0],center[1],marker = '*',c = 'red')
[Link]()
Output:
def distance(p1,p2):
return [Link]([Link]((p1-p2)**2))
curr_x = X[idx]
for i in range(k):
dis = distance(curr_x,clusters[i]['center'])
[Link](dis)
curr_cluster = [Link](dist)
clusters[curr_cluster]['points'].append(curr_x)
return clusters
def update_clusters(X, clusters):
for i in range(k):
points = [Link](clusters[i]['points'])
if [Link][0] > 0:
new_center = [Link](axis =0)
clusters[i]['center'] = new_center
clusters[i]['points'] = []
return clusters
We create a function to predict the cluster for each data point based on the
final centroids.
[Link]([Link](dist)): Appends the index of the closest cluster (the
one with the minimum distance) to pred.
clusters = assign_clusters(X,clusters)
clusters = update_clusters(X,clusters)
pred = pred_cluster(X,clusters)
[Link](X[:,0],X[:,1],c = pred)
for i in clusters:
center = clusters[i]['center']
[Link](center[0],center[1],marker = '^',c = 'red')
[Link]()
Output:
Arbitrary-Shaped Clusters : Clusters can take any shape not just circular or
convex.
Noise and Outliers: It effectively identifies and handles noise points without
assigning them to any cluster.
The figure above shows a data set with clustering algorithms: K-Means and
Hierarchical handling compact, spherical clusters with varying noise tolerance
while DBSCAN manages arbitrary-shaped clusters and noise handling.
Identify Core Points : For each point in the dataset count the number of points
within its eps neighborhood. If the count meets or exceeds MinPts mark the
point as a core point.
Form Clusters: For each core point that is not already assigned to a cluster
create a new cluster. Recursively find all density-connected points i.e points
within the eps radius of the core point and add them to the cluster.
Density Connectivity : Two points a and b are density-connected if there exists a
chain of points where each point is within the eps radius of the next and at
least one point in the chain is a core point. This chaining process ensures that
all points in a cluster are connected through a series of dense regions.
Label Noise Points: After processing all points any point that does not belong to
a cluster is labeled as noise.
We will create a dataset of 4 clusters using make_blob. The dataset have 300
points that are grouped into 4 visible clusters.
Now we apply DBSCAN clustering on our data, count it and visualize it using
the matplotlib library.
db = DBSCAN(eps=0.3, min_samples=10).fit(X)
core_samples_mask = np.zeros_like(db.labels_, dtype=bool)
core_samples_mask[db.core_sample_indices_] = True
labels = db.labels_
n_clusters_ = len(set(labels)) - (1 if -1 in labels else 0)
unique_labels = set(labels)
colors = ['y', 'b', 'g', 'r']
print(colors)
for k, col in zip(unique_labels, colors):
if k == -1:
col = 'k'
class_member_mask = (labels == k)
xy = X[class_member_mask & core_samples_mask]
[Link](xy[:, 0], xy[:, 1], 'o', markerfacecolor=col,
markeredgecolor='k',
markersize=6)
We will use the Silhouette score and Adjusted rand score for evaluating
clustering algorithms.
Silhouette's score is in the range of -1 to 1. A score near 1 denotes the best
meaning that the data point i is very compact within the cluster to which it
belongs and far away from the other clusters. The worst value is -1. Values
near 0 denote overlapping clusters.
Adjusted Rand Score is in the range of 0 to 1. More than 0.9 denotes excellent
cluster recovery and above 0.8 is a good recovery. Less than 0.5 is considered
to be poor recovery.
Black points represent outliers. By changing the eps and the MinPts we can
change the cluster configuration.
DBSCAN and K-Means are both clustering algorithms that group together
data that have the same characteristic. However they work on different
principles and are suitable for different types of data. We prefer to use
DBSCAN when the data is not spherical in shape or the number of classes is
not known beforehand.
DBSCAN K-Means
Before Reduction we can see that data exist in 3D (X,Y,Z). It has high
redundancy and Z contributes little meaningful information
On the right after reducing the dimensionality the data is represented in lower-
dimensional spaces. The top plot (X-Y) maintains the meaningful structure
while the bottom plot (Z-Y) shows that the Z-dimension contributed little
useful information.
This process makes data analysis more efficient hence improving computation
speed and visualization while minimizing redundancy
Feature Extraction
Feature extraction involves creating new features by combining or
transforming the original features. These new features retain most of the
dataset’s important information in fewer dimensions. Common feature
extraction methods are:
Principal Component Analysis (PCA): Converts correlated variables into
uncorrelated principal components hence reducing dimensionality while
maintaining as much variance as possible enabling more efficient analysis.
Factor Analysis: Groups variables by correlation and keeps the most relevant
ones for further analysis.
Independent Component Analysis (ICA): Identifies statistically independent
components, ideal for applications like ‘blind source separation’ where
traditional correlation-based methods fall short.
Advantages
Reduces computation time as models process fewer features.
Makes data easier to visualize and understand patterns.
Helps reduce overfitting and improves model generalization.
Disadvantages
May lead to loss of important information from the data.
Choosing the right number of dimensions can be challenging.
Excessive reduction can negatively affect model accuracy.
Collaborative Filtering
Collaborative Filtering
Collaborative filtering works by identifying users with similar preferences and
recommending items based on what those similar users like. Instead of using
item features, it groups users into clusters and suggests content according to
the shared preferences of each group.
User 1 and User 2 have nearly similar ratings (both liked Movie 1), showing
similar preferences
Based on this, Movie 3 (liked by User 2) can be recommended to User 1
Similarly, Movie 4 (liked by User 1) can be recommended to User 2
User 1 and User 3 have opposite tastes, so their recommendations will differ
User 3 and User 4 share similar low ratings for Movie 2
Since User 3 disliked Movie 4, it can be predicted that User 4 may also dislike
Movie 4
Cosine Similarity in Collaborative Filtering
Cosine similarity measures how similar two users are based on their ratings. A
higher cosine value means users have similar preferences, while a lower value
means they are different. Missing values are often treated as 0 to simplify
calculations.
Measures similarity between users using their rating patterns
Higher cosine value means more similar users
Lower cosine value means less similar users
Missing ratings can be filled with 0 for easy calculation
Helps in recommending items liked by similar users
Example:
After rounding, User 1 and User 2 show similar patterns (more 1s) which
means similar preferences
User 3 and User 4 show similar patterns (more 0s) which means similar dislikes
Normalizing Rating
Normalization adjusts user ratings by subtracting each user’s average rating
from their given ratings. This converts values into positive and negative scores,
making it easier to compare user preferences fairly.
Advantages
Unlike content-based systems, it does not rely on limited item features making
it more flexible in different use cases
It can handle a wide variety of data since it learns from user interactions instead
of predefined content
It provides strong personalization by recommending items based on similar
users’ preferences
It adapts easily to changes in user behaviour over time, improving
recommendations continuously
It performs well when large amounts of user data are available, increasing
accuracy and relevance
Challenges
As the number of users and items increases, computation and storage
requirements grow significantly, making the system slower
Scalability becomes a major issue with large datasets, affecting performance
and accuracy
Relies heavily on historical data, so it may struggle when there is limited or
new user data
Tends to recommend similar types of items repeatedly, reducing diversity in
recommendations
May not capture changing interests instantly if recent data is limited
UNIT-5
Association Rule
Association rules are a fundamental concept used to find relationships,
correlations or patterns within large sets of data items. They describe how
often item sets occur together in transactions and express implications of the
form:
Where X and Y are disjoint sets of items. This rule suggests that when items
in XX appear, items in YY tend to appear as well. Association rules originated
from market basket analysis and help retailers and analysts understand customer
behavior by discovering item associations in transaction data. For example, a
rule stating
Key Components
Antecedent (X): The "if" part representing one or more items found in
transactions.
Consequent (Y): The "then" part, representing the items likely to be purchased
when antecedent items appear.
Rules are evaluated based on metrics that quantify their strength and usefulness:
Lift > 1 implies a positive association — items occur together more than
expected.
Lift = 1 implies independence.
Lift < 1 implies a negative association.
Implementation
Step 1: Install and Import Libraries
We will install and import all the required libraries such as pandas,
mixtend, matplotlib, networkx.
import pandas as pd
from [Link] import TransactionEncoder
from mlxtend.frequent_patterns import apriori, association_rules
import [Link] as plt
import seaborn as sns
import networkx as nx
data = pd.read_csv("Groceries_dataset.csv")
print([Link]())
output
Apriori requires this one-hot encoded format where columns = items and rows =
transactions with True/False flags.
transactions = [Link]('Member_number')[
'itemDescription'].apply(list).[Link]()
te = TransactionEncoder()
te_ary = [Link](transactions).transform(transactions)
df = [Link](te_ary, columns=te.columns_)
[Link]()
Output:
print(frequent_itemsets.head())
Output:
rules = association_rules(
frequent_itemsets, metric="confidence", min_threshold=0.3)
print([Link]())
Output:
item_frequencies = [Link]().sort_values(ascending=False)
[Link](figsize=(10, 6))
[Link](x=item_frequencies.head(10).values,
y=item_frequencies.head(10).index)
[Link]('Top 10 Frequent Items')
[Link]('Frequency')
[Link]('Items')
[Link]()
Output:
[Link](figsize=(8, 6))
scatter = [Link](rules['support'], rules['confidence'],
c=rules['lift'], cmap='viridis', alpha=0.7)
[Link](scatter, label='Lift')
[Link]('Support')
[Link]('Confidence')
[Link]('Scatter Plot of Association Rules')
[Link]()
Output:
Step 8: Heatmap of Confidence for Selected Rules
rules['antecedents_str'] = rules['antecedents'].apply(
lambda x: ', '.join(list(x)))
rules['consequents_str'] = rules['consequents'].apply(
lambda x: ', '.join(list(x)))
top_ants = [Link]('antecedents_str')['support'].sum().nlargest(10).index
top_cons = [Link]('consequents_str')['support'].sum().nlargest(10).index
[Link](figsize=(12, 8))
[Link](heatmap_data, annot=True, cmap='YlGnBu',
linewidths=0.5, cbar_kws={'label': 'Confidence'})
[Link]('Heatmap of Confidence for Top Association Rules')
[Link]('Consequents')
[Link]('Antecedents')
[Link]()
Output:
Use Cases
Market Basket Analysis : Identifies products often bought together to improve
store layouts and promotions (e.g., bread and butter).
Recommendation Systems : Suggests related items based on buying patterns (e.g.,
accessories with laptops).
Fraud Detection: Detects unusual transaction patterns indicating fraud.
Healthcare Analytics : Finds links between symptoms, diseases and treatments
(e.g., symptom combinations predicting a disease).
Advantages
Interpretable and Easy to Explain : Rules offer clear “if-then” relationships
understandable to non-technical stakeholders.
Unsupervised Learning : Works well on unlabeled data to find hidden patterns
without prior knowledge.
Flexible Data Types: Effective on transactional, categorical and binary data.
Helps in Feature Engineering : Can be used to create new features for downstream
supervised models.
Limitations
Large Number of Rules : Can generate many rules, including trivial or redundant
ones, making interpretation hard.
Support Threshold Sensitivity : High support thresholds miss interesting but
infrequent patterns; low thresholds generate too many rules.
Not Suitable for Continuous Variables : Requires discretization or binning before
use with numerical attributes.
Computationally Expensive : Performance degrades on very large or dense
datasets due to combinatorial explosion.
Statistical Significance : High confidence doesn’t guarantee a meaningful rule;
domain knowledge is essential to validate findings.
ECLAT Algorithm
Apriori uses a horizontal format where each transaction is a row and it follows
a breadth-first search (BFS) strategy. This means it scans the database
multiple times to find frequent item combinations.
ECLAT on the other hand uses a vertical format where each item is linked to a
list of transaction IDs (TIDs). It uses a depth-first search (DFS) strategy which
requires fewer scans and makes it faster and more memory-efficient.
This vertical approach significantly reduces the number of database scans
making ECLAT faster and more memory-efficient especially for large
datasets.
Aspect Apriori ECLAT
Database
Multiple scans required Fewer scans needed
Scans
Memory
Less memory-efficient More memory-efficient
Efficiency
Working
Let’s walk through an example to better understand how ECLAT algorithm
works. Consider the following transaction dataset represented in a Boolean
matrix:
Brea
Transaction ID d Butter Milk Coke Jam
T1 1 1 0 0 1
T2 0 1 0 1 0
T3 0 1 1 0 0
T4 1 1 0 1 0
T5 1 0 1 0 0
T6 0 1 1 0 0
T7 1 0 1 0 0
T8 1 1 1 0 1
T9 1 1 1 0 0
The core idea of the ECLAT algorithm is based on the interaction of datasets
to calculate the support of itemsets, avoiding the generation of subsets that are
not likely to exist in the dataset. Here’s a breakdown of the steps:
Step 1: Create the Tidset
The first step is to generate the tidset for each individual item. A tidset is
simply a list of transaction IDs where the item appears. For example: k = 1,
minimum support = 2
Item Tidset
ECLAT then proceeds by recursively combining the tid sets. The support of
an item set is determined by the intersection of tid sets. For example: k = 2
Item Tidset
{Bread, Butter,
{T8, T9}
Milk}
The algorithm stops once no more itemset combinations meet the minimum
support threshold. k = 4
Item Tidset
Bread Butter
Bread Milk
Bread Jam
Items Bought Recommended Products
Butter Milk
Butter Coke
Butter Jam
Bread and
Milk
Butter
Bread and
Jam
Butter
Purpose: create a mapping item -> set_of_tids (the vertical format ECLAT
uses).
Benefit: intersections of these tidsets are quick to compute and give support
counts.
def generate_tidsets(transactions):
item_tidset = defaultdict(set)
for tid, items in [Link]():
for item in items:
item_tidset[item].add(tid)
return item_tidset
item_tidset = generate_tidsets(transactions)
Purpose: convert the item_tidset dict into a sorted list of (item, tidset) pairs.
Tip: sorting by tidset size (ascending) often helps pruning and makes
intersections cheaper earlier.
Call the recursive function, then inspect the found frequent itemsets (with
support counts).
item_tidset = generate_tidsets(transactions)
items = sorted(item_tidset.items(), key=lambda x: len(x[1]))
frequent_itemsets = {}
eclat([], items, min_support, frequent_itemsets)
Applications
Market Basket Analysis: Identifying frequently purchased items together.
Recommendation Systems: Suggesting products based on past purchase
patterns.
Medical Diagnosis: Finding co-occurring symptoms in medical records.
Web Usage Mining: Analyzing web logs to understand user behavior.
Fraud Detection: Discovering frequent patterns in fraudulent activities.
Advantages
Efficient in Dense Datasets: Performs better than Apriori in datasets with
frequent co-occurrences.
Memory Efficient: Uses vertical representation, reducing redundant scans.
Fast Itemset Intersection: Computing itemset support via TID-set
intersections is faster than scanning transactions repeatedly.
Better Scalability: Can handle larger datasets due to its depth-first search
mechanism.
Disadvantages
High Memory Requirement: Large TID sets can consume significant
memory.
Not Suitable for Sparse Data: Works better in dense datasets, but
performance drops for sparse datasets where intersections result in small
itemsets.
Sensitive to Large Transactions: If a transaction has too many items its
corresponding TID-set intersections can be expensive.
Foundational Concepts
Itemset
1-itemset: {bread}
Frequent Itemset
Support
Confidence
Lift
Leverage
Jaccard Coefficient
Kulczynski Measure
This enables pruning eliminating huge numbers of candidate itemsets without scanning
the database, making algorithms computationally feasible.
Join Step
Combine two frequent (k-1)-item sets that share the same first (k-2) items to generate a
candidate k-item set.
Prune Step
Remove any candidate whose any (k-1)-subset is infrequent — using the Apriori
principle.
Support Counting
Scan the database to verify which candidates actually meet minimum support.
Data Representations
T1 → {A, B, C}
T2 → {A, C}
T3 → {B, D}
A → {T1, T2}
B → {T1, T3}
C → {T1, T2}
FP-Tree Concepts
Nodes contain:
Item name
Count (support)
Header Table: Links all occurrences of each item across the tree.
For item X — all prefix paths in the FP-Tree leading to X, with adjusted counts.
Conditional FP-Tree
FP-Tree built from the conditional pattern base of item X — used to recursively mine
patterns.
Mining Order
Items mined in reverse order of frequency (least frequent first) to keep conditional trees
small.
Itemset Lattice
{A, B, C}
/ | \
{A, B} {A, C} {B,C}
| \/ | \/ |
{A} {B} {C}
|
{}
Bottom-up traversal → finds small frequent item sets first (Apriori style)
A frequent item set with no frequent superset most compact representation of all frequent
item sets.
A frequent item set with no superset with the same support lossless compression of all
frequent item sets.
Closed ⊇ Maximal (all maximal item sets are closed but not vice versa)
Rule Strength
Determined by support, confidence, and lift together — not any single measure alone.
Redundant Rules
Rule A→B is redundant if a more specific rule A'→B (where A' ⊂ A) has equal or higher
confidence.
Rule Pruning
Null Transaction
Problem: Measures like support and confidence are inflated by null transactions in sparse
datasets.
Kulczynski
All-confidence
Not null-invariant:
Support-Confidence Framework
The standard threshold pair used to filter rules — but does NOT guarantee interestingness
(a rule can have high support & confidence yet be misleading if lift < 1).
Types of Patterns
Approximate Rule
Actionable Rule
A rule that provides useful, actionable business insight — the ultimate goal.
Trivial Rule
Technically valid but provides no new information (e.g., stating the obvious).
Concept Hierarchy
Cross-level Rules
Key algorithms:
Constraint-Based Mining
Mining rules under user-defined constraints to reduce search space and improve
relevance.
Types of Constraints:
Type Example
Objective Measures
Subjective Measures
Interestingness
Scalability Concepts
Sampling
Mine rules on a random sample → verify on full database. Faster but may miss some
patterns.
Partitioning
Divide DB into partitions → mine each → combine. Any globally frequent itemset must
be locally frequent in at least one partition.
Incremental Mining
Update rules when new transactions are added without re-mining from scratch.
Distribute the database and mining across multiple processors/nodes — essential for big
data ARL.
Apriori Algorithm
For Example:
If customers often buy bread and butter together in a grocery store, the store
can place these items nearby or create combo offers to improve sales and
customer experience.
Working
Identifying Frequent Item-Sets
The Apriori algorithm starts by looking through all the data to count how
many times each single item appears. These single items are called 1-Item-
Sets.
Next it uses a rule called minimum support this is a number that tells us how
often an item or group of items needs to appear to be important. If an item
appears often enough meaning its count is above this minimum support it is
called a frequent Item-Set.
Support
Confidence
Lift
Lift measures how much more likely two items are purchased together
compared to random chance.
All items have support ≥ 50%, so they qualify as frequent 1-Item-Sets. If any
item has support < 50%, It will be omitted from the frequent 1- Item-Sets.
Applications
Used in e-commerce to recommend products that are frequently bought
together
Helps food delivery platforms identify popular meal combinations and combo
offers
Enables streaming services to recommend related movies and shows
Assists financial services in analyzing spending patterns and personalized
offers
Supports travel platforms in creating combined travel and hotel packages
Used in health and fitness applications for personalized recommendations
based on user behaviour