Add Two PyTorch Tensors Together

Add two PyTorch Tensors together by using the PyTorch add operation

Add two PyTorch Tensors together by using the PyTorch add operation

Video Transcript


This video will show you how to add two PyTorch tensors together by using the PyTorch add operation.


First, we import PyTorch.

import torch


Then we print the PyTorch version we are using.

print(torch.__version__)

We are using PyTorch 0.3.1.post2.


Let’s now create a PyTorch tensor for our example.

pt_tensor_one_ex = torch.Tensor([2, 3, 4])

So we use torch.Tensor.

We want it to be 2x3x4.

We assign it to the Python variable pt_tensor_one_ex.


Let’s print the pt_tensor_one_ex Python variable to see what we have.

print(pt_tensor_one_ex)

We see that it’s a torch.FloatTensor of size 3.

The elements are the number 2, the number 3, and the number 4, just as we defined it.


Next, let’s create a second tensor to add to our first.

pt_tensor_two_ex = torch.Tensor([4, 3, 2])

So we use torch.Tensor again, we define it as 4, 3, 2, and we assign it to the Python variable pt_tensor_two_ex.


We print this variable to see what we have.

print(pt_tensor_two_ex)

We see that it’s a torch.FloatTensor of size 3.

We see the numbers 4, 3, 2.


Next, let’s add the two tensors together using the PyTorch dot add operation.

pt_addition_result_ex = pt_tensor_one_ex.add(pt_tensor_two_ex)

So the first tensor, then dot add, and then the second tensor.

The result, we’re going to assign to the Python variable pt_addition_result_ex.

Note that this operation returns a new PyTorch tensor.


We can print the pt_addition_result_ex and see that we get 6, 6, 6.

print(pt_addition_result_ex)

So 2 plus 4 is 6, 3 plus 3 is 6, 4 plus 2 is 6.


All right, so we were able to add two tensors together.

Just to make sure that we didn’t change our initial tensors, let’s check pt_tensor_one_ex.


So we print pt_tensor_one_ex, and we see that it’s still 2, 3, 4.

print(pt_tensor_one_ex)


We also print pt_tensor_two_ex, and we see that it’s still 4, 3, 2.

print(pt_tensor_two_ex)


So the PyTorch addition operation does not change the original tensors.

It generates a new tensor.


Perfect - We were able to add two PyTorch tensors together by using the PyTorch add operation.

Receive the Data Science Weekly Newsletter every Thursday

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