PyTorch Tutorial: How to Develop Deep Learning Models with Python

Predictive modeling with deep learning is a skill that modern developers need to know.

PyTorch is the premier open-source deep learning framework developed and maintained by Facebook.

At its core, PyTorch is a mathematical library that allows you to perform efficient computation and automatic differentiation on graph-based models.

Achieving this directly is challenging, although thankfully, the modern PyTorch API provides classes and idioms that allow you to easily develop a suite of deep learning models.

In this tutorial, you will discover a step-by-step guide to developing deep learning models in PyTorch.

After completing this tutorial, you will know:Let’s get started.

PyTorch Tutorial – How to Develop Deep Learning ModelsPhoto by Dimitry B.

, some rights reserved.

The focus of this tutorial is on using the PyTorch API for common deep learning model development tasks; we will not be diving into the math and theory of deep learning.

For that, I recommend starting with this excellent book.

The best way to learn deep learning in python is by doing.

Dive in.

You can circle back for more theory later.

I have designed each code example to use best practices and to be standalone so that you can copy and paste it directly into your project and adapt it to your specific needs.

This will give you a massive head start over trying to figure out the API from official documentation alone.

It is a large tutorial, and as such, it is divided into three parts; they are:Work through this tutorial.

It will take you 60 minutes, max!You do not need to understand everything (at least not right now).

Your goal is to run through the tutorial end-to-end and get a result.

You do not need to understand everything on the first pass.

List down your questions as you go.

Make heavy use of the API documentation to learn about all of the functions that you’re using.

You do not need to know the math first.

Math is a compact way of describing how algorithms work, specifically tools from linear algebra, probability, and calculus.

These are not the only tools that you can use to learn how algorithms work.

You can also use code and explore algorithm behavior with different inputs and outputs.

Knowing the math will not tell you what algorithm to choose or how to best configure it.

You can only discover that through carefully controlled experiments.

You do not need to know how the algorithms work.

It is important to know about the limitations and how to configure deep learning algorithms.

But learning about algorithms can come later.

You need to build up this algorithm knowledge slowly over a long period of time.

Today, start by getting comfortable with the platform.

You do not need to be a Python programmer.

The syntax of the Python language can be intuitive if you are new to it.

Just like other languages, focus on function calls (e.

g.

function()) and assignments (e.

g.

a = “b”).

This will get you most of the way.

You are a developer; you know how to pick up the basics of a language really fast.

Just get started and dive into the details later.

You do not need to be a deep learning expert.

You can learn about the benefits and limitations of various algorithms later, and there are plenty of tutorials that you can read to brush up on the steps of a deep learning project.

In this section, you will discover what PyTorch is, how to install it, and how to confirm that it is installed correctly.

PyTorch is an open-source Python library for deep learning developed and maintained by Facebook.

The project started in 2016 and quickly became a popular framework among developers and researchers.

Torch (Torch7) is an open-source project for deep learning written in C and generally used via the Lua interface.

It was a precursor project to PyTorch and is no longer actively developed.

PyTorch includes “Torch” in the name, acknowledging the prior torch library with the “Py” prefix indicating the Python focus of the new project.

The PyTorch API is simple and flexible, making it a favorite for academics and researchers in the development of new deep learning models and applications.

The extensive use has led to many extensions for specific applications (such as text, computer vision, and audio data), and may pre-trained models that can be used directly.

As such, it may be the most popular library used by academics.

The flexibility of PyTorch comes at the cost of ease of use, especially for beginners, as compared to simpler interfaces like Keras.

The choice to use PyTorch instead of Keras gives up some ease of use, a slightly steeper learning curve, and more code for more flexibility, and perhaps a more vibrant academic community.

Before installing PyTorch, ensure that you have Python installed, such as Python 3.

6 or higher.

If you don’t have Python installed, you can install it using Anaconda.

This tutorial will show you how:There are many ways to install the PyTorch open-source deep learning library.

The most common, and perhaps simplest, way to install PyTorch on your workstation is by using pip.

For example, on the command line, you can type:Perhaps the most popular application of deep learning is for computer vision, and the PyTorch computer vision package is called “torchvision.

”Installing torchvision is also highly recommended and it can be installed as follows:If you prefer to use an installation method more specific to your platform or package manager, you can see a complete list of installation instructions here:There is no need to set up the GPU now.

All examples in this tutorial will work just fine on a modern CPU.

If you want to configure PyTorch for your GPU, you can do that after completing this tutorial.

Don’t get distracted!Once PyTorch is installed, it is important to confirm that the library was installed successfully and that you can start using it.

Don’t skip this step.

If PyTorch is not installed correctly or raises an error on this step, you won’t be able to run the examples later.

Create a new file called versions.

py and copy and paste the following code into the file.

Save the file, then open your command line and change directory to where you saved the file.

Then type:You should then see output like the following:This confirms that PyTorch is installed correctly and that we are all using the same version.

This also shows you how to run a Python script from the command line.

