SALE! Use code blackfriday for 40% off everything!
Hurry, sale ends soon! Click to see the full catalog.

# PyTorch Tutorial: How to Develop Deep Learning Models with Python

Last Updated on August 27, 2020

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:

• The difference between Torch and PyTorch and how to install and confirm PyTorch is working.
• The five-step life-cycle of PyTorch models and how to define, fit, and evaluate models.
• How to develop PyTorch deep learning models for regression, classification, and predictive modeling tasks.

Let’s get started. PyTorch Tutorial – How to Develop Deep Learning Models
Photo by Dimitry B., some rights reserved.

## PyTorch Tutorial Overview

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:

1. How to Install PyTorch
1. What Are Torch and PyTorch?
2. How to Install PyTorch
3. How to Confirm PyTorch Is Installed
2. PyTorch Deep Learning Model Life-Cycle
1. Step 1: Prepare the Data
2. Step 2: Define the Model
3. Step 3: Train the Model
4. Step 4: Evaluate the Model
5. Step 5: Make Predictions
3. How to Develop PyTorch Deep Learning Models
1. How to Develop an MLP for Binary Classification
2. How to Develop an MLP for Multiclass Classification
3. How to Develop an MLP for Regression
4. How to Develop a CNN for Image Classification

### You Can Do Deep Learning in Python!

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.

## 1. How to Install PyTorch

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

### 1.1. What Are Torch and PyTorch?

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.

### 1.2. How to Install PyTorch

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!

### 1.3. How to Confirm PyTorch Is Installed

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.

## 2. PyTorch Deep Learning Model Life-Cycle

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:

• 1. Prepare the Data.
• 2. Define the Model.
• 3. Train the Model.
• 4. Evaluate the Model.
• 5. Make Predictions.

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.

### Step 1: Prepare the 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.

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.

### Step 2: Define the Model

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:

### Step 3: Train the Model

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

Common loss functions include the following:

• BCELoss: Binary cross-entropy loss for binary classification.
• CrossEntropyLoss: Categorical cross-entropy loss for multi-class classification.
• MSELoss: Mean squared loss for regression.

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:

• Clearing the last error gradient.
• A forward pass of the input through the model.
• Calculating the loss for the model output.
• Backpropagating the error through the model.
• Update the model in an effort to reduce loss.

For example:

### Step 4: Evaluate the model

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.

### Step 5: Make predictions

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.

## 3. How to Develop PyTorch Deep Learning Models

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.

### 3.1. How to Develop an MLP for Binary Classification

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.

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.

Note: Your results may vary given the stochastic nature of the algorithm or evaluation procedure, or differences in numerical precision. Consider running the example a few times and compare the average outcome.

What result did you get?
Can you change the model to do better?

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.

### 3.2. How to Develop an MLP for Multiclass Classification

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.

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.

Note: Your results may vary given the stochastic nature of the algorithm or evaluation procedure, or differences in numerical precision. Consider running the example a few times and compare the average outcome.

What result did you get?
Can you change the model to do better?

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.

### 3.3. How to Develop an MLP for Regression

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.

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.

Note: Your results may vary given the stochastic nature of the algorithm or evaluation procedure, or differences in numerical precision. Consider running the example a few times and compare the average outcome.

What result did you get?
Can you change the model to do better?

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.

### 3.4. How to Develop a CNN for Image Classification

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 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 dataset

We 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.

Note: Your results may vary given the stochastic nature of the algorithm or evaluation procedure, or differences in numerical precision. Consider running the example a few times and compare the average outcome.

What result did you get?
Can you change the model to do better?

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.

## Summary

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

Specifically, you learned:

• The difference between Torch and PyTorch and how to install and confirm PyTorch is working.
• The five-step life-cycle of PyTorch models and how to define, fit, and evaluate models.
• How to develop PyTorch deep learning models for regression, classification, and predictive modeling tasks.

Do you have any questions?

## Develop Deep Learning Projects with Python! #### What If You Could Develop A Network in Minutes

...with just a few lines of Python

Discover how in my new Ebook:
Deep Learning With Python

It covers end-to-end projects on topics like:
Multilayer PerceptronsConvolutional Nets and Recurrent Neural Nets, and more...

### 84 Responses to PyTorch Tutorial: How to Develop Deep Learning Models with Python

1. Kashif March 23, 2020 at 5:39 am #

