The Wayback Machine - https://web.archive.org/web/20240824063630/https://www.geeksforgeeks.org/identifying-handwritten-digits-using-logistic-regression-pytorch/
Open In App

Identifying handwritten digits using Logistic Regression in PyTorch

Last Updated : 12 Aug, 2021
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Logistic Regression is a very commonly used statistical method that allows us to predict a binary output from a set of independent variables. The various properties of logistic regression and its Python implementation have been covered in this article previously. Now, we shall find out how to implement this in PyTorch, a very popular deep learning library that is being developed by Facebook.
Now, we shall see how to classify handwritten digits from the MNIST dataset using Logistic Regression in PyTorch. Firstly, you will need to install PyTorch into your Python environment. The easiest way to do this is to use the pip or conda tool. Visit pytorch.org and install the version of your Python interpreter and the package manager that you would like to use.
With PyTorch installed, let us now have a look at the code. Write the three lines given below to import the required library functions and objects.

Python3




import torch
import torch.nn as nn
import torchvision.datasets as dsets
import torchvision.transforms as transforms
from torch.autograd import Variable


Here, the torch.nn module contains the code required for the model, torchvision.datasets contain the MNIST dataset. It contains the dataset of handwritten digits that we shall be using here. The torchvision.transforms module contains various methods to transform objects into others. Here, we shall be using it to transform from images to PyTorch tensors. Also, the torch.autograd module contains the Variable class amongst others, which will be used by us while defining our tensors.
Next, we shall download and load the dataset to memory.

Python3




# MNIST Dataset (Images and Labels)
train_dataset = dsets.MNIST(root ='./data', 
                            train = True, 
                            transform = transforms.ToTensor(),
                            download = True)
  
test_dataset = dsets.MNIST(root ='./data', 
                           train = False, 
                           transform = transforms.ToTensor())
  
# Dataset Loader (Input Pipeline)
train_loader = torch.utils.data.DataLoader(dataset = train_dataset, 
                                           batch_size = batch_size, 
                                           shuffle = True)
  
test_loader = torch.utils.data.DataLoader(dataset = test_dataset, 
                                          batch_size = batch_size, 
                                          shuffle = False)


Now, we shall define our hyperparameters.

Python3




# Hyper Parameters 
input_size = 784
num_classes = 10
num_epochs = 5
batch_size = 100
learning_rate = 0.001


In our dataset, the image size is 28*28. Thus, our input size is 784. Also, 10 digits are present in this and hence, we can have 10 different outputs. Thus, we set num_classes as 10. Also, we shall train five times on the entire dataset. Finally, we will train in small batches of 100 images each so as to prevent the crashing of the program due to memory overflow.
After this, we shall be defining our model as below. Here, we shall initialize our model as a subclass of torch.nn.Module and then define the forward pass. In the code that we are writing, the softmax is internally calculated during each forward pass and hence we do not need to specify it inside the forward() function.

Python3




class LogisticRegression(nn.Module):
    def __init__(self, input_size, num_classes):
        super(LogisticRegression, self).__init__()
        self.linear = nn.Linear(input_size, num_classes)
  
    def forward(self, x):
        out = self.linear(x)
        return out


Having defined our class, now we instantiate an object for the same.

Python3




model = LogisticRegression(input_size, num_classes)


Next, we set our loss function and the optimizer. Here, we shall be using the cross-entropy loss and for the optimizer, we shall be using the stochastic gradient descent algorithm with a learning rate of 0.001 as defined in the hyperparameter above.

Python3




criterion = nn.CrossEntropyLoss()
optimizer = torch.optim.SGD(model.parameters(), lr = learning_rate)


Now, we shall start the training. Here, we shall be performing the following tasks:

  1. Reset all gradients to 0.
  2. Make a forward pass.
  3. Calculate the loss.
  4. Perform backpropagation.
  5. Update all weights.

Python3