I recommend running all code from the command line in this manner, and not from a notebook or an IDE.

In this section, you will discover the life-cycle for a deep learning model and the PyTorch API that you can use to define models.

A model has a life-cycle, and this very simple knowledge provides the backbone for both modeling a dataset and understanding the PyTorch API.

The five steps in the life-cycle are as follows:Let’s take a closer look at each step in turn.

Note: There are many ways to achieve each of these steps using the PyTorch API, although I have aimed to show you the simplest, or most common, or most idiomatic.

If you discover a better approach, let me know in the comments below.

The first step is to load and prepare your data.

Neural network models require numerical input data and numerical output data.

You can use standard Python libraries to load and prepare tabular data, like CSV files.

For example, Pandas can be used to load your CSV file, and tools from scikit-learn can be used to encode categorical data, such as class labels.

PyTorch provides the Dataset class that you can extend and customize to load your dataset.

For example, the constructor of your dataset object can load your data file (e.

g.

a CSV file).

You can then override the __len__() function that can be used to get the length of the dataset (number of rows or samples), and the __getitem__() function that is used to get a specific sample by index.

When loading your dataset, you can also perform any required transforms, such as scaling or encoding.

A skeleton of a custom Dataset class is provided below.

Once loaded, PyTorch provides the DataLoader class to navigate a Dataset instance during the training and evaluation of your model.

A DataLoader instance can be created for the training dataset, test dataset, and even a validation dataset.

The random_split() function can be used to split a dataset into train and test sets.

Once split, a selection of rows from the Dataset can be provided to a DataLoader, along with the batch size and whether the data should be shuffled every epoch.

For example, we can define a DataLoader by passing in a selected sample of rows in the dataset.

Once defined, a DataLoader can be enumerated, yielding one batch worth of samples each iteration.

The next step is to define a model.

The idiom for defining a model in PyTorch involves defining a class that extends the Module class.

The constructor of your class defines the layers of the model and the forward() function is the override that defines how to forward propagate input through the defined layers of the model.

Many layers are available, such as Linear for fully connected layers, Conv2d for convolutional layers, and MaxPool2d for pooling layers.

Activation functions can also be defined as layers, such as ReLU, Softmax, and Sigmoid.

Below is an example of a simple MLP model with one layer.

The weights of a given layer can also be initialized after the layer is defined in the constructor.

Common examples include the Xavier and He weight initialization schemes.

For example:The training process requires that you define a loss function and an optimization algorithm.

Common loss functions include the following:For more on loss functions generally, see the tutorial:Stochastic gradient descent is used for optimization, and the standard algorithm is provided by the SGD class, although other versions of the algorithm are available, such as Adam.

Training the model involves enumerating the DataLoader for the training dataset.

First, a loop is required for the number of training epochs.

Then an inner loop is required for the mini-batches for stochastic gradient descent.

Each update to the model involves the same general pattern comprised of:For example:Once the model is fit, it can be evaluated on the test dataset.

This can be achieved by using the DataLoader for the test dataset and collecting the predictions for the test set, then comparing the predictions to the expected values of the test set and calculating a performance metric.

A fit model can be used to make a prediction on new data.

For example, you might have a single image or a single row of data and want to make a prediction.

This requires that you wrap the data in a PyTorch Tensor data structure.

A Tensor is just the PyTorch version of a NumPy array for holding data.

It also allows you to perform the automatic differentiation tasks in the model graph, like calling backward() when training the model.

The prediction too will be a Tensor, although you can retrieve the NumPy array by detaching the Tensor from the automatic differentiation graph and calling the NumPy function.

Now that we are familiar with the PyTorch API at a high-level and the model life-cycle, let’s look at how we can develop some standard deep learning models from scratch.

In this section, you will discover how to develop, evaluate, and make predictions with standard deep learning models, including Multilayer Perceptrons (MLP) and Convolutional Neural Networks (CNN).

A Multilayer Perceptron model, or MLP for short, is a standard fully connected neural network model.

It is comprised of layers of nodes where each node is connected to all outputs from the previous layer and the output of each node is connected to all inputs for nodes in the next layer.

An MLP is a model with one or more fully connected layers.

This model is appropriate for tabular data, that is data as it looks in a table or spreadsheet with one column for each variable and one row for each variable.

There are three predictive modeling problems you may want to explore with an MLP; they are binary classification, multiclass classification, and regression.

Let’s fit a model on a real dataset for each of these cases.

Note: The models in this section are effective, but not optimized.

See if you can improve their performance.

Post your findings in the comments below.

We will use the Ionosphere binary (two class) classification dataset to demonstrate an MLP for binary classification.

This dataset involves predicting whether there is a structure in the atmosphere or not given radar returns.

The dataset will be downloaded automatically using Pandas, but you can learn more about it here.

We will use a LabelEncoder to encode the string labels to integer values 0 and 1.

The model will be fit on 67 percent of the data, and the remaining 33 percent will be used for evaluation, split using the train_test_split() function.