Nice tutorial. May I ask if you are migrating from Keras to Pytorch and any solid grounds for doing so? I know its a research favourite but what else.

• Jason Brownlee March 23, 2020 at 6:16 am #

No plan to migrate to pytorch at this stage, I’m just showing how to get started.

• Hoson March 27, 2020 at 6:40 pm #

Keras API is still looking simpler than Pytorch API, but Tensorflow’s version 2 is relatively more powerful and production-ready than Pytorch. Any reason behind in creating this tutorial or any plan/reason in switching to Pytorch?

I did evaluate Pytorch more than a year ago but did not switch finally. Another one was Julia but also sticking with TF and Keras until now, especially after having version 2 eager mode.

• Jason Brownlee March 28, 2020 at 6:15 am #

Agreed, Keras API is better for beginners by a mile. No plans to switch.

2. Anon March 24, 2020 at 3:10 am #

Sir a simple program I am running binary classification using DNN with pytorch. A discussion also going on in pytorch forum which is not yet solved. Can you help out I will post the link

• Jason Brownlee March 24, 2020 at 6:09 am #

See the MLP example above for a “DNN with pytorch”.

3. Vince March 24, 2020 at 8:27 am #

Thank you for your tutorial. It is very nice. However, did you have any tutorial like this for tensorflow? Or from other source (book, web…)?
Thank you!

• Jason Brownlee March 24, 2020 at 8:31 am #
4. Vince March 24, 2020 at 9:33 am #

My meant is: did you have any tutorial like this for only tensorflow without keras?
Furthermore, I really like “prepare dataset” in your pytorch tutorial because I can be easy to customize my data set. However, this tutorial is not. It is instead of function in library that is difficult to customize. Can you explain why you do that?
Thank you!

5. Benjamin March 25, 2020 at 2:51 am #

Great tutorial.

I am hoping you’ll continue this series and cover more examples in Pytorch

• Jason Brownlee March 25, 2020 at 6:36 am #

Thanks for the suggestion.

No plans at this stage.

6. ZCoder March 25, 2020 at 7:28 am #

Jason,

This is an amazing tutorial. Your end-to-end examples with very clear explanations take the prize! Thank you very much!

My favorite tutorial on your site is “How to Use the Keras Functional API for Deep Learning”, especially its part 5 “Multiple Input and Output Models”. That Keras tutorial helped me to develop far more sophisticated models.

While you’ve mentioned that you have no current plans to expand on PyTorch tutorials, it would be fantastic to see a similar PyTorch tutorial covering different multiple input/multiple output cases sometime in the future.

Thanks!

• Jason Brownlee March 25, 2020 at 11:24 am #

Thanks!

Great suggestion.

7. Kyla March 26, 2020 at 5:48 am #

Thanks as always Jason! I was looking forward to a good pytorch tutorial. this nailed it.

• Jason Brownlee March 26, 2020 at 8:02 am #

Thanks!

8. Abraham March 26, 2020 at 7:01 pm #

Hi Jason,
Pytorch may provide some flexibility wrt Keras in deep learning issues according to my recent experiences i.e You can have deep insight what the model does and enhance somehow your coding skills. We look forward to new pytorch tutorials.

• Jason Brownlee March 27, 2020 at 6:08 am #

Thanks.

9. Ashutosh March 27, 2020 at 5:58 am #

This is an excellent tutorial. Thanks, Jason for sharing.

• Jason Brownlee March 27, 2020 at 6:21 am #

Thank you!

10. Anthony The Koala March 27, 2020 at 1:46 pm #

Dear Dr Jason,
For those with difficulties with the installation of Pytorch, I present another way of installing

When you thought that by pipping pytorch and its cuda and non-cuda variations seemed to be ok, you may get errors on either installation or DLL errors when trying to import from within python.

The following installation was straightforward and produced no errors.

If you one is having trouble with the PyTorch Installation particularly when you get errors during the installation, try the following:

Thank you,
Anthony of Sydney

• Jason Brownlee March 28, 2020 at 6:09 am #

Thanks for sharing!

• Sean benhur November 2, 2020 at 12:39 am #

This is an excellent tutorial..Please make more on Pytorch,

• Jason Brownlee November 2, 2020 at 6:41 am #

Thanks!

11. asko April 2, 2020 at 1:17 am #

Thank you very much,

