Learn practical skills, build real-world projects, and advance your career

Image Classification using Logistic Regression in PyTorch

Part 3 of "PyTorch: Zero to GANs"

This post is the third in a series of tutorials on building deep learning models with PyTorch, an open source neural networks library. Check out the full series:

  1. PyTorch Basics: Tensors & Gradients
  2. Linear Regression & Gradient Descent
  3. Image Classfication using Logistic Regression
  4. Training Deep Neural Networks on a GPU
  5. Image Classification using Convolutional Neural Networks
  6. Data Augmentation, Regularization and ResNets
  7. Generating Images using Generative Adverserial Networks

In this tutorial, we'll use our existing knowledge of PyTorch and linear regression to solve a very different kind of problem: image classification. We'll use the famous MNIST Handwritten Digits Database as our training dataset. It consists of 28px by 28px grayscale images of handwritten digits (0 to 9), along with labels for each image indicating which digit it represents. Here are some sample images from the dataset:

mnist-sample

System setup

This tutorial takes a code-first approach towards learning PyTorch, and you should try to follow along by running and experimenting with the code yourself. The easiest way to start executing this notebook is to click the "Run" button at the top of this page, and select "Run on Kaggle". This will run the notebook on Kaggle, a free online service for running Jupyter notebooks (you might need to create an account).

Running on your computer locally

(Skip this if you're running on Kaggle) To run this notebook locally, clone this notebook, install the required dependencies using conda, and start Jupyter by running the following commands on the terminal / Conda prompt:

pip install jovian --upgrade # Install the jovian library jovian clone aakashns/03-logistic-regression # Download notebook & dependencies cd 03-logistic-regression # Enter the created directory conda create -n 03-logistic-regression python=3.8 # Create an environment conda activate 03-logistic-regression # Activate virtual env jupyter notebook # Start Jupyter

You can find the notebook_id by cliking the Clone button at the top of this page on Jovian. For a more detailed explanation of the above steps, check out the System setup section in the first notebook.

Exploring the Data

We begin by importing torch and torchvision. torchvision contains some utilities for working with image data. It also contains helper classes to automatically download and import popular datasets like MNIST.

# Uncomment and run the commands below if imports fail
# !conda install numpy pytorch torchvision cpuonly -c pytorch -y
# !pip install matplotlib --upgrade --quiet