It is a good practice to use ‘relu‘ activation with a ‘He Uniform‘ weight initialization.

This combination goes a long way to overcome the problem of vanishing gradients when training deep neural network models.

For more on ReLU, see the tutorial:The model predicts the probability of class 1 and uses the sigmoid activation function.

The model is optimized using stochastic gradient descent and seeks to minimize the binary cross-entropy loss.

The complete example is listed below.

Running the example first reports the shape of the train and test datasets, then fits the model and evaluates it on the test dataset.

Finally, a prediction is made for a single row of data.

Your specific results will vary given the stochastic nature of the learning algorithm.

Try running the example a few times.

What result did you get? Can you change the model to do better? Post your findings to the comments below.

In this case, we can see that the model achieved a classification accuracy of about 94 percent and then predicted a probability of 0.

99 that the one row of data belong to class 1.

We will use the Iris flowers multiclass classification dataset to demonstrate an MLP for multiclass classification.

This problem involves predicting the species of iris flower given measures of the flower.

The dataset will be downloaded automatically using Pandas, but you can learn more about it here.

Given that it is a multiclass classification, the model must have one node for each class in the output layer and use the softmax activation function.

The loss function is the cross entropy, which is appropriate for integer encoded class labels (e.

g.

0 for one class, 1 for the next class, etc.

).

The complete example of fitting and evaluating an MLP on the iris flowers dataset is listed below.

Running the example first reports the shape of the train and test datasets, then fits the model and evaluates it on the test dataset.

Finally, a prediction is made for a single row of data.

Your specific results will vary given the stochastic nature of the learning algorithm.

Try running the example a few times.

What result did you get? Can you change the model to do better? Post your findings to the comments below.

In this case, we can see that the model achieved a classification accuracy of about 98 percent and then predicted a probability of a row of data belonging to each class, although class 0 has the highest probability.

We will use the Boston housing regression dataset to demonstrate an MLP for regression predictive modeling.

This problem involves predicting house value based on properties of the house and neighborhood.

The dataset will be downloaded automatically using Pandas, but you can learn more about it here.

This is a regression problem that involves predicting a single numeric value.

As such, the output layer has a single node and uses the default or linear activation function (no activation function).

The mean squared error (mse) loss is minimized when fitting the model.

Recall that this is regression, not classification; therefore, we cannot calculate classification accuracy.

For more on this, see the tutorial:The complete example of fitting and evaluating an MLP on the Boston housing dataset is listed below.

Running the example first reports the shape of the train and test datasets, then fits the model and evaluates it on the test dataset.

Finally, a prediction is made for a single row of data.

Your specific results will vary given the stochastic nature of the learning algorithm.

Try running the example a few times.

What result did you get? Can you change the model to do better? Post your findings to the comments below.

In this case, we can see that the model achieved a MSE of about 82, which is an RMSE of about nine (units are thousands of dollars).

A value of 21 is then predicted for the single example.

Convolutional Neural Networks, or CNNs for short, are a type of network designed for image input.

They are comprised of models with convolutional layers that extract features (called feature maps) and pooling layers that distill features down to the most salient elements.

CNNs are best suited to image classification tasks, although they can be used on a wide array of tasks that take images as input.

A popular image classification task is the MNIST handwritten digit classification.

It involves tens of thousands of handwritten digits that must be classified as a number between 0 and 9.

The torchvision API provides a convenience function to download and load this dataset directly.

The example below loads the dataset and plots the first few images.

Running the example loads the MNIST dataset, then summarizes the default train and test datasets.

A plot is then created showing a grid of examples of handwritten images in the training dataset.

Plot of Handwritten Digits From the MNIST datasetWe can train a CNN model to classify the images in the MNIST dataset.

Note that the images are arrays of grayscale pixel data, therefore, we must add a channel dimension to the data before we can use the images as input to the model.

It is a good idea to scale the pixel values from the default range of 0-255 to have a zero mean and a standard deviation of 1.

For more on scaling pixel values, see the tutorial:The complete example of fitting and evaluating a CNN model on the MNIST dataset is listed below.

Running the example first reports the shape of the train and test datasets, then fits the model and evaluates it on the test dataset.

Your specific results will vary given the stochastic nature of the learning algorithm.

Try running the example a few times.

What result did you get? Can you change the model to do better? Post your findings to the comments below.

In this case, we can see that the model achieved a classification accuracy of about 98 percent on the test dataset.

We can then see that the model predicted class 5 for the first image in the training set.

This section provides more resources on the topic if you are looking to go deeper.

In this tutorial, you discovered a step-by-step guide to developing deep learning models in PyTorch.

Specifically, you learned:Do you have any questions? Ask your questions in the comments below and I will do my best to answer.

with just a few lines of PythonDiscover how in my new Ebook: Deep Learning With PythonIt covers end-to-end projects on topics like: Multilayer Perceptrons, Convolutional Nets and Recurrent Neural Nets, and more.

Skip the Academics.

Just Results.

.

Leave a Reply