I still do not understand why we extend Dataset when we create a custom dataset class, I know Dataset is an abstract class but what will happen if we will not extend it ??

Thank you

• Jason Brownlee April 2, 2020 at 6:00 am #

This is the convention in the PyTorch library.

What happens if you don’t follow it. Probably your code won’t work – e.g. your are not meeting the expectations of the library.

12. Sushant Gautam April 4, 2020 at 3:55 am #

This is a very well-detailed explanation Tutorial. Your Tutorial always helps me to learn more. Thanks, Jasons for Sharing.

• Jason Brownlee April 4, 2020 at 6:26 am #

I’m happy it helps!

13. Ando Ki April 27, 2020 at 12:55 pm #

It is a nice tutorial and thank you.
Could you enlighten me to how to prepare a new image to feed ‘forward(x)’?
Thanks again.
Ando

• Ando Ki April 27, 2020 at 10:37 pm #

The previous question is about MNIST and the question was how to prepare input image to feed forward(x) from PNG or JPG image.

• Jason Brownlee April 28, 2020 at 6:45 am #

Load the image as per normal, then scale pixels/resize in an identical manner as the training dataset.

• Jason Brownlee April 28, 2020 at 6:39 am #

You’re welcome.

New images must be prepared in an identical way as the training data.

14. Xu Zhang April 29, 2020 at 8:41 am #

Thank you so much for your great post.
Recently, more and more new models are written in Pytorch. However, I am familiar with Keras. Do you have any ideas to transfer pytorch models to keras models? Many thanks

• Jason Brownlee April 29, 2020 at 12:05 pm #

You’re welcome.

No, not offhand, sorry.

15. Akshay Tiwari May 10, 2020 at 12:31 am #

As always very useful tutorial Jason.Thanks.
Am I not wrong in assuming that pytorch is more useful for people who are looking for complete control over their model i.e researchers.Having said that, keras does almost all my stuff.

• Jason Brownlee May 10, 2020 at 6:12 am #

You’re welcome.

Perhaps. Both tensorflow and pytorch give complete control, but for those interested in control, pytorch appears more popular – e.g. academics/researchers developing new methods rather than engineers solving problems.

Just my observation, not a truth.

16. Tuan May 14, 2020 at 12:35 am #

Thank you for a great post. I am just curious: what do the numbers that go with MLP mean? For example MLP(13) and MLP(1). I see that you use different numbers in different examples.

• Jason Brownlee May 14, 2020 at 5:52 am #

The number of inputs to the model.

17. Tenchu May 23, 2020 at 2:06 am #

Thank you so much… wonderful post. I learned a lot

• Jason Brownlee May 23, 2020 at 6:25 am #

Thanks!

18. Hoang May 26, 2020 at 12:54 pm #

Hello, I ran the regression code on my side, but I noticed the output is always the same for any sets of inputs. Did anyone flag this bug yet?

Ex: Try running
row = [0.00632,18.00,2.310,0,0.5380,6.5750,65.20,4.0900,1,296.0,15.30,396.90,4.98]
yhat = predict(row, model)
print(‘Predicted: %.3f’ % yhat)

row = [1,30,2.310,0,2,6.5750,80,4.0900,1,296.0,20,500,4.98]
yhat = predict(row, model)
print(‘Predicted: %.3f’ % yhat)

They always are the same answer…

• Jason Brownlee May 26, 2020 at 1:23 pm #

• Hoang May 26, 2020 at 9:13 pm #

Actually, I took the as is from your site, and just ran it. If I expand the predictions to:
row = [0.00632,18.00,2.310,0,0.5380,6.5750,65.20,4.0900,1,296.0,15.30,396.90,4.98]
yhat = predict(row, model)
print(‘Predicted: %.3f’ % yhat) # should be near 24.00

row2 = [0.17505,0.00,5.960,0,0.4990,5.9660,30.20,3.8473,5,279.0,19.20,393.43,10.13]
yhat2 = predict(row2, model)
print(‘Predicted: %.3f’ % yhat2) #should be near 24.70

row3 = [2.77974,0.00,19.580,0,0.8710,4.9030,97.80,1.3459,5,403.0,14.70,396.90,29.29]
yhat3 = predict(row3, model)
print(‘Predicted: %.3f’ % yhat3) #should be near 11.80

