PyTorch List to Tensor: Convert A Python List To A PyTorch Tensor

PyTorch List to Tensor - Use the PyTorch Tensor operation (torch.tensor) to convert a Python list object into a PyTorch Tensor

PyTorch List to Tensor - Use the PyTorch Tensor operation (torch.tensor) to convert a Python list object into a PyTorch Tensor

Video Transcript


This video will show you how to convert a Python list object into a PyTorch tensor using the tensor operation.


First, we import PyTorch.

import torch


Then we check the PyTorch version we are using.

print(torch.__version__)

We are using PyTorch version 0.4.1.


Next, let’s create a Python list full of floating point numbers.

py_list = [[1.,2.,3.,4.],[5.,6.,7.,8.],[9.,10.,11.,12.]]

We can tell that they’re floating point because each number has a decimal point.


To confirm that it’s a Python list, let’s use the Python type operation.

type(py_list)

We can see that it’s a class list.


Next, let’s use the PyTorch tensor operation torch.Tensor to convert a Python list object into a PyTorch tensor.


In this example, we’re going to specifically use the float tensor operation because we want to point out that we are using a Python list full of floating point numbers.

pt_tensor_from_list = torch.FloatTensor(py_list)

So we use torch.FloatTensor and we pass our py_list variable which contains our original Python list.

And the result from this operation is going to be assigned to the Python variable pt_tensor_from_list.


Let’s check what kind of object the Python variable pt_tensor_from_list is holding using the Python type operation, and we see that it is a class of torch.Tensor.

type(pt_tensor_from_list)


Next, let’s check to see the data type of the data inside of the tensor by using the PyTorch dtype operator.

pt_tensor_from_list.dtype

So we have the variable, and then we have dtype.

When we evaluate it, we see that the data type inside of it is torch.float32.

So these are floating point numbers.


Finally, let’s print out the tensor to see what we have.

print(pt_tensor_from_list)

We print pt_tensor_from_list, and we have our tensor.

That is 1x3x4.

We see that all of our original numbers are inside of it and we also know that they are being evaluated as floating32 numbers.


Perfect - We were able to use the PyTorch tensor operation torch.Tensor to convert a Python list object into a PyTorch tensor.

Receive the Data Science Weekly Newsletter every Thursday

Easy to unsubscribe at any time. Your e-mail address is safe.