# Training the Model
for epoch in range(num_epochs):
    for i, (images, labels) in enumerate(train_loader):
        images = Variable(images.view(-1, 28 * 28))
        labels = Variable(labels)
  
        # Forward + Backward + Optimize
        optimizer.zero_grad()
        outputs = model(images)
        loss = criterion(outputs, labels)
        loss.backward()
        optimizer.step()
  
        if (i + 1) % 100 == 0:
            print('Epoch: [% d/% d], Step: [% d/% d], Loss: %.4f'
                  % (epoch + 1, num_epochs, i + 1,
                     len(train_dataset) // batch_size, loss.data[0]))


Finally, we shall be testing out the model by using the following code.

Python3




# Test the Model
correct = 0
total = 0
for images, labels in test_loader:
    images = Variable(images.view(-1, 28 * 28))
    outputs = model(images)
    _, predicted = torch.max(outputs.data, 1)
    total += labels.size(0)
    correct += (predicted == labels).sum()
  
print('Accuracy of the model on the 10000 test images: % d %%' % (
            100 * correct / total))


Assuming that you performed all steps correctly, you will get an accuracy of 82%, which is far off from today’s state-of-the-art model, which uses a special type of neural network architecture. For your reference, you can find the entire code for this article below:

Python3




import torch
import torch.nn as nn
import torchvision.datasets as dsets
import torchvision.transforms as transforms
from torch.autograd import Variable
  
  
# MNIST Dataset (Images and Labels)
train_dataset = dsets.MNIST(root ='./data',
                            train = True,
                            transform = transforms.ToTensor(),
                            download = True)
  
test_dataset = dsets.MNIST(root ='./data',
                           train = False,
                           transform = transforms.ToTensor())
  
# Dataset Loader (Input Pipeline)
train_loader = torch.utils.data.DataLoader(dataset = train_dataset,
                                           batch_size = batch_size,
                                           shuffle = True)
  
test_loader = torch.utils.data.DataLoader(dataset = test_dataset,
                                          batch_size = batch_size,
                                          shuffle = False)
  
# Hyper Parameters
input_size = 784
num_classes = 10
num_epochs = 5
batch_size = 100
learning_rate = 0.001
  
# Model
class LogisticRegression(nn.Module):
    def __init__(self, input_size, num_classes):
        super(LogisticRegression, self).__init__()
        self.linear = nn.Linear(input_size, num_classes)
  
    def forward(self, x):
        out = self.linear(x)
        return out
  
  
model = LogisticRegression(input_size, num_classes)
  
# Loss and Optimizer
# Softmax is internally computed.
# Set parameters to be updated.
criterion = nn.CrossEntropyLoss()
optimizer = torch.optim.SGD(model.parameters(), lr = learning_rate)
  
# Training the Model
for epoch in range(num_epochs):
    for i, (images, labels) in enumerate(train_loader):
        images = Variable(images.view(-1, 28 * 28))
        labels = Variable(labels)
  
        # Forward + Backward + Optimize
        optimizer.zero_grad()
        outputs = model(images)
        loss = criterion(outputs, labels)
        loss.backward()
        optimizer.step()
  
        if (i + 1) % 100 == 0:
            print('Epoch: [% d/% d], Step: [% d/% d], Loss: %.4f'
                  % (epoch + 1, num_epochs, i + 1,
                     len(train_dataset) // batch_size, loss.data[0]))
  
# Test the Model
correct = 0
total = 0
for images, labels in test_loader:
    images = Variable(images.view(-1, 28 * 28))
    outputs = model(images)
    _, predicted = torch.max(outputs.data, 1)
    total += labels.size(0)
    correct += (predicted == labels).sum()
  
print('Accuracy of the model on the 10000 test images: % d %%' % (
            100 * correct / total))


References:

 



Previous Article
Next Article

Similar Reads

Logistic Regression on MNIST with PyTorch
Logistic Regression Logistic Regression is also known as Binary Classification is one of the most popular Machine Learning Algorithms. It comes under Supervised Learning Classification Algorithms. It is used to predict the probability of the target label. By binary classification, it means that the model predicts the label either 0 or 1. The target
4 min read
Multinomial Logistic Regression with PyTorch
Logistic regression is a popular machine learning algorithm used for binary classification tasks. It models the probability of the output variable (also known as the dependent variable) given the input variables (also known as the independent variables). It is a linear algorithm that applies a logistic function to the output of a linear regression
11 min read
ML | Linear Regression vs Logistic Regression
Linear Regression is a machine learning algorithm based on supervised regression algorithm. Regression models a target prediction value based on independent variables. It is mostly used for finding out the relationship between variables and forecasting. Different regression models differ based on – the kind of relationship between the dependent and
3 min read
K-Means clustering on the handwritten digits data using Scikit Learn in Python
K - means clustering is an unsupervised algorithm that is used in customer segmentation applications. In this algorithm, we try to form clusters within our datasets that are closely related to each other in a high-dimensional space. In this article, we will see how to use the k means algorithm to identify the clusters of the digits. Load the Datase
5 min read
OCR of Handwritten digits | OpenCV
OCR which stands for Optical Character Recognition is a computer vision technique used to identify the different types of handwritten digits that are used in common mathematics. To perform OCR in OpenCV we will use the KNN algorithm which detects the nearest k neighbors of a particular data point and then classifies that data point based on the cla
2 min read
Recognizing HandWritten Digits in Scikit Learn
Scikit learn is one of the most widely used machine learning libraries in the machine learning community the reason behind that is the ease of code and availability of approximately all functionalities which a machine learning developer will need to build a machine learning model. In this article, we will learn how can we use sklearn to train an ML
7 min read
Python | Classify Handwritten Digits with Tensorflow
Classifying handwritten digits is the basic problem of the machine learning and can be solved in many ways here we will implement them by using TensorFlowUsing a Linear Classifier Algorithm with tf.contrib.learn linear classifier achieves the classification of handwritten digits by making a choice based on the value of a linear combination of the f
4 min read
Logistic Regression using Statsmodels
Prerequisite: Understanding Logistic RegressionLogistic regression is the type of regression analysis used to find the probability of a certain event occurring. It is the best suited type of regression for cases where we have a categorical dependent variable which can take only discrete values. The dataset : In this article, we will predict whether
4 min read
Implementation of Logistic Regression from Scratch using Python
Introduction:Logistic Regression is a supervised learning algorithm that is used when the target variable is categorical. Hypothetical function h(x) of linear regression predicts unbounded values. But in the case of Logistic Regression, where the target variable is categorical we have to strict the range of predicted values. Consider a classificati
5 min read
Placement prediction using Logistic Regression
Prerequisites: Understanding Logistic Regression, Logistic Regression using Python In this article, we are going to discuss how to predict the placement status of a student based on various student attributes using Logistic regression algorithm. Placements hold great importance for students and educational institutions. It helps a student to build
4 min read
Logistic Regression using PySpark Python
In this tutorial series, we are going to cover Logistic Regression using Pyspark. Logistic Regression is one of the basic ways to perform classification (don’t be confused by the word “regression”). Logistic Regression is a classification method. Some examples of classification are: Spam detectionDisease DiagnosisLoading Dataframe We will be using
3 min read
Logistic Regression using Python
A basic machine learning approach that is frequently used for binary classification tasks is called logistic regression. Though its name suggests otherwise, it uses the sigmoid function to simulate the likelihood of an instance falling into a specific class, producing values between 0 and 1. Logistic regression, with its emphasis on interpretabilit
8 min read
Text Classification using Logistic Regression
Text classification is the process of automatically assigning labels or categories to pieces of text. This has tons of applications, like sorting emails into spam or not-spam, figuring out if a product review is positive or negative, or even identifying the topic of a news article. In this article, we will see How logistic regression is used for te
5 min read
ML | Heart Disease Prediction Using Logistic Regression
World Health Organization has estimated that four out of five cardiovascular disease (CVD) deaths are due to heart attacks. This whole research intends to pinpoint the ratio of patients who possess a good chance of being affected by CVD and also to predict the overall risk using Logistic Regression. What is Logistic Regression?Logistic Regression i
4 min read
ML | Kaggle Breast Cancer Wisconsin Diagnosis using Logistic Regression
Dataset:It is given by Kaggle from UCI Machine Learning Repository, in one of its challenge. It is a dataset of Breast Cancer patients with Malignant and Benign tumor. Logistic Regression is used to predict whether the given patient is having Malignant or Benign tumor based on the attributes in the given dataset. Code : Loading Libraries C/C++ Code
5 min read
ML | Logistic Regression using Tensorflow
Prerequisites: Understanding Logistic Regression and TensorFlow. Brief Summary of Logistic Regression: Logistic Regression is Classification algorithm commonly used in Machine Learning. It allows categorizing data into discrete classes by learning the relationship from a given set of labeled data. It learns a linear relationship from the given data
6 min read
ML | Why Logistic Regression in Classification ?
Using Linear Regression, all predictions >= 0.5 can be considered as 1 and rest all < 0.5 can be considered as 0. But then the question arises why classification can't be performed using it? Problem - Suppose we are classifying a mail as spam or not spam and our output is y, it can be 0(spam) or 1(not spam). In case of Linear Regression, hθ(x
3 min read
ML | Logistic Regression v/s Decision Tree Classification
Logistic Regression and Decision Tree classification are two of the most popular and basic classification algorithms being used today. None of the algorithms is better than the other and one's superior performance is often credited to the nature of the data being worked upon. We can compare the two algorithms on different categories - CriteriaLogis
2 min read
Logistic Regression in R Programming
Logistic regression in R Programming is a classification algorithm used to find the probability of event success and event failure. Logistic regression is used when the dependent variable is binary(0/1, True/False, Yes/No) in nature. The logit function is used as a link function in a binomial distribution. A binary outcome variable's probability ca
8 min read
Differentiate between Support Vector Machine and Logistic Regression
Logistic Regression: It is a classification model which is used to predict the odds in favour of a particular event. The odds ratio represents the positive event which we want to predict, for example, how likely a sample has breast cancer/ how likely is it for an individual to become diabetic in future. It used the sigmoid function to convert an in
4 min read
Role of Log Odds in Logistic Regression
Prerequisite : Log Odds, Logistic Regression NOTE: It is advised to go through the prerequisite topics to have a clear understanding of this article. Log odds play an important role in logistic regression as it converts the LR model from probability based to a likelihood based model. Both probability and log odds have their own set of properties, h
4 min read
Logistic Regression Vs Random Forest Classifier
A statistical technique called logistic regression is used to solve problems involving binary classification, in which the objective is to predict a binary result (such as yes/no, true/false, or 0/1) based on one or more predictor variables (also known as independent variables, features, or predictors). Based on the values of the predictor variable
7 min read
What is the default threshold in Sklearn logistic regression?
Logistic regression is a popular machine-learning algorithm used for classification problems. It is commonly used in various applications such as marketing, finance, healthcare, etc. One of the critical parameters in logistic regression is the threshold, which determines the class label of the prediction. In this article, we will discuss the defaul
8 min read
Cost function in Logistic Regression in Machine Learning
Logistic Regression is one of the simplest classification algorithms we learn while exploring machine learning algorithms. In this article, we will explore cross-entropy, a cost function used for logistic regression. What is Logistic Regression?Logistic Regression is a statistical method used for binary classification. Despite its name, it is emplo
10 min read
Naive Bayes vs Logistic Regression in Machine Learning
In the vast landscape of machine learning, selecting the most appropriate algorithm for a classification task. Two widely-used algorithms in this context are Naive Bayes and Logistic Regression. Before delving into the detailed comparison, let's establish a clear understanding of each algorithm. Table of Content Naive BayesLogistic RegressionNaive
5 min read
Logistic Regression vs K Nearest Neighbors in Machine Learning
Machine learning algorithms play a crucial role in training the data and decision-making processes. Logistic Regression and K Nearest Neighbors (KNN) are two popular algorithms in machine learning used for classification tasks. In this article, we'll delve into the concepts of Logistic Regression and KNN and understand their functions and their dif
4 min read
Weighted Logistic Regression for Imbalanced Dataset
In real-world datasets, it's common to encounter class imbalance, where one class significantly outnumbers the other(s). This class imbalance poses challenges for machine learning models, particularly for classification tasks, as models tend to be biased towards the majority class, leading to suboptimal performance. What are imbalanced datasets?Imb
6 min read
How to interpret odds ratios in logistic regression
Logistic regression is a statistical method used to model the relationship between a binary outcome and predictor variables. This article provides an overview of logistic regression, including its assumptions and how to interpret regression coefficients. Assumptions of logistic regressionBinary Outcome: Logistic regression assumes that the outcome
12 min read
Outlier Detection in Logistic Regression
Outliers, data points that deviate significantly from the rest, can significantly impact the performance of logistic regression models. In this article we will explore various techniques for detecting and handling outliers in Logistic regression. What are Outliers?An outlier is an observation that falls far outside the typical range of other data p
8 min read
Logistic Regression and the Feature Scaling Ensemble
Logistic Regression is a widely used classification algorithm in machine learning. However, to enhance its performance further specially when dealing with features of different scales, employing feature scaling ensemble techniques becomes imperative. In this guide, we will dive depth into logistic regression, its significance and how feature sealin
9 min read
Article Tags :
Practice Tags :