row4 = [0.07503,33.00,2.180,0,0.4720,7.4200,71.90,3.0992,7,222.0,18.40,396.90,6.47]
yhat4 = predict(row4, model)
print(‘Predicted: %.3f’ % yhat4) #should be near 33.40

I get:

339 167
MSE: 85.617, RMSE: 9.253
Predicted: 22.318
Predicted: 22.318
Predicted: 22.318
Predicted: 22.318

Can you retest it on your side see if you get the same results? Again, I ran the same code with the same dataset of housing prices.

Thanks!

• Carlos May 27, 2020 at 5:20 am #

The SGD optimizer was getting stuck at a local minimum, changing it for the Adam optimizer works a lot better and you’ll see a noticeable response to different inputs.

• Hoang May 27, 2020 at 5:39 am #

Thank you so much Carlos! Check out his blog here: http://cgoliver.com/blog

• Jason Brownlee May 27, 2020 at 8:04 am #

Great blog!

• Jason Brownlee May 27, 2020 at 8:03 am #

Well done!

• Jason Brownlee May 27, 2020 at 7:49 am #

Yes, I see the same problem.

Perhaps the model has over fit the training data, perhaps try changing the model architecture or learning hyperparameters?

E.g. smaller learning rate or fewer epochs.

• Carlos May 27, 2020 at 9:24 am #

Thanks!

But wouldn’t the issue be under-fitting? I would expect very high variance at inference time for a model that over-fit, but we see the opposite..
.

• Jason Brownlee May 27, 2020 at 1:29 pm #

It could be either over or under fit. Both could give similar behavior.

19. Hoang Ngo May 27, 2020 at 2:02 pm #

BTW Jason, great site you got going here, I’m a software engineer too and starting to learn ML and I love your content. Keep up the great work, you’re doing a blessing to all devs wanting to get in the ML train ride!

• Jason Brownlee May 28, 2020 at 6:07 am #

Thanks!

20. Bruce D. Sidlinger June 6, 2020 at 7:26 am #

>>> # check pytorch version
>>> import torch
>>> print(torch.__version__)
1.5.0
>>>
(base) MacBookAir81-2:~ sidlinger\$ nano bindemo.py
(base) MacBookAir81-2:~ sidlinger\$ python bindemo.py
235 116
Accuracy: 0.931
Predicted: 0.999 (class=1)
(base) MacBookAir81-2:~ sidlinger\$

• Jason Brownlee June 6, 2020 at 8:00 am #

Grea work!

21. Hemanth V June 21, 2020 at 11:07 pm #

Jason,

I plotted actuals Vs predictions for the Regression example and see a constant line. Tried changing learning rate, epochs, Relu, number of hidden layers but did not help. This is true for other data sets aswell, not just Boston Housing dataset. Looks like something else needs to be changed in the program, any ideas.

Thanks
Hemanth

• Jason Brownlee June 22, 2020 at 6:14 am #

Sorry to hear that you are having trouble, this may help:
https://machinelearningmastery.com/faq/single-faq/why-does-the-code-in-the-tutorial-not-work-for-me

• Hemanth V June 22, 2020 at 3:40 pm #

Json,

The code is unmodified just added a plot to evaluate_model function, pl see below. My torch version is 1.5.1 running on anaconda windows 10. All code is run from command line. Could you check once on your system, if you are seeing a constant line for predictions.

Thanks
Hemanth

def evaluate_model(test_dl, model):
predictions, actuals = list(), list()
for i, (inputs, targets) in enumerate(test_dl):
# evaluate the model on the test set
yhat = model(inputs)
# retrieve numpy array
yhat = yhat.detach().numpy()
actual = targets.numpy()
actual = actual.reshape((len(actual), 1))
# store
predictions.append(yhat)
actuals.append(actual)
predictions, actuals = vstack(predictions), vstack(actuals)
# calculate mse
mse = mean_squared_error(actuals, predictions)
pyplot.plot(actuals)
pyplot.plot(predictions, color=’red’)
pyplot.show()
return mse

• Jason Brownlee June 23, 2020 at 6:15 am #

It is possible that the model is not skilful and requires further tuning on the dataset.

• Hemanth V June 23, 2020 at 11:37 am #

Can you suggest how to do further training

• Jason Brownlee June 23, 2020 at 1:28 pm #

Here are some suggestions for improving neural nets:
http://machinelearningmastery.com/improve-deep-learning-performance/

