Understanding Machine Learning Basics
Understanding Machine Learning Basics
Machine Learning, often abbreviated as ML, is a subset of artificial intelligence (AI) that
focuses on the development of computer algorithms that improve automatically through
experience and by the use of data. In simpler terms, machine learning enables computers to
learn from data and make decisions or predictions without being explicitly programmed to
do so.
At its core, machine learning is all about creating and implementing algorithms that facilitate
these decisions and predictions. These algorithms are designed to improve their
performance over time, becoming more accurate and effective as they process more data.
Data Pre-processing − It is a key step in the process of machine learning, which involves
deleting duplicate data, fixing errors, managing missing data either by eliminating or filling it
in, and adjusting and formatting the data.
Choosing the Right Model − The next step is to select a machine learning model; once data
is prepared, then we apply it to ML models like linear regression, decision trees, and neural
networks that may be selected to implement. This selection depends on many factors, such
as the kind of data and your problem, the size and type of data, the complexity, and the
computational resources.
Training the Model − This step includes training the model from the data so it can make
better predictions.
Evaluating the model − When module is trained, the model has to be tested on new data
that they haven't been able to see during training.
Hyperparameter Tuning and Optimization − After evaluating the model, you may need to
adjust its hyperparameters to make it more efficient. You should try different combinations
of parameters and cross-validation to ensure that the model performs well on different data
sets.
Predictions and Deployment − When the model has been programmed and optimized, it
will be ready to estimate new data. This is done by adding new data to the model and using
its output for decision-making or other analysis. The deployment includes its integration into
a production environment to make it capable of processing real-world data.
Supervised learning
Supervised learning is the most common type of machine learning. In this approach, the
model is trained on a labeled dataset. In other words, the data is accompanied by a label
that the model is trying to predict. This could be anything from a category label to a real-
valued number.
The model learns a mapping between the input (features) and the output (label) during the
training process. Once trained, the model can predict the output for new, unseen data.
Common examples of supervised learning algorithms include linear regression for regression
problems and logistic regression, decision trees, and support vector machines for
classification problems. In practical terms, this could look like an image recognition process,
wherein a dataset of images where each picture is labeled as "cat," "dog," etc., a supervised
model can recognize and categorize new images accurately.
Unsupervised learning
Unsupervised learning, on the other hand, involves training the model on an unlabeled
dataset. The model is left to find patterns and relationships in the data on its own.
This type of learning is often used for clustering and dimensionality reduction. Clustering
involves grouping similar data points together, while dimensionality reduction involves
reducing the number of random variables under consideration by obtaining a set of principal
variables.
Reinforcement learning
Reinforcement learning is a type of machine learning where an agent learns to make
decisions by interacting with its environment. The agent is rewarded or penalized (with
points) for the actions it takes, and its goal is to maximize the total reward.
Besides these three main types, modern machine learning also includes two other important
approaches: Self-Supervised Learning and Semi-Supervised Learning.
Self-Supervised Learning
Self-Supervised Learning (SSL) is a modern approach where models generate their own
labels from raw data. It doesn’t rely on manual annotation instead, the model learns by
predicting parts of data from other parts.
Example: In NLP, models like BERT or GPT learn by predicting masked words in sentences,
using surrounding context as supervision. This helps them learn language understanding
without human labelling.
Traditional programming struggles with tasks like language understanding and medical
diagnosis. ML learns from data and predicts outcomes easily.
Examples:
The internet generates huge amounts of data every day. Machine Learning processes and
analyzes this data quickly by providing valuable insights and real-time predictions.
Examples:
Examples:
Examples:
ML models evolve and improve with more data helps in making them smarter over time.
They adapt to user behavior and increase their performance.
Examples:
• Voice assistants like Siri and Alexa learning our preferences and accents.
• Data provides the examples from which models learn patterns and relationships.
• High-quality and diverse data improves how well models perform and generalize to
new situations.
• Separate datasets for validation and testing measure how well the model works on
unseen data.
• Data drives continuous improvements in models through feedback loops.
2. Data-Driven Insights: It can analyze large amounts of data to identify patterns and
trends that might be missed by people and help businesses make better decisions.
2. Security and Privacy Concerns: Since it depends on large amounts of data, there is a
risk of sensitive information being exposed so protecting privacy is important.
4. Job Displacement and Automation: Automation may replace some jobs so retraining
and helping workers learn new skills is important to adapt to these changes.
1. Healthcare: It helps doctors to diagnose diseases from medical images like X-rays and
MRIs. It also predicts patient outcomes and personalizes treatments which improves
healthcare quality.
2. Finance: In finance it detects fraudulent transactions in real time and supports
algorithmic trading. It also helps to assess credit risk helps in making lending safer
and faster.
5. Social Media and Entertainment: Platforms like Netflix and YouTube use ML to
recommend content we'll enjoy. It enables image and speech recognition for better
user interaction.
• Gather a dataset where each input has a known correct output (label).
• Divide the data into training data (about 80%) and testing data (about 20%).
• The model will learn from the training data and be evaluated on the testing data.
• The model tries to find patterns that map inputs to correct outputs.
4. Validate and Test the Model
• Evaluate the model using testing data it has never seen before.
• The model predicts outputs and these predictions are compared with the actual
labels to calculate accuracy or error.
Classification
Classification is a supervised machine learning technique used to predict labels or categories
based on input data. The goal is to assign each data point to a predefined class, such as
spam vs. non-spam emails or diseased vs. healthy patients.
For example, a classification model might be trained on dataset of images labeled as either
dogs or cats and it can be used to predict the class of new and unseen images as dogs or cats
based on their features such as colour, texture or shape.
Types of Classification
When we talk about classification in machine learning, we’re talking about the process of
sorting data into categories based on specific features or characteristics. There are different
types of classification problems depending on how many categories (or classes) we are
working with and how they are organized.
1. Binary Classification
This is the simplest kind of classification. In binary classification, the goal is to sort the data
into two distinct categories. Think of it like a simple choice between two options. Imagine a
system that sorts emails into either spam or not spam. It works by looking at different
features of the email like certain keywords or sender details and decides whether it’s spam
or not. It only chooses between these two options.
2. Multiclass Classification
Here, instead of just two categories, the data needs to be sorted into more than two
categories. The model picks the one that best matches the input. Think of an image
recognition system that sorts pictures of animals into categories like cat, dog and bird.
3. Multi-Label Classification
In multi-label classification single piece of data can belong to multiple categories at once.
Unlike multiclass classification where each data point belongs to only one class, multi-label
classification allows datapoints to belong to multiple classes. A movie recommendation
system could tag a movie as both action and comedy. The system checks various features
(like movie plot, actors or genre tags) and assigns multiple labels to a single piece of data,
rather than just one.
4. Imbalanced classification
Imbalanced classification, in which some categories contain more data points than others,
requires a specialized approach. As certain groups amass more data points, some
classification models become biased toward those groups and increasingly predict in their
favor.
Classification Algorithms
1. Linear Classifiers: Linear classifier models create a linear decision
boundary between classes. They are simple and computationally efficient.
2. Non-linear Classifiers: Non-linear models create a non-linear decision
boundary between classes. They can capture more complex relationships
between input features and target variable.
Logistic functions are ideal for classification problems since their output is between 0 and
1. Many fields employ it because of its simplicity, interpretability, and efficiency. Logistic
Regression works well when features and event probability are linear. Logistic Regression
used for binary classification tasks. A logistic function models probability in this linear model.
2. Decision Tree
Decision Trees are versatile and simple classification and regression techniques. Recursively
splitting the dataset into key-criteria subgroups provides a tree-like structure. Judgments at
each node produce leaf nodes. Decision trees are easy to understand and depict, making
them useful for decision-making. A tree-like model of decisions and their consequences,
including chance event outcomes, resource costs and utility.
3. Random Forest
Random forest are an ensemble learning techniques that combines multiple decision trees
to improve predictive accuracy and control over-fitting. By aggregating the predictions of
numerous trees, Random Forests enhance the decision-making process, making them robust
against noise and bias.
Random Forest uses numerous decision trees to increase prediction accuracy and reduce
overfitting. It constructs many trees and integrates their predictions to create a reliable
model. Diversity is added by using a random dataset and characteristics in each tree.
Random Forests excel at high-dimensional data, feature importance metrics, and overfitting
resistance. Many fields use them for classification and regression.
[Link] Vector Machine (SVM)
SVM is an effective classification and regression algorithm. It seeks the hyperplane that best
classifies data while increasing the margin. SVM works well in high-dimensional areas and
handles nonlinear feature interactions with its kernel technique. It is powerful classification
algorithm known for their accuracy in high-dimensional spaces
SVM is robust against overfitting and generalizes well to different datasets. It finds
applications in image recognition, text classification, and bioinformatics, among other fields.
Its use cases span image recognition, text categorization, and bioinformatics, where
precision is paramount.
[Link] Bayes
Text categorization and spam filtering benefit from Bayes theorem-based probabilistic
classification algorithm Naive Bayes. Despite its simplicity and "naive" assumption of feature
independence, Naive Bayes often works well in practice. It uses conditional probabilities of
features to calculate the class likelihood of an instance. Naive Bayes handles high-
dimensional datasets quickly.
Naive Bayes which describes the probability of an event, based on prior knowledge of
conditions that might be related to the event. Naive Bayes classifiers assume that the
presence (or absence) of a particular feature of a class is unrelated to the presence (or
absence) of any other feature, given the class variable
• Email spam filtering: Filters our emails into spam or not spam based on email
content.
• Medical diagnosis: Machine learning models classify whether a patient has a certain
condition like cancer or diabetes based on medical data such as test results,
symptoms and patient history. This aids doctors in making quicker, more accurate
diagnoses, improving patient care.
Regression
Regression in machine learning refers to a supervised learning technique where the goal is
to predict a continuous numerical value based on one or more independent features. It finds
relationships between variables so that predictions can be made. we have two types of
variables present in regression:
• Dependent Variable (Target): The variable we are trying to predict e.g house price.
• Independent Variables (Features): The input variables that influence the prediction
e.g locality, number of rooms.
Regression analysis problem works with if output variable is a real or continuous value such
as “salary” or “weight”. Many different regression models can be used but the simplest
model in them is linear regression.
Types of Regression
Regression can be classified into different types based on the number of predictor variables
and the nature of the relationship between variables:
3. Polynomial Regression
Polynomial regression is used to model with non-linear relationships between the
dependent variable and the independent variables. It adds polynomial terms to the linear
regression model to capture more complex relationships. For example when we want to
predict a non-linear trend like population growth over time we use polynomial regression.
4. Ridge & Lasso Regression
Ridge & lasso regression are regularized versions of linear regression that help avoid
overfitting by penalizing large coefficients. When there’s a risk of overfitting due to too many
features we use these type of regression algorithms.
• Mean Absolute Error (MAE): The average absolute difference between the
predicted and actual values of the target variable.
• Mean Squared Error (MSE): The average squared difference between the
predicted and actual values of the target variable.
• Root Mean Squared Error (RMSE): Square root of the mean squared error.
• Huber Loss: A hybrid loss function that transitions from MAE to MSE for larger
errors, providing balance between robustness and MSE’s sensitivity to outliers.
• R2 – Score: Higher values indicate better fit ranging from 0 to 1.
Applications of Regression
• Predicting prices: Used to predict the price of a house based on its size, location and
other features.
• Forecasting trends: Model to forecast the sales of a product based on historical sales
data.
• Identifying risk factors: Used to identify risk factors for heart patient based on
patient medical data.
Advantages of Regression
• Easy to understand and interpret.
• Robust to outliers.
Disadvantages of Regression
• Assumes linearity.
• Sensitive to situation where two or more independent variables are highly correlated
with each other i.e multicollinearity.
Regression,
Algorithm Classification Purpose Method Use Cases
Linear equation
Predict Predicting
minimizing sum of
Regression continuous continuous
Linear squares of
output values values
Regression residuals
Reducing
Improve
Combining overfitting,
classification and
Both multiple decision improving
regression
Random trees prediction
accuracy
Forests accuracy
Create Maximizing
hyperplane for margin between Classification
Both classification or classes or and Regression
predict predicting tasks
SVM continuous values continuous values
Finding k closest
Classification
Predict class or neighbors and
and Regression
Both value based on k predicting based
tasks, sensitive
closest neighbors on majority or
to noisy data
KNN average
Classification
Combine weak Iteratively and Regression
Both learners to create correcting errors tasks to improve
Gradient strong model with new models prediction
Boosting accuracy
sentiment
analysis, medical
These types of supervised learning in machine learning vary based on the problem we're
trying to solve and the dataset we're working with. In classification problems, the task is to
assign inputs to predefined classes, while regression problems involve predicting numerical
outcomes.
• Cancer cell classification: Implements supervised learning for cancer cells based on
their features and identifying them if they are ‘malignant’ or ‘benign.
• Stock Price Prediction: Applies supervised learning to predict a signal that indicates
whether buying a particular stock will be helpful or not.
Advantages
Here are some advantages of supervised learning listed below:
• Simplicity & clarity: Easy to understand and implement since it learns from labeled
examples.
• High accuracy: When sufficient labeled data is available, models achieve strong
predictive performance.
• Versatility: Works for both classification like spam detection, disease prediction and
regression like price forecasting.
• Generalization: With enough diverse data and proper training, models can generalize
well to unseen inputs.
Disadvantages
• Requires labeled data: Large amounts of labeled datasets are expensive and time-
consuming to prepare.
• Bias from data: If training data is biased or unbalanced, the model may learn and
amplify those biases.
• Overfitting risk: Model may memorize training data instead of learning general
patterns, especially with small datasets.
• Not scalable for some problems: In tasks with millions of possible labels like natural
language, supervised labeling becomes impractical.
Decision Tree in Machine Learning
A decision tree is a supervised learning algorithm used for both classification and
regression tasks. It has a hierarchical tree structure which consists of a root node,
branches, internal nodes and leaf nodes. It works like a flowchart help to make decisions
step by step where:
Decision trees are widely used due to their interpretability, flexibility and low
preprocessing needs.
Let’s consider a decision tree for predicting whether a customer will buy a product based
on age, income and previous purchases: Here's how the decision tree works:
1. Information Gain
Information Gain tells us how useful a question (or feature) is for splitting data into
groups. It measures how much the uncertainty decreases after the split. A good question
will create clearer groups and the feature with the highest Information Gain is chosen to
make the decision.
For example if we split a dataset of people into "Young" and "Old" based on age and all
young people bought the product while all old people did not, the Information Gain would
be high because the split perfectly separates the two groups with no uncertainty left
For example if a dataset has an equal number of "Yes" and "No" outcomes (like 3 people
who bought a product and 3 who didn’t), the entropy is high because it’s uncertain which
outcome to predict. But if all the outcomes are the same (all "Yes" or all "No") the entropy
is 0 meaning there is no uncertainty left in predicting the outcome.
2. Gini Index
Gini Index is a metric to measure how often a randomly chosen element would be
incorrectly identified. It means an attribute with a lower Gini index should be preferred.
Sklearn supports “Gini” criteria for Gini Index and by default it takes “gini” value.
For example if we have a group of people where all bought the product (100% "Yes") the
Gini Index is 0 indicate perfect purity. But if the group has an equal mix of "Yes" and "No"
the Gini Index would be 0.5 show high impurity or uncertainty. Formula for Gini Index is
given by :
1. Binomial Logistic Regression: This type is used when the dependent variable has only
two possible categories. Examples include Yes/No, Pass/Fail or 0/1. It is the most
common form of logistic regression and is used for binary classification problems.
2. Multinomial Logistic Regression: This is used when the dependent variable has three or
more possible categories that are not ordered. For example, classifying animals into
categories like "cat," "dog" or "sheep." It extends the binary logistic regression to
handle multiple classes.
3. Ordinal Logistic Regression: This type applies when the dependent variable has three
or more categories with a natural order or ranking. Examples include ratings like "low,"
"medium" and "high." It takes the order of the categories into account when modeling.
2. This function takes any real number and maps it into the range 0 to 1 forming an
"S" shaped curve called the sigmoid curve or logistic curve. Because probabilities
must lie between 0 and 1, the sigmoid function is perfect for this purpose.
3. In logistic regression, we use a threshold value usually 0.5 to decide the class label.
If the sigmoid output is same or above the threshold, the input is classified
as Class 1.
If it is below the threshold, the input is classified as Class 0.
This approach helps to transform continuous input values into meaningful class
predictions.
1. Independent Variables: These are the input features or predictor variables used to
make predictions about the dependent variable.
2. Dependent Variable: This is the target variable that we aim to predict. In logistic
regression, the dependent variable is categorical.
3. Logistic Function: This function transforms the independent variables into a probability
between 0 and 1 which represents the likelihood that the dependent variable is either 0
or 1.
4. Odds: This is the ratio of the probability of an event happening to the probability of it
not happening. It differs from probability because probability is the ratio of occurrences
to total possibilities.
5. Log-Odds (Logit): The natural logarithm of the odds. In logistic regression, the log-odds
are modeled as a linear combination of the independent variables and the intercept.
6. Coefficient: These are the parameters estimated by the logistic regression model which
shows how strongly the independent variables affect the dependent variable.
7. Intercept: The constant term in the logistic regression model which represents the log-
odds when all independent variables are equal to zero.
Manufacturing
Manufacturing companies use logistic regression analysis to estimate the probability of part
failure in machinery. They then plan maintenance schedules based on this estimate to
minimize future failures.
Healthcare
Medical researchers plan preventive care and treatment by predicting the likelihood of
disease in patients. They use logistic regression models to compare the impact of family
history or genes on diseases.
Finance
Financial companies have to analyze financial transactions for fraud and assess loan
applications and insurance applications for risk. These problems are suitable for a logistic
regression model because they have discrete outcomes, like high risk or low risk and
fraudulent or not fraudulent.
Marketing
Online advertising tools use the logistic regression model to predict if users will click on an
advertisement. As a result, marketers can analyze user responses to different words and
images and create high-performing advertisements with which customers will engage.
Curve/Model
In this we find best fit line. In this we find S-Curve.
Fitting
For example we want to predict a student's exam score based on how many hours they
studied. We observe that as students study more hours, their scores go up. In the example
of predicting exam scores based on hours studied. Here
Independent variable (input): Hours studied because it's the factor we control or
observe.
Dependent variable (output): Exam score because it depends on hobw many hours
were studied.
Where:
y is the predicted value (dependent variable)
x is the input (independent variable)
m is the slope of the line (how much y changes when x changes)
b is the intercept (the value of y when x = 0)
The best-fit line will be the one that optimizes the values of m (slope) and b (intercept) so
that the predicted y values are as close as possible to the actual data points.
This method ensures that the line best represents the data where the sum of the squared
differences between the predicted values and actual values is as small as possible.
Limitations
Assumes Linearity: The method assumes the relationship between the variables is
linear. If the relationship is non-linear, linear regression might not work well.
Sensitivity to Outliers: Outliers can significantly affect the slope and intercept,
skewing(suddenly change direction or position) the best-fit line.
2. Independence of Errors: The errors in predictions should not affect each other.
3. Constant Variance (Homoscedasticity): The errors should have equal spread across all
values of the input. If the spread changes (like fans out or shrinks), it's called
heteroscedasticity and it's a problem for the model.
7. Additivity: The total effect on Y is just the sum of effects from each X, no mixing or
interaction between them.
Use Cases
Real Estate: Predict property prices using location, size and other factors.
Finance: Forecast stock prices using interest rates and inflation data.
Agriculture: Estimate crop yield from rainfall, temperature and soil quality.
E-commerce: Analyze how price, promotions and seasons affect sales.
A variety of evaluation measures can be used to determine the strength of any linear
regression model. These assessment metrics often give an indication of how well the
model is producing the observed outputs.
The most common measurements are:
Residual sum of Squares(RSS): The sum of squares of the residual for each data
point in the plot or data is known as the residual sum of squares or RSS. It is a
measurement of the difference between the output that was observed and what
was anticipated.
Total Sum of Squares (TSS): The sum of the data points' errors from the answer
variable's mean is known as the total sum of squares or TSS.
R squared metric is a measure of the proportion of variance in the dependent variable that
is explained the independent variables in the model.
Advantages
Linear regression is a relatively simple algorithm, making it easy to understand and
implement. The coefficients of the linear regression model can be interpreted as the
change in the dependent variable for a one-unit change in the independent variable,
providing insights into the relationships between variables.
Linear regression is computationally efficient and can handle large datasets effectively.
It can be trained quickly on large datasets, making it suitable for real-time applications.
Linear regression is relatively robust to outliers compared to other machine learning
algorithms. Outliers may have a smaller impact on the overall model performance.
Linear regression often serves as a good baseline model for comparison with more
complex machine learning algorithms.
Linear regression is a well-established algorithm with a rich history and is widely
available in various machine learning libraries and software packages.
Limitations
Linear regression assumes a linear relationship between the dependent and
independent variables. If the relationship is not linear, the model may not perform
well.
Linear regression is sensitive to multicollinearity, which occurs when there is a high
correlation between independent variables. Multicollinearity can inflate the variance
of the coefficients and lead to unstable model predictions.
Linear regression assumes that the features are already in a suitable form for the
model. Feature engineering may be required to transform features into a format that
can be effectively used by the model.
Linear regression is susceptible to both overfitting and underfitting. Overfitting occurs
when the model learns the training data too well and fails to generalize to unseen
data. Underfitting occurs when the model is too simple to capture the underlying
relationships in the data.
Linear regression provides limited explanatory power for complex relationships
between variables. More advanced machine learning techniques may be necessary for
deeper insights.
Neural Network
Neural networks are machine learning models that mimic the complex functions of the
human brain. These models consist of interconnected nodes or neurons that process data,
learn patterns and enable tasks such as pattern recognition and decision-making.
Neural networks are capable of learning and identifying patterns directly from data
without pre-defined rules. These networks are built from several key components:
Neurons: The basic units that receive inputs, each neuron is governed by a
threshold and an activation function.
Connections: Links between neurons that carry information, regulated by weights
and biases.
Weights and Biases: These parameters determine the strength and influence of
connections.
Propagation Functions: Mechanisms that help process and transfer data across
layers of neurons.
Learning Rule: The method that adjusts weights and biases over time to improve
accuracy.
Learning in neural networks follows a structured, three-stage
process:
3. Iterative Refinement: The network refines its output by adjusting weights and
biases, gradually improving its performance on diverse tasks.
where
w represents the weights
x represents the inputs
b is the bias
2. Backpropagation
After forward propagation, the network evaluates its performance using a loss
function which measures the difference between the actual output and the
predicted output. The goal of training is to minimize this loss. This is where
backpropagation comes into play:
Loss Calculation: The network calculates the loss which provides a measure of
error in the predictions. The loss function could vary; common choices are mean
squared error for regression tasks or cross-entropy loss for classification.
Gradient Calculation: The network computes the gradients of the loss function
with respect to each weight and bias in the network. This involves applying the
chain rule of calculus to find out how much each part of the output error can be
attributed to each weight and bias.
Weight Update: Once the gradients are calculated, the weights and biases are
updated using an optimization algorithm like stochastic gradient descent (SGD).
The weights are adjusted in the opposite direction of the gradient to minimize the
loss. The size of the step taken in each update is determined by the learning rate.
3. Iteration
This process of forward propagation, loss calculation, backpropagation and weight
update is repeated for many iterations over the dataset. Over time, this iterative
process reduces the loss and the network's predictions become more accurate.
Through these steps, neural networks can adapt their parameters to better
approximate the relationships in the data, thereby improving their performance on
tasks such as classification, regression or any other predictive modeling.
Mathematical Example
Consider a neural network with:
Inputs: i1, i2
Hidden layer: neurons h1 and h2
Output layer: one neuron (output)
Weights: w1, w2, w3, w4, w5, w6
Biases: b1 for hidden layer, b2 for output layer
This gives the final output of the network after applying the sigmoid activation
function in output layers, introducing the desired non-linearity.
1. Input Layer: This is where the network receives its input data. Each input neuron in
the layer corresponds to a feature in the input data.
2. Hidden Layers: These layers perform most of the computational heavy lifting. A
neural network can have one or multiple hidden layers. Each layer consists of units
(neurons) that transform the inputs into something that the output layer can use.
3. Output Layer: The final layer produces the output of the model. The format of
these outputs varies depending on the specific task like classification, regression.
Architecture: Made up of layers with unidirectional flow of data i.e., from input
through hidden and the output layer.
Training: Backpropagation is often used during training for the main aim of
reducing the prediction errors.
Applications: In visual and voice recognition, NLP, financial forecasting and
recommending system
When to use: Best for general-purpose tasks like classification and regression. Ideal
when data is static and has no sequential dependencies.
Key Components: Utilizing convolutional layers, pooling layers and fully connected
layers.
Applications: Used for classification of images, object detection, medical imaging
analyzes, autonomous driving and visualization in augmented reality.
When to use: Use when working with image, video or grid-structured data.
Advantages
Neural networks are widely used in many different applications because of their many
benefits:
Adaptability: Neural networks are useful for activities where the link between
inputs and outputs is complex or not well defined because they can adapt to new
situations and learn from data.
Pattern Recognition: Their proficiency in pattern recognition renders them
efficacious in tasks like as audio and image identification, natural language
processing and other intricate data patterns.
Parallel Processing: Because neural networks are capable of parallel processing by
nature, they can process numerous jobs at once which speeds up and improves the
efficiency of computations.
Non-Linearity: Neural networks are able to model and comprehend complicated
relationships in data by virtue of the non-linear activation functions found in
neurons which overcome the drawbacks of linear models.
Limitations
Neural networks while powerful, are not without drawbacks and difficulties:
Computational Intensity: Large neural network training can be a laborious and
computationally demanding process that demands a lot of computing power.
Black box Nature: As "black box" models, neural networks pose a problem in
important applications since it is difficult to understand how they make decisions.
Overfitting: Overfitting is a phenomenon in which neural networks commit training
material to memory rather than identifying patterns in the data. Although
regularization approaches help to alleviate this, the problem still exists.
Need for Large datasets: For efficient training, neural networks frequently need
sizable, labeled datasets; otherwise, their performance may suffer from incomplete
or skewed data.
Applications
Neural networks have numerous applications across various fields:
1. Image and Video Recognition: CNNs are extensively used in applications such as
facial recognition, autonomous driving and medical image analysis.
2. Natural Language Processing (NLP): RNNs and transformers power language
translation, chatbots and sentiment analysis.
3. Finance: Predicting stock prices, fraud detection and risk management.
4. Healthcare: Neural networks assist in diagnosing diseases, analyzing medical
images and personalizing treatment plans.
5. Gaming and Autonomous Systems: Neural networks enable real-time decision-
making, enhancing user experience in video games and enabling autonomous
systems like self-driving cars.
Regularization in Machine Learning
model, the loss function measures how well the model’s predictions match the actual data.
Regularization adds an extra term to this loss function that penalizes large weights.
Original Loss: Measures the difference between the model’s predictions and the
actual values.
Imagine we have a dataset with many features (variables), but not all of them are important
for predicting the output. Using L1 regularization can help the model focus on the most
Suppose we’re building a model to predict house prices based on various features like size,
number of rooms, age, location, etc. L2 regularization helps ensure that the model doesn’t
assign too much importance to any one feature and considers all of them in a balanced way.
Number of bedrooms
Without regularization, our model might give too much importance to some features, like
the presence of a swimming pool or the age of the house, even if those features don’t
significantly influence the price. This could lead to overfitting, especially if the training data
contains houses with unusual characteristics (outliers). For example, maybe one very
expensive house has a large swimming pool, and the model might learn that “swimming
as whether the house has a garage, by shrinking their corresponding weights to zero.
This makes the model simpler and helps focus on the most important factors (like
the price prediction, preventing any one feature from dominating the prediction.
Benefits of Regularization
Now, let’s see various benefits of regularization which are as follows:
It is used for tasks like clustering, dimensionality reduction and Association Rule
Learning.
The image shows set of animals like elephants, camels and cows that represents raw data
that the unsupervised learning algorithm will process.
The "Interpretation" stage signifies that the algorithm doesn't have predefined labels
or categories for the data. It needs to figure out how to group or organize the data
based on inherent patterns.
The output shows the results of the unsupervised learning process. In this case, the
algorithm might have grouped the animals into clusters based on their species (elephants,
camels, cows).
Working of Unsupervised Learning
The working of unsupervised machine learning can be explained in these steps:
2. Select an Algorithm
Choose a suitable unsupervised algorithm such as clustering like K-Means,
association rule learning like Apriori or dimensionality reduction like PCA based
on the goal.
Analyze the discovered groups, rules or features to gain insights or use them
for further tasks like visualization, anomaly detection or as input for other
models.
1. Clustering Algorithms
Clustering is an unsupervised machine learning technique that groups unlabeled data into
clusters based on similarity. Its goal is to discover patterns or relationships within the data
without any prior knowledge of categories or labels.
K-means Clustering: Groups data into K clusters based on how close the points are
to each other.
Hierarchical Clustering: Creates clusters by building a tree step-by-step, either
merging or splitting groups.
Density-Based Clustering (DBSCAN): Finds clusters in dense areas and treats
scattered points as noise.
Mean-Shift Clustering: Discovers clusters by moving points toward the most
crowded areas.
Spectral Clustering: Groups data by analyzing connections between points using
graphs.
3. Dimensionality Reduction
Dimensionality reduction is the process of decreasing the number of features or variables
in a dataset while retaining as much of the original information as possible. This technique
helps simplify complex data making it easier to analyze and visualize. It also improves the
efficiency and performance of machine learning algorithms by reducing noise and
computational cost.
It reduces the dataset’s feature space from many dimensions to fewer, more
meaningful ones.
Helps focus on the most important traits or patterns in the data.
Commonly used to improve model speed and reduce overfitting.
Advantages
No need for labeled data: Works with raw, unlabeled data hence saving time and
effort on data annotation.
Discovers hidden patterns: Finds natural groupings and structures that might be
missed by humans.
Handles complex and large datasets: Effective for high-dimensional or vast
amounts of data.
Useful for anomaly detection: Can identify outliers and unusual data points
without prior examples.
Challenges
Here are the key challenges of unsupervised learning:
Noisy Data: Outliers and noise can distort patterns and reduce the effectiveness of
algorithms.
Overfitting Risk: Overfitting can occur when models capture noise instead of
meaningful patterns in the data.
Limited Guidance: The absence of labels restricts the ability to guide the algorithm
toward specific outcomes.
Cluster Interpretability: Results such as clusters may lack clear meaning or
alignment with real-world categories.
Clustering in Machine Learning
Clustering is an unsupervised machine learning technique that groups similar data points
together into clusters based on their characteristics, without using any labeled data. The
objective is to ensure that data points within the same cluster are more similar to each
other than to those in different clusters, enabling the discovery of natural groupings and
hidden patterns in complex datasets.
Goal: Discover the natural grouping or structure in unlabeled data without
predefined categories.
How: Data points are assigned to clusters based on similarity or distance measures.
Similarity Measures: Can include Euclidean distance, cosine similarity or other
metrics depending on data type and clustering method.
Output: Each group is assigned a cluster ID, representing shared
characteristics within the cluster.
For example, if we have customer purchase data, clustering can group customers with
similar shopping habits. These clusters can then be used for targeted marketing,
personalized recommendations or customer segmentation.
Types of Clustering
1. Hard Clustering: In hard clustering, each data point strictly belongs to exactly one
cluster, no overlap is allowed. This approach assigns a clear membership, making it easier
to interpret and use for definitive segmentation tasks.
Example: If clustering customer data into 2 segments, each customer belongs fully
to either Cluster 1 or Cluster 2 without partial memberships.
Use cases: Market segmentation, customer grouping, document clustering.
Limitations: Cannot represent ambiguity or overlap between groups; boundaries
are crisp.
2. Soft Clustering: Soft clustering assigns each data point a probability or degree of
membership to multiple clusters simultaneously, allowing data points to partially belong
to several groups.
Example: A data point may have a 70% membership in Cluster 1 and 30% in Cluster
2, reflecting uncertainty or overlap in group characteristics.
Use cases: Situations with overlapping class boundaries, fuzzy categories like
customer personas or medical diagnosis.
Benefits: Captures ambiguity in data, models gradual transitions between clusters.
Let's see an example to see the difference between the hard and soft clustering using a
distribution,
4. Distribution-based Clustering
5. Fuzzy Clustering
Fuzzy clustering extends traditional methods by allowing each data point to belong to
multiple clusters with varying degrees of membership. This approach captures ambiguity
and soft boundaries in data and is particularly useful when the clusters overlap or
boundaries are not clear-cut.
Algorithm:
Fuzzy C-Means: Similar to K-means but with fuzzy memberships updated
iteratively.
Pros:
Models data ambiguity explicitly.
Useful for complex or imprecise data.
Cons:
Choosing fuzziness parameter can be tricky.
Computational overhead compared to hard clustering.
Use Cases
Customer Segmentation: Grouping customers based on behavior or demographics
for targeted marketing and personalized services.
Anomaly Detection: Identifying outliers or fraudulent activities in finance, network
security and sensor data.
Image Segmentation: Dividing images into meaningful parts for object detection,
medical diagnostics or computer vision tasks.
Recommendation Systems: Clustering user preferences to recommend movies,
products or content tailored to different groups.
Market Basket Analysis: Discovering products frequently bought together to
optimize store layouts and promotions.
Association Rule Mining
Association rules are a fundamental concept used to find relationships, correlations or
patterns within large sets of data items. They describe how often itemsets occur together
in transactions and express implications of the form:
X→Y
Where X and Y are disjoint sets of items. This rule suggests that when items in X appear,
items in Y 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
{Bread,Butter}→{Milk}
indicates that customers who buy bread and butter also tend to buy milk.
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:
Example Transaction Data
Transaction ID Items
1 Bread, Milk
{Milk,Diaper}→{Beer}
Market-Based Analysis
Medical Diagnosis
Census Data
1) Market-Basket Analysis
In most supermarkets, data is collected using barcode scanners. This database is called the
“market basket” database. It contains a large number of past transaction records. Every
record contains the name of all the items each customer purchases in one transaction. From
this data, the stores come to know the inclination and choices of items of the customers.
And according to this information, they decide the store layout and optimize the cataloging
of different items.
A single record contains a list of all the items purchased by a customer in a single
transaction. Knowing which groups are inclined toward which set of items allows these
stores to adjust the store layout and catalog to place them optimally next to one another.
2) Medical Diagnosis
Association rules in medical diagnosis can help physicians diagnose and treat patients.
Diagnosis is a difficult process with many potential errors that can lead to unreliable results.
You can use relational association rule mining to determine the likelihood of illness based on
various factors and symptoms. This application can be further expanded using some
learning techniques on the basis of symptoms and their relationships in accordance with
diseases.
3) Census Data
The concept of Association Rule Mining is also used in dealing with the massive amount of
census data. If properly aligned, this information can be used in planning efficient public
services and businesses.
Apriori Algorithm
Eclat Algorithm
FP-Growth Algorithm
1) Apriori Algorithm
It delivers by characteristic the foremost frequent individual things within the information
and increasing them to larger and bigger item sets as long as those item sets seem ofttimes
enough within the information.
The common itemsets ensured by apriori also are accustomed make sure association rules
that highlight trends within the information. It counts the support of item sets employing a
breadth-first search strategy and a candidate generation perform that takes advantage of
the downward closure property of support.
2) Eclat Algorithm
Eclat denotes equivalence class transformation. The set intersection was supported by its
depth-first search formula. It’s applicable for each successive and parallel execution with
spot-magnifying properties. This can be the associate formula for frequent pattern mining
supported by the item set lattice’s depth-first search cross.
This algorithm is also called a recurring pattern. The FP growth formula is used for locating
frequent item sets terribly dealings data but not for candidate generation.
This was primarily designed to compress the database that provides frequent sets and then
divides the compressed data into conditional database sets.
This conditional database is associated with a frequent set. Each database then undergoes
the process of data mining.
FP-tree construction
Extract frequently used itemsets