Calculate The Power Of Each Element In A PyTorch Tensor For A Given Exponent

Calculate the power of each element in a PyTorch Tensor for a given exponent by using the PyTorch pow operation

Type: FREE   By: Sebastian Gutierrez, AIWorkbox.com Instructor Sebastian Gutierrez   Duration: 2:04   Technologies: PyTorch, Python

Page Sections: Video  |  Code  |  Transcript


< > Code:

You must be a Member to view code

Access all courses and lessons, gain confidence and expertise, and learn how things work and how to use them.

    or   Log In


Transcript:

This video will show you how to calculate the power of each element in a PyTorch tensor for a given exponent by using the PyTorch pow 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.


Next, let’s manually create a PyTorch tensor using the FloatTensor operation for this example.

pt_tensor_ex = torch.FloatTensor(
[
  [
    [1, 1, 1],
    [2, 2, 2],
    [3, 3, 3]
  ]
  ,
  [
    [4, 4, 4],
    [5, 5, 5],
    [6, 6, 6]
  ]
])

So torch.FloatTensor, and we pass in the structure that we want and we assign it to the Python variable pt_tensor_ex.

We construct this tensor this way so that it is easy to visually check that each element has been raised to a power for a given exponent.


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

print(pt_tensor_ex)

We see that it is a PyTorch FloatTensor of size 2x3x3.

First row of the first matrix is all ones, all twos, all threes, all fours, all fives, all sixes, which is what we expect as that’s how we constructed it.


Now, let’s raise all the elements of our example tensor by the power of two using the PyTorch pow operation.

pt_tensor_pow_ex = torch.pow(pt_tensor_ex, 2)

So torch.pow, we pass in the pt_tensor_ex Python variable, and we’re going to raise all of the elements of this tensor to the power of two.

Basically, we are squaring them.

Then that resulting tensor is going to be assigned to the Python variable pt_tensor_pow_ex.

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

print(pt_tensor_pow_ex)

We see that we have a torch.FloatTensor of size 2x3x3, which is what we would expect.

All the elements were raised to the power of two, so we should expect that the size should be the same.


Now, let’s take a visual look.

1 squared is 1.

2 squared is 4.

3 squared is 9.

And that’s the same thing all across the rows.

4 squared is 16.

5 squared is 25.

6 squared is 36.

And that’s the same thing all across the rows.


Perfect - We were able to calculate the power of each element in a PyTorch tensor for a given exponent by using the PyTorch pow operation.



Back to deep learning tutorial lesson list