22. SJ July 10, 2020 at 4:07 am #

Thank you Jason,
I tried to solve the NYC taxi problem
https://www.kaggle.com/c/new-york-city-taxi-fare-prediction

I was able to crack it even though it had Categorical Variables, however i couldn’t create a “prepare data” function as the Model requires many inputs:

class TabularModel(nn.Module):
def __init__(self, embedding_size, num_numerical_cols, output_size, layers, p=0.4):

Can you please suggest how to write the “Preapre data” when there are categorical and numerical values ?

Sample code for your reference – https://stackabuse.com/introduction-to-pytorch-for-classification/

• Jason Brownlee July 10, 2020 at 6:07 am #

Sorry, I don’t have data preparation tutorials for pytorch, I cannot give you good advice off the cuff.

23. Bunga July 12, 2020 at 9:27 am #

Hi
Thank for the great tutorial.

Anyway, I copied the mlp multiclass classification and run it in spider. However, it got the following error message.

runfile(‘E:/Exercises/master_MLPMultiClassIris.py’, wdir=’E:/Exercises’)
100 50
Traceback (most recent call last):

File “E:\Exercises\master_MLPMultiClassIris.py”, line 158, in
train_model(train_dl, model)

File “E:\Exercises\master_MLPMultiClassIris.py”, line 113, in train_model
loss = criterion(yhat, targets)

File “C:\Anaconda3\lib\site-packages\torch\nn\modules\module.py”, line 477, in __call__
result = self.forward(*input, **kwargs)

File “C:\Anaconda3\lib\site-packages\torch\nn\modules\loss.py”, line 862, in forward
ignore_index=self.ignore_index, reduction=self.reduction)

File “C:\Anaconda3\lib\site-packages\torch\nn\functional.py”, line 1550, in cross_entropy
return nll_loss(log_softmax(input, 1), target, weight, None, ignore_index, None, reduction)

File “C:\Anaconda3\lib\site-packages\torch\nn\functional.py”, line 1407, in nll_loss

RuntimeError: Expected object of type torch.LongTensor but found type torch.IntTensor for argument #2 ‘target’

• Bunga July 12, 2020 at 9:29 am #

Sorry,,, I accidently press enter before finishing my message. Would you mind suggesting me what to do in resolving this problem?

• Jason Brownlee July 12, 2020 at 11:29 am #

I’m sorry to hear that you’re having trouble, I have some suggestions here that might help:
https://machinelearningmastery.com/faq/single-faq/why-does-the-code-in-the-tutorial-not-work-for-me

• Bunga July 14, 2020 at 7:48 pm #

Thanks a lot, Jason…

I am truly sorry for instantly jumping into questioning. The previous problem has disappeared now and dealing with another problem in the same program.

I would recheck it again though….

• Jason Brownlee July 15, 2020 at 8:15 am #

No problem.

• Waiming July 20, 2020 at 6:47 pm #

Jason,

I got the same error as Bunga, only for Multi-class code. Can you help?

RuntimeError Traceback (most recent call last)
in
149 model = MLP(4)
150 # train the model
–> 151 train_model(train_dl, model)
152 # evaluate the model
153 acc = evaluate_model(test_dl, model)

in train_model(train_dl, model)
104 yhat = model(inputs)
105 # calculate loss
–> 106 loss = criterion(yhat, targets)
107 # credit assignment
108 loss.backward()

• Jason Brownlee July 21, 2020 at 5:59 am #

Sorry to hear that, this will help:
https://machinelearningmastery.com/faq/single-faq/why-does-the-code-in-the-tutorial-not-work-for-me

• Waiming July 20, 2020 at 5:32 pm #

Hi Bunga,

I met the same problem as yours.
How did you solve the 1st issue?

• Waiming July 20, 2020 at 7:04 pm #

Bunga,

How can you solve the runtime error, can you share with me? I got the same error

24. L. Wolf July 24, 2020 at 3:46 am #

Nice tuto JAson!
Please do you have an ebook on pytorch?

• Jason Brownlee July 24, 2020 at 6:36 am #

Not at this stage.

25. Haider August 24, 2020 at 1:00 am #

greetings I hope you are doing great I am getting this error while trying to run your given code for MLP multiclass classification problem

runfile(‘C:/Users/haide/OneDrive/바탕 화면/temp.py’, wdir=’C:/Users/haide/OneDrive/바탕 화면’)
100 50
Traceback (most recent call last):

