Logistic Regression in Machine Learning
Last Updated :
20 Jun, 2024
Logistic regression is a supervised machine learning algorithm used for classification tasks where the goal is to predict the probability that an instance belongs to a given class or not. Logistic regression is a statistical algorithm which analyze the relationship between two data factors. The article explores the fundamentals of logistic regression, it’s types and implementations.
What is Logistic Regression?
Logistic regression is used for binary classification where we use sigmoid function, that takes input as independent variables and produces a probability value between 0 and 1.
For example, we have two classes Class 0 and Class 1 if the value of the logistic function for an input is greater than 0.5 (threshold value) then it belongs to Class 1 otherwise it belongs to Class 0. It’s referred to as regression because it is the extension of linear regression but is mainly used for classification problems.
Key Points:
- Logistic regression predicts the output of a categorical dependent variable. Therefore, the outcome must be a categorical or discrete value.
- It can be either Yes or No, 0 or 1, true or False, etc. but instead of giving the exact value as 0 and 1, it gives the probabilistic values which lie between 0 and 1.
- In Logistic regression, instead of fitting a regression line, we fit an “S” shaped logistic function, which predicts two maximum values (0 or 1).
Logistic Function – Sigmoid Function
- The sigmoid function is a mathematical function used to map the predicted values to probabilities.
- It maps any real value into another value within a range of 0 and 1. The value of the logistic regression must be between 0 and 1, which cannot go beyond this limit, so it forms a curve like the “S” form.
- The S-form curve is called the Sigmoid function or the logistic function.
- In logistic regression, we use the concept of the threshold value, which defines the probability of either 0 or 1. Such as values above the threshold value tends to 1, and a value below the threshold values tends to 0.
Types of Logistic Regression
On the basis of the categories, Logistic Regression can be classified into three types:
- Binomial: In binomial Logistic regression, there can be only two possible types of the dependent variables, such as 0 or 1, Pass or Fail, etc.
- Multinomial: In multinomial Logistic regression, there can be 3 or more possible unordered types of the dependent variable, such as “cat”, “dogs”, or “sheep”
- Ordinal: In ordinal Logistic regression, there can be 3 or more possible ordered types of dependent variables, such as “low”, “Medium”, or “High”.
Assumptions of Logistic Regression
We will explore the assumptions of logistic regression as understanding these assumptions is important to ensure that we are using appropriate application of the model. The assumption include:
- Independent observations: Each observation is independent of the other. meaning there is no correlation between any input variables.
- Binary dependent variables: It takes the assumption that the dependent variable must be binary or dichotomous, meaning it can take only two values. For more than two categories SoftMax functions are used.
- Linearity relationship between independent variables and log odds: The relationship between the independent variables and the log odds of the dependent variable should be linear.
- No outliers: There should be no outliers in the dataset.
- Large sample size: The sample size is sufficiently large
Terminologies involved in Logistic Regression
Here are some common terms involved in logistic regression:
- Independent variables: The input characteristics or predictor factors applied to the dependent variable’s predictions.
- Dependent variable: The target variable in a logistic regression model, which we are trying to predict.
- Logistic function: The formula used to represent how the independent and dependent variables relate to one another. The logistic function transforms the input variables into a probability value between 0 and 1, which represents the likelihood of the dependent variable being 1 or 0.
- Odds: It is the ratio of something occurring to something not occurring. it is different from probability as the probability is the ratio of something occurring to everything that could possibly occur.
- Log-odds: The log-odds, also known as the logit function, is the natural logarithm of the odds. In logistic regression, the log odds of the dependent variable are modeled as a linear combination of the independent variables and the intercept.
- Coefficient: The logistic regression model’s estimated parameters, show how the independent and dependent variables relate to one another.
- Intercept: A constant term in the logistic regression model, which represents the log odds when all independent variables are equal to zero.
- Maximum likelihood estimation: The method used to estimate the coefficients of the logistic regression model, which maximizes the likelihood of observing the data given the model.
How does Logistic Regression work?
The logistic regression model transforms the linear regression function continuous value output into categorical value output using a sigmoid function, which maps any real-valued set of independent variables input into a value between 0 and 1. This function is known as the logistic function.
Let the independent input features be:
[Tex]X = \begin{bmatrix} x_{11} & … & x_{1m}\\ x_{21} & … & x_{2m} \\ \vdots & \ddots & \vdots \\ x_{n1} & … & x_{nm} \end{bmatrix}[/Tex]
and the dependent variable is Y having only binary value i.e. 0 or 1.
[Tex]Y = \begin{cases} 0 & \text{ if } Class\;1 \\ 1 & \text{ if } Class\;2 \end{cases}
[/Tex]
then, apply the multi-linear function to the input variables X.
[Tex]z = \left(\sum_{i=1}^{n} w_{i}x_{i}\right) + b
[/Tex]
Here [Tex]x_i
[/Tex] is the ith observation of X, [Tex]w_i = [w_1, w_2, w_3, \cdots,w_m]
[/Tex] is the weights or Coefficient, and b is the bias term also known as intercept. simply this can be represented as the dot product of weight and bias.
[Tex]z = w\cdot X +b
[/Tex]
whatever we discussed above is the linear regression.
Sigmoid Function
Now we use the sigmoid function where the input will be z and we find the probability between 0 and 1. i.e. predicted y.
[Tex]\sigma(z) = \frac{1}{1+e^{-z}}
[/Tex]