File “C:\Users\haide\OneDrive\바탕 화면\temp.py”, line 150, in
train_model(train_dl, model)

File “C:\Users\haide\OneDrive\바탕 화면\temp.py”, line 105, in train_model
loss = criterion(yhat, targets)

File “C:\Users\haide\anaconda3\lib\site-packages\torch\nn\modules\module.py”, line 532, in __call__
result = self.forward(*input, **kwargs)

File “C:\Users\haide\anaconda3\lib\site-packages\torch\nn\modules\loss.py”, line 915, in forward
return F.cross_entropy(input, target, weight=self.weight,

File “C:\Users\haide\anaconda3\lib\site-packages\torch\nn\functional.py”, line 2021, in cross_entropy
return nll_loss(log_softmax(input, 1), target, weight, None, ignore_index, None, reduction)

File “C:\Users\haide\anaconda3\lib\site-packages\torch\nn\functional.py”, line 1838, in nll_loss
ret = torch._C._nn.nll_loss(input, target, weight, _Reduction.get_enum(reduction), ignore_index)

RuntimeError: expected scalar type Long but found Int

Any idea how to remove this error, please?

26. German Mandrini August 26, 2020 at 4:25 am #

Great tutorial, very clear. I run the MLP for Regression and when I change the predictor values of the “row” I get always the same that. Is it possible that the model is predicting only one value?
Thanks

• German Mandrini August 26, 2020 at 4:27 am #

*the same “yhat”. The dictionary changed it.

• Jason Brownlee August 26, 2020 at 6:54 am #

It is possible, in which case perhaps the model requires further tuning.

27. JC September 6, 2020 at 5:41 pm #

Hi Jason,

I am soon enrolling a course on DL at my work, now doing some exercises in advance to better understand the logic of e.g. perceptrons. Running your MLP for MC classification, I get the error shown below (just from copy’n’paste into my IDE). What am I doing wrong? I get the 100, 50, but accuracy info is blocked by the error happening.

Traceback (most recent call last):
File “C:/Users/jcst/PycharmProjects/Deep_Learning_Projects/MLP_for_Multiclass_Classification.py”, line 166, in
train_model(train_dl, model)
File “C:/Users/jcst/PycharmProjects/Deep_Learning_Projects/MLP_for_Multiclass_Classification.py”, line 121, in train_model
loss = criterion(yhat, targets)
File “C:\Users\jcst\PycharmProjects\Deep_Learning_Projects\venv\lib\site-packages\torch\nn\modules\module.py”, line 722, in _call_impl
result = self.forward(*input, **kwargs)
File “C:\Users\jcst\PycharmProjects\Deep_Learning_Projects\venv\lib\site-packages\torch\nn\modules\loss.py”, line 948, in forward
ignore_index=self.ignore_index, reduction=self.reduction)
File “C:\Users\jcst\PycharmProjects\Deep_Learning_Projects\venv\lib\site-packages\torch\nn\functional.py”, line 2422, in cross_entropy
return nll_loss(log_softmax(input, 1), target, weight, None, ignore_index, None, reduction)
File “C:\Users\jcst\PycharmProjects\Deep_Learning_Projects\venv\lib\site-packages\torch\nn\functional.py”, line 2218, in nll_loss
ret = torch._C._nn.nll_loss(input, target, weight, _Reduction.get_enum(reduction), ignore_index)
RuntimeError: expected scalar type Long but found Int

28. Joseph Kim September 11, 2020 at 11:35 pm #

I am always thankful for your valuable articles like this!

Just one minor comment for the loss function:
The cross entropy loss (i.e., torch.nn.CrossEntropyLoss) in PyTorch combines nn.LogSoftmax() and nn.NLLLoss() in one single class, which means that you don’t need the softmax function in the case of multiclass classification problem (e.g., see the comments from ‘Oli’, ‘god_sp33d’, and so on). In fact, many PyTorch tutorials on multiclass classification do not use the softmax function for the said reason.

• Jason Brownlee September 12, 2020 at 6:15 am #

Thanks!

29. George November 9, 2020 at 5:14 pm #

Hi Jason,
How to do parameter tuning for epochs, activation function…. for pytorch?
Thanks

• Jason Brownlee November 10, 2020 at 6:36 am #

Perhaps start with a simple for-loop over the values you want to compare.