Sigmoid function
As shown above, the figure sigmoid function converts the continuous variable data into the probability i.e. between 0 and 1.
- [Tex]\sigma(z)
[/Tex] tends towards 1 as [Tex]z\rightarrow\infty
[/Tex]
- [Tex]\sigma(z)
[/Tex] tends towards 0 as [Tex]z\rightarrow-\infty
[/Tex]
- [Tex]\sigma(z)
[/Tex] is always bounded between 0 and 1
where the probability of being a class can be measured as:
[Tex]P(y=1) = \sigma(z) \\ P(y=0) = 1-\sigma(z)
[/Tex]
Logistic Regression Equation
The odd is the ratio of something occurring to something not occurring. it is different from probability as the probability is the ratio of something occurring to everything that could possibly occur. so odd will be:
[Tex]\frac{p(x)}{1-p(x)} = e^z[/Tex]
Applying natural log on odd. then log odd will be:
[Tex]\begin{aligned}
\log \left[\frac{p(x)}{1-p(x)} \right] &= z
\\ \log \left[\frac{p(x)}{1-p(x)} \right] &= w\cdot X +b
\\ \frac{p(x)}{1-p(x)}&= e^{w\cdot X +b} \;\;\cdots\text{Exponentiate both sides}
\\ p(x) &=e^{w\cdot X +b}\cdot (1-p(x))
\\p(x) &=e^{w\cdot X +b}-e^{w\cdot X +b}\cdot p(x))
\\p(x)+e^{w\cdot X +b}\cdot p(x))&=e^{w\cdot X +b}
\\p(x)(1+e^{w\cdot X +b}) &=e^{w\cdot X +b}
\\p(x)&= \frac{e^{w\cdot X +b}}{1+e^{w\cdot X +b}}
\end{aligned}[/Tex]
then the final logistic regression equation will be:
[Tex]p(X;b,w) = \frac{e^{w\cdot X +b}}{1+e^{w\cdot X +b}} = \frac{1}{1+e^{-w\cdot X +b}}[/Tex]
Likelihood Function for Logistic Regression
The predicted probabilities will be:
- for y=1 The predicted probabilities will be: p(X;b,w) = p(x)
- for y = 0 The predicted probabilities will be: 1-p(X;b,w) = 1-p(x)
[Tex]L(b,w) = \prod_{i=1}^{n}p(x_i)^{y_i}(1-p(x_i))^{1-y_i}[/Tex]
Taking natural logs on both sides
[Tex]\begin{aligned}\log(L(b,w)) &= \sum_{i=1}^{n} y_i\log p(x_i)\;+\; (1-y_i)\log(1-p(x_i)) \\ &=\sum_{i=1}^{n} y_i\log p(x_i)+\log(1-p(x_i))-y_i\log(1-p(x_i)) \\ &=\sum_{i=1}^{n} \log(1-p(x_i)) +\sum_{i=1}^{n}y_i\log \frac{p(x_i)}{1-p(x_i} \\ &=\sum_{i=1}^{n} -\log1-e^{-(w\cdot x_i+b)} +\sum_{i=1}^{n}y_i (w\cdot x_i +b) \\ &=\sum_{i=1}^{n} -\log1+e^{w\cdot x_i+b} +\sum_{i=1}^{n}y_i (w\cdot x_i +b) \end{aligned}[/Tex]
Gradient of the log-likelihood function
To find the maximum likelihood estimates, we differentiate w.r.t w,
[Tex]\begin{aligned} \frac{\partial J(l(b,w)}{\partial w_j}&=-\sum_{i=n}^{n}\frac{1}{1+e^{w\cdot x_i+b}}e^{w\cdot x_i+b} x_{ij} +\sum_{i=1}^{n}y_{i}x_{ij} \\&=-\sum_{i=n}^{n}p(x_i;b,w)x_{ij}+\sum_{i=1}^{n}y_{i}x_{ij} \\&=\sum_{i=n}^{n}(y_i -p(x_i;b,w))x_{ij} \end{aligned}
[/Tex]
Code Implementation for Logistic Regression
Binomial Logistic regression:
Target variable can have only 2 possible types: “0” or “1” which may represent “win” vs “loss”, “pass” vs “fail”, “dead” vs “alive”, etc., in this case, sigmoid functions are used, which is already discussed above.
Importing necessary libraries based on the requirement of model. This Python code shows how to use the breast cancer dataset to implement a Logistic Regression model for classification.
Python
# import the necessary libraries
from sklearn.datasets import load_breast_cancer
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
# load the breast cancer dataset
X, y = load_breast_cancer(return_X_y=True)
# split the train and test dataset
X_train, X_test,\
y_train, y_test = train_test_split(X, y,
test_size=0.20,
random_state=23)
# LogisticRegression
clf = LogisticRegression(random_state=0)
clf.fit(X_train, y_train)
# Prediction
y_pred = clf.predict(X_test)
acc = accuracy_score(y_test, y_pred)
print("Logistic Regression model accuracy (in %):", acc*100)
Output:
Logistic Regression model accuracy (in %): 95.6140350877193
Multinomial Logistic Regression:
Target variable can have 3 or more possible types which are not ordered (i.e. types have no quantitative significance) like “disease A” vs “disease B” vs “disease C”.
In this case, the softmax function is used in place of the sigmoid function. Softmax function for K classes will be:
[Tex]\text{softmax}(z_i) =\frac{ e^{z_i}}{\sum_{j=1}^{K}e^{z_{j}}}[/Tex]
Here, K represents the number of elements in the vector z, and i, j iterates over all the elements in the vector.
Then the probability for class c will be:
[Tex]P(Y=c | \overrightarrow{X}=x) = \frac{e^{w_c \cdot x + b_c}}{\sum_{k=1}^{K}e^{w_k \cdot x + b_k}}[/Tex]
In Multinomial Logistic Regression, the output variable can have more than two possible discrete outputs. Consider the Digit Dataset.
Python
from sklearn.model_selection import train_test_split
from sklearn import datasets, linear_model, metrics
# load the digit dataset
digits = datasets.load_digits()
# defining feature matrix(X) and response vector(y)
X = digits.data
y = digits.target
# splitting X and y into training and testing sets
X_train, X_test,\
y_train, y_test = train_test_split(X, y,
test_size=0.4,
random_state=1)
# create logistic regression object
reg = linear_model.LogisticRegression()
# train the model using the training sets
reg.fit(X_train, y_train)
# making predictions on the testing set
y_pred = reg.predict(X_test)
# comparing actual response values (y_test)
# with predicted response values (y_pred)
print("Logistic Regression model accuracy(in %):",
metrics.accuracy_score(y_test, y_pred)*100)
Output:
Logistic Regression model accuracy(in %): 96.52294853963839
How to Evaluate Logistic Regression Model?
We can evaluate the logistic regression model using the following metrics:
- Accuracy: Accuracy provides the proportion of correctly classified instances.
[Tex]Accuracy = \frac{True \, Positives + True \, Negatives}{Total}
[/Tex]
- Precision: Precision focuses on the accuracy of positive predictions.
[Tex]Precision = \frac{True \, Positives }{True\, Positives + False \, Positives}
[/Tex]
- Recall (Sensitivity or True Positive Rate): Recall measures the proportion of correctly predicted positive instances among all actual positive instances.
[Tex]Recall = \frac{ True \, Positives}{True\, Positives + False \, Negatives}
[/Tex]
- F1 Score: F1 score is the harmonic mean of precision and recall.
[Tex]F1 \, Score = 2 * \frac{Precision * Recall}{Precision + Recall}
[/Tex]
- Area Under the Receiver Operating Characteristic Curve (AUC-ROC): The ROC curve plots the true positive rate against the false positive rate at various thresholds. AUC-ROC measures the area under this curve, providing an aggregate measure of a model’s performance across different classification thresholds.
- Area Under the Precision-Recall Curve (AUC-PR): Similar to AUC-ROC, AUC-PR measures the area under the precision-recall curve, providing a summary of a model’s performance across different precision-recall trade-offs.
Precision-Recall Tradeoff in Logistic Regression Threshold Setting
Logistic regression becomes a classification technique only when a decision threshold is brought into the picture. The setting of the threshold value is a very important aspect of Logistic regression and is dependent on the classification problem itself.
The decision for the value of the threshold value is majorly affected by the values of precision and recall. Ideally, we want both precision and recall being 1, but this seldom is the case.
In the case of a Precision-Recall tradeoff, we use the following arguments to decide upon the threshold:
- Low Precision/High Recall: In applications where we want to reduce the number of false negatives without necessarily reducing the number of false positives, we choose a decision value that has a low value of Precision or a high value of Recall. For example, in a cancer diagnosis application, we do not want any affected patient to be classified as not affected without giving much heed to if the patient is being wrongfully diagnosed with cancer. This is because the absence of cancer can be detected by further medical diseases, but the presence of the disease cannot be detected in an already rejected candidate.
- High Precision/Low Recall: In applications where we want to reduce the number of false positives without necessarily reducing the number of false negatives, we choose a decision value that has a high value of Precision or a low value of Recall. For example, if we are classifying customers whether they will react positively or negatively to a personalized advertisement, we want to be absolutely sure that the customer will react positively to the advertisement because otherwise, a negative reaction can cause a loss of potential sales from the customer.
Differences Between Linear and Logistic Regression
The difference between linear regression and logistic regression is that linear regression output is the continuous value that can be anything while logistic regression predicts the probability that an instance belongs to a given class or not.
Linear Regression
| Logistic Regression
|
|---|
Linear regression is used to predict the continuous dependent variable using a given set of independent variables.
| Logistic regression is used to predict the categorical dependent variable using a given set of independent variables.
|
Linear regression is used for solving regression problem.
| It is used for solving classification problems.
|
In this we predict the value of continuous variables
| In this we predict values of categorical variables
|
In this we find best fit line.
| In this we find S-Curve.
|
Least square estimation method is used for estimation of accuracy.
| Maximum likelihood estimation method is used for Estimation of accuracy.
|
The output must be continuous value, such as price, age, etc.
| Output must be categorical value such as 0 or 1, Yes or no, etc.
|
It required linear relationship between dependent and independent variables.
| It not required linear relationship.
|
There may be collinearity between the independent variables.
| There should be little to no collinearity between independent variables.
|
Logistic Regression – Frequently Asked Questions (FAQs)
What is Logistic Regression in Machine Learning?
Logistic regression is a statistical method for developing machine learning models with binary dependent variables, i.e. binary. Logistic regression is a statistical technique used to describe data and the relationship between one dependent variable and one or more independent variables.
What are the three types of logistic regression?
Logistic regression is classified into three types: binary, multinomial, and ordinal. They differ in execution as well as theory. Binary regression is concerned with two possible outcomes: yes or no. Multinomial logistic regression is used when there are three or more values.
Why logistic regression is used for classification problem?
Logistic regression is easier to implement, interpret, and train. It classifies unknown records very quickly. When the dataset is linearly separable, it performs well. Model coefficients can be interpreted as indicators of feature importance.
What distinguishes Logistic Regression from Linear Regression?
While Linear Regression is used to predict continuous outcomes, Logistic Regression is used to predict the likelihood of an observation falling into a specific category. Logistic Regression employs an S-shaped logistic function to map predicted values between 0 and 1.
What role does the logistic function play in Logistic Regression?
Logistic Regression relies on the logistic function to convert the output into a probability score. This score represents the probability that an observation belongs to a particular class. The S-shaped curve assists in thresholding and categorising data into binary outcomes.
Similar Reads
Machine Learning Algorithms
Machine learning algorithms are essentially sets of instructions that allow computers to learn from data, make predictions, and improve their performance over time without being explicitly programmed. Machine learning algorithms are broadly categorized into three types: Supervised Learning: Algorith
9 min read
Top 15 Machine Learning Algorithms Every Data Scientist Should Know in 2024
Machine Learning (ML) Algorithms are the backbone of everything from Netflix recommendations to fraud detection in financial institutions. These algorithms form the core of intelligent systems, empowering organizations to analyze patterns, predict outcomes, and automate decision-making processes. Wi
15 min read
Linear Model Regression
Ordinary Least Squares (OLS) using statsmodels
In this article, we will use Python's statsmodels module to implement Ordinary Least Squares ( OLS ) method of linear regression. Introduction : A linear regression model establishes the relation between a dependent variable( y ) and at least one independent variable( x ) as : [Tex] \hat{y}=b_1x+b_0
4 min read
Linear Regression (Python Implementation)
This article discusses the basics of linear regression and its implementation in the Python programming language. Linear regression is a statistical method for modeling relationships between a dependent variable with a given set of independent variables. Note: In this article, we refer to dependent
15+ min read
ML | Multiple Linear Regression using Python
Linear Regression: It is the basic and commonly used type for predictive analysis. It is a statistical approach to modeling the relationship between a dependent variable and a given set of independent variables. These are of two types: Simple linear RegressionMultiple Linear Regression Let's Discuss
6 min read
Polynomial Regression ( From Scratch using Python )
Prerequisites Linear RegressionGradient DescentIntroductionLinear Regression finds the correlation between the dependent variable ( or target variable ) and independent variables ( or features ). In short, it is a linear model to fit the data linearly. But it fails to fit and catch the pattern in no
5 min read
Implementation of Bayesian Regression
Linear regression is a popular regression approach in machine learning. Linear regression is based on the assumption that the underlying data is normally distributed and that all relevant predictor variables have a linear relationship with the outcome. But In the real world, this is not always poss
13 min read
How to Perform Quantile Regression in Python
In this article, we are going to see how to perform quantile regression in Python. Linear regression is defined as the statistical method that constructs a relationship between a dependent variable and an independent variable as per the given set of variables. While performing linear regression we a
4 min read
Isotonic Regression in Scikit Learn
Isotonic regression is a regression technique in which the predictor variable is monotonically related to the target variable. This means that as the value of the predictor variable increases, the value of the target variable either increases or decreases in a consistent, non-oscillating manner. Mat
6 min read
Stepwise Regression in Python
Stepwise regression is a method of fitting a regression model by iteratively adding or removing variables. It is used to build a model that is accurate and parsimonious, meaning that it has the smallest number of variables that can explain the data. There are two main types of stepwise regression: F
6 min read
Least Angle Regression (LARS)
Regression is a supervised machine learning task that can predict continuous values (real numbers), as compared to classification, that can predict categorical or discrete values. Before we begin, if you are a beginner, I highly recommend this article. Least Angle Regression (LARS) is an algorithm u
3 min read
Linear Model Classification
K-Nearest Neighbors (KNN)
ML | Stochastic Gradient Descent (SGD)
Gradient Descent is an iterative optimization process that searches for an objective function's optimum value (Minimum/Maximum). It is one of the most used methods for changing a model's parameters in order to reduce a cost function in machine learning projects. The primary goal of gradient descen
10 min read
Generative Model
ML | Naive Bayes Scratch Implementation using Python
A key concept in probability theory, the Bayes theorem, provides the foundation for the probabilistic classifier known as Naive Bayes. It is a simple yet powerful algorithm that has risen in popularity because of its understanding, simplicity, and ease of implementation. Naive Bayes Algorithm is a p
8 min read
Applying Multinomial Naive Bayes to NLP Problems
Multinomial Naive Bayes (MNB) is a popular machine learning algorithm for text classification problems in Natural Language Processing (NLP). It is particularly useful for problems that involve text data with discrete features such as word frequency counts. MNB works on the principle of Bayes theorem
7 min read
Gaussian Process Classification (GPC) on the XOR Dataset in Scikit Learn
Gaussian process classification (GPC) is a probabilistic approach to classification that models the conditional distribution of the class labels given the feature values. In GPC, the data is assumed to be generated by a Gaussian process, which is a stochastic process that is characterized by its mea
4 min read
Gaussian Discriminant Analysis
Gaussian Discriminant Analysis (GDA) is a supervised learning algorithm used for classification tasks in machine learning. It is a variant of the Linear Discriminant Analysis (LDA) algorithm that relaxes the assumption that the covariance matrices of the different classes are equal. GDA works by ass
7 min read
Quadratic Discriminant Analysis
Linear Discriminant Analysis Now, Let's consider a classification problem represented by a Bayes Probability distribution P(Y=k | X=x), LDA does it differently by trying to model the distribution of X given the predictors class (I.e. the value of Y) P(X=x| Y=k): [Tex]P(Y=k | X=x) = \frac{P(X=x | Y=k
4 min read
Basic Understanding of Bayesian Belief Networks
Bayesian Belief Network is a graphical representation of different probabilistic relationships among random variables in a particular set. It is a classifier with no dependency on attributes i.e it is condition independent. Due to its feature of joint probability, the probability in Bayesian Belief
4 min read
Hidden Markov Model in Machine learning
A statistical model called a Hidden Markov Model (HMM) is used to describe systems with changing unobservable states over time. It is predicated on the idea that there is an underlying process with concealed states, each of which has a known result. Probabilities for switching between concealed stat
11 min read
Time Series Forecasting
Components of Time Series Data
Time series data is a sequence of data points recorded or collected at regular time intervals. It is a type of data that tracks the evolution of a variable over time, such as sales, stock prices, temperature, etc. The regular time intervals can be daily, weekly, monthly, quarterly, or annually, and
11 min read
AutoCorrelation
Autocorrelation is a fundamental concept in time series analysis. Autocorrelation is a statistical concept that assesses the degree of correlation between the values of variable at different time points. The article aims to discuss the fundamentals and working of Autocorrelation. Table of Content Wh
10 min read
How to Check if Time Series Data is Stationary with Python?
Time series data are generally characterized by their temporal nature. This temporal nature adds a trend or seasonality to the data that makes it compatible for time series analysis and forecasting. Time-series data is said to be stationary if it doesn't change with time or if they don't have a temp
8 min read
How to Perform an Augmented Dickey-Fuller Test in R
Augmented Dickey-Fuller Test: It is a common test in statistics and is used to check whether a given time series is at rest. A given time series can be called stationary or at rest if it doesn't have any trend and depicts a constant variance over time and follows autocorrelation structure over a per
3 min read
How to calculate MOVING AVERAGE in a Pandas DataFrame?
Calculating the moving average in a Pandas DataFrame is used for smoothing time series data and identifying trends. The moving average, also known as the rolling mean, helps reduce noise and highlight significant patterns by averaging data points over a specific window. In Pandas, this can be achiev
7 min read
Exponential Smoothing in R Programming
The Exponential Smoothing is a technique for smoothing data of time series using an exponential window function. It is a rule of the thumb method. Unlike simple moving average, over time the exponential functions assign exponentially decreasing weights. Here the greater weights are placed on the rec
15+ min read
Python | ARIMA Model for Time Series Forecasting
A Time Series is defined as a series of data points indexed in time order. The time order can be daily, monthly, or even yearly. Given below is an example of a Time Series that illustrates the number of passengers of an airline per month from the year 1949 to 1960. Time Series Forecasting Time Serie
5 min read
Supervised Dimensionality Reduction Technique
Metrics for Classification & Regression Algorithms
Python | Mean Squared Error
The Mean Squared Error (MSE) or Mean Squared Deviation (MSD) of an estimator measures the average of error squares i.e. the average squared difference between the estimated values and true value. It is a risk function, corresponding to the expected value of the squared error loss. It is always non –
2 min read
Root-Mean-Square Error in R Programming
In this article, we will cover the theory behind RMSE, explain its significance, and provide detailed steps on how to compute RMSE in R programming using different approaches using R Programming Language. What is RMSE?Root mean squared error (RMSE) is the square root of the mean of the square of all
4 min read
How to Calculate Mean Absolute Error in Python?
When building machine learning models, our aim is to make predictions as accurately as possible. However, not all models are perfect some predictions will surely deviate from the actual values. To evaluate how well a model performs, we rely on error metrics. One widely used metric for measuring pred
4 min read
R-squared in Regression Analysis in Machine Learning
The most important thing we do after making any model is evaluating the model. We have different evaluation matrices for evaluating the model. However, the choice of evaluation matrix to use for evaluating the model depends upon the type of problem we are solving whether it's a regression, classific
4 min read
ML | Adjusted R-Square in Regression Analysis
Prerequisite: Linear Regression, R-square in Regression Why Adjusted-R Square Test: R-square test is used to determine the goodness of fit in regression analysis. Goodness of fit implies how better regression model is fitted to the data points. More is the value of r-square near to 1, better is the
3 min read
Understanding the Confusion Matrix in Machine Learning
Machine learning models are increasingly used in various applications to classify data into different categories. However, evaluating the performance of these models is crucial to ensure their accuracy and reliability. One essential tool in this evaluation process is the confusion matrix. In this ar
11 min read
Techniques To Evaluate Accuracy of Classifier in Data Mining
Pre-requisites: Data Mining Data Mining can be referred to as knowledge mining from data, knowledge extraction, data/pattern analysis, data archaeology, and data dredging. In this article, we will see techniques to evaluate the accuracy of classifiers. HoldOutIn the holdout method, the largest datas
3 min read
Precision Handling in Python
Python in its definition allows handling the precision of floating-point numbers in several ways using different functions. Most of them are defined under the "math" module. In this article, we will use high-precision calculations in Python with Decimal in Python. Example Input: x = 2.4Output: Integ
6 min read
Precision-Recall Curve | ML
There are numerous ways to evaluate the performance of a classifier. In this article, we introduce the Precision-Recall Curve and further examine the difference between two popular performance reporting methods: Precision-Recall (PR) Curve and Receiver Operating Characteristic (ROC) Curve. ROC Curve
10 min read
Calculate Sensitivity, Specificity and Predictive Values in CARET
R programming is used for predictive data analysis we all know that. In R the "CARET" package is used to train and evaluate machine learning models. The 'caret' package (short for Classification and Regression Training) is a comprehensive and powerful tool that provides a unified interface and a wid
9 min read
How to Calculate F1 Score in R?
In this article, we will be looking at the approach to calculate F1 Score using the various packages and their various functionalities in the R language. F1 Score The F-score or F-measure is a measure of a test's accuracy. It is calculated from the precision and recall of the test, where the precisi
5 min read
AUC ROC Curve in Machine Learning
One important aspect of Machine Learning is model evaluation. You need to have some mechanism to evaluate your model. This is where these performance metrics come into the picture they give us a sense of how good a model is. If you are familiar with some of the basics of Machine Learning then you mu
15+ min read
Probability Calibration Curve in Scikit Learn
Probability Calibration is a technique used to convert the output scores from a binary classifier into probabilities to correlate with the actual probabilities of the target class. In this article, we will discuss probability calibration curves and how to plot them using Scikit-learn. Probability Ca
6 min read
Calibration Curves
Generally, for any classification problem, we predict the class value that has the highest probability of being the true class label. However, sometimes, we want to predict the probabilities of a data instance belonging to each class label. For example, say we are building a model to classify fruits
3 min read
Probability Calibration of Classifiers in Scikit Learn
In this article, we will explore the concepts and techniques related to the probability calibration of classifiers in the context of machine learning. Classifiers in machine learning frequently provide probabilities indicating how confident they are in their predictions. However, the probabilities m
4 min read
Cross Validation Technique
Optimization Technique
Gradient Descent in Linear Regression
We know that in any machine learning project our main aim relies on how good our project accuracy is or how much our model prediction differs from the actual data point. Based on the difference between model prediction and actual data points we try to find the parameters of the model which give bett
9 min read
ML | Stochastic Gradient Descent (SGD)
Gradient Descent is an iterative optimization process that searches for an objective function's optimum value (Minimum/Maximum). It is one of the most used methods for changing a model's parameters in order to reduce a cost function in machine learning projects. The primary goal of gradient descen
10 min read
ML | Mini-Batch Gradient Descent with Python
In machine learning, gradient descent is an optimization technique used for computing the model parameters (coefficients and bias) for algorithms like linear regression, logistic regression, neural networks, etc. In this technique, we repeatedly iterate through the training set and update the model
5 min read
ML | Momentum-based Gradient Optimizer introduction
Gradient Descent is an optimization technique used in Machine Learning frameworks to train different models. The training process consists of an objective function (or the error function), which determines the error a Machine Learning model has on a given dataset. While training, the parameters of t
5 min read
Find root of a number using Newton's method
Given an integer N and a tolerance level L, the task is to find the square root of that number using Newton's Method.Examples: Input: N = 16, L = 0.0001 Output: 4 42 = 16Input: N = 327, L = 0.00001 Output: 18.0831 Newton's Method: Let N be any number then the square root of N can be given by the for
7 min read
Hill Climbing in Artificial Intelligence
Hill climbing is a widely used optimization algorithm in Artificial Intelligence (AI) that helps find the best possible solution to a given problem. As part of the local search algorithms family, it is often applied to optimization problems where the goal is to identify the optimal solution from a s
12 min read
What is TABU Search?
Tabu search (TS) is an iterative neighborhood search algorithm, where the neighborhood changes dynamically. Tabu search enhances local search by avoiding points in the search space which are already visited. By avoiding already visited points, loops in search space are avoided and local optima can b
11 min read
Clustering
Clustering in Machine Learning
In real world, not every data we work upon has a target variable. This kind of data cannot be analyzed using supervised learning algorithms. We need the help of unsupervised algorithms. One of the most popular type of analysis under unsupervised learning is Cluster analysis. When the goal is to grou
12 min read
K means Clustering - Introduction
K-Means Clustering is an Unsupervised Machine Learning algorithm, which groups the unlabeled dataset into different clusters. The article aims to explore the fundamentals and working of k mean clustering along with the implementation. Table of Content What is K-means Clustering?What is the objective
9 min read
ML | K-means++ Algorithm
Prerequisite: K-means Clustering – IntroductionDrawback of standard K-means algorithm:One disadvantage of the K-means algorithm is that it is sensitive to the initialization of the centroids or the mean points. So, if a centroid is initialized to be a "far-off" point, it might just end up with no po
5 min read
K-Mode Clustering in Python
K-mode clustering is an unsupervised machine-learning technique used to group a set of data objects into a specified number of clusters, based on their categorical attributes. The algorithm is called "K-Mode" because it uses modes (i.e. the most frequent values) instead of means or medians to repres
8 min read
Fuzzy C-means Clustering in MATLAB
Fuzzy C-means (FCM) is a method of clustering that allows points to be more than one cluster. The (FCM) is a kind of data clustering technique in which the data set is grouped into N numbers of clusters with every data point corresponding to each cluster on the basis. which is to differentiate the d
4 min read
Gaussian Mixture Model
Suppose there are a set of data points that need to be grouped into several parts or clusters based on their similarity. In Machine Learning, this is known as Clustering. There are several methods available for clustering: K Means ClusteringHierarchical ClusteringGaussian Mixture Models In this arti
6 min read
ML | Expectation-Maximization Algorithm
In real-world machine learning applications, it is common to have many relevant features, but only a subset of them may be observable. When dealing with variables that are sometimes observable and sometimes not, it is indeed possible to utilize the instances when that variable is visible or observed
8 min read
Hierarchical Clustering in Machine Learning
In data mining and statistics, hierarchical clustering analysis is a method of clustering analysis that seeks to build a hierarchy of clusters i.e. tree-type structure based on the hierarchy. In machine learning, clustering is the unsupervised learning technique that groups the data based on similar
7 min read
Implementing Agglomerative Clustering using Sklearn
Prerequisites: Agglomerative Clustering Agglomerative Clustering is one of the most common hierarchical clustering techniques. Dataset - Credit Card Dataset. Assumption: The clustering technique assumes that each data point is similar enough to the other data points that the data at the starting can
3 min read
Difference Between Agglomerative clustering and Divisive clustering
Hierarchical clustering is a popular unsupervised machine learning technique used to group similar data points into clusters based on their similarity or dissimilarity. It is called "hierarchical" because it creates a tree-like hierarchy of clusters, where each node represents a cluster that can be
5 min read
Affinity Propagation in ML | To find the number of clusters
Affinity Propagation creates clusters by sending messages between data points until convergence. Unlike clustering algorithms such as k-means or k-medoids, affinity propagation does not require the number of clusters to be determined or estimated before running the algorithm, for this purpose the tw
3 min read
DBSCAN Clustering in ML | Density based clustering
Clustering analysis or simply Clustering is basically an Unsupervised learning method that divides the data points into a number of specific batches or groups, such that the data points in the same groups have similar properties and data points in different groups have different properties in some s
7 min read
ML | OPTICS Clustering Explanation
Prerequisites: DBSCAN Clustering OPTICS Clustering stands for Ordering Points To Identify Cluster Structure. It draws inspiration from the DBSCAN clustering algorithm. It adds two more terms to the concepts of DBSCAN clustering. OPTICS (Ordering Points To Identify the Clustering Structure) is a dens
7 min read
Dimensionality Reduction Technique
Principal Component Analysis(PCA)
As the number of features or dimensions in a dataset increases, the amount of data required to obtain a statistically significant result increases exponentially. This can lead to issues such as overfitting, increased computation time, and reduced accuracy of machine learning models this is known as
14 min read
ML | T-distributed Stochastic Neighbor Embedding (t-SNE) Algorithm
T-distributed Stochastic Neighbor Embedding (t-SNE) is a nonlinear dimensionality reduction technique well-suited for embedding high-dimensional data for visualization in a low-dimensional space of two or three dimensions. What is Dimensionality Reduction? Dimensionality Reduction represents n-dimen
5 min read
Non-Negative Matrix Factorization
Prerequisite : Low Rank Approximation Non-Negative Matrix Factorization: Nonnegative Matrix Factorization is a matrix factorization method where we constrain the matrices to be nonnegative. In order to understand NMF, we should clarify the underlying intuition between matrix factorization. For a mat
3 min read
ML | Independent Component Analysis
Independent Component Analysis is a technique used to separate mixed signals into their independent sources. The application of ICA ranges from audio and image processing to biomedical signal analysis. The article discusses about the fundamentals of ICA. What is Independent Component Analysis? Indep
7 min read
Factor Analysis | Data Analysis
Factor analysis is a statistical method used to analyze the relationships among a set of observed variables by explaining the correlations or covariances between them in terms of a smaller number of unobserved variables called factors. Table of Content What is Factor Analysis?What does Factor mean i
13 min read
Latent Dirichlet Allocation
Topic Modeling: Topic modeling is a way of abstract modeling to discover the abstract 'topics' that occur in the collections of documents. The idea is that we will perform unsupervised classification on different documents, which find some natural groups in topics. We can answer the following questi
8 min read
Swiss Roll Reduction with LLE in Scikit Learn
This article discusses the concept of dimensionality reduction, specifically using the Swiss Roll dataset and the Locally Linear Embedding (LLE) algorithm. The article discusses the process involved in performing Swiss Roll reduction with LLE, including the steps of loading and preprocessing the dat
9 min read
Latent Semantic Analysis
Latent Semantic Analysis is a natural language processing method that uses the statistical approach to identify the association among the words in a document. LSA deals with the following kind of issue: Example: mobile, phone, cell phone, telephone are all similar but if we pose a query like “The
2 min read
Asynchronous Advantage Actor Critic (A3C) algorithm
The Asynchronous Advantage Actor Critic (A3C) algorithm is one of the newest algorithms to be developed under the field of Deep Reinforcement Learning Algorithms. This algorithm was developed by Google's DeepMind which is the Artificial Intelligence division of Google. This algorithm was first menti
3 min read