Specify PyTorch Tensor Maximum Value Threshold

Specify PyTorch Tensor Maximum Value Threshold by using the PyTorch clamp operation

Type: FREE   By: Sebastian Gutierrez, AIWorkbox.com Instructor Sebastian Gutierrez   Duration: 1:59   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 specify a PyTorch tensor’s maximum value threshold by using the torch.clamp operation.


First, we import PyTorch.

import torch


Then we print the PyTorch version that we are using.

print(torch.__version__)

We are using PyTorch 0.3.1.post2.


Let’s now create a PyTorch tensor full of random floating point numbers using the torch.rand functionality.

pt_tensor_no_max_val_threshold_ex = torch.rand(2, 4, 6)

The shape is going to be 2x4x6, and we’re going to assign it to the Python variable pt_tensor_no_max_val_threshold_ex.


Let’s print this variable to see what we have.

print(pt_tensor_no_max_val_threshold_ex)

We see that it’s a PyTorch FloatTensor of size 2x4x6, all the numbers are floating point numbers, and they are between zero and the number one.


Next, let’s create a PyTorch tensor based on our pt_tensor_no_max_val_threshold_ex whose values will adhere to a 0.5 maximum.

pt_tensor_zero_point_five_max_val_threshold_ex = torch.clamp(pt_tensor_no_max_val_threshold_ex, max=0.5)

So anything above 0.5 will get clamped and converted to a 0.5.

We’re going to use the torch.clamp operation, and we’re going to assign that result to the Python variable pt_tensor_zero_point_five_max_val_threshold_ex.


Let’s now print this result:

print(pt_tensor_zero_point_five_max_val_threshold_ex)

And we see a lot of numbers.

We see 0.5 and we see a lot of numbers below 0.5.


Let’s compare it to our original tensor.

We’re going to look at the second matrix.


So the first element, 0.53 is above 0.5, so it got clamped and made a 0.5.


This element, 0.02, is below 0.5, so it gets left alone.


0.93 is above 0.5.

It got converted to a 0.5.


So you can see that any value below 0.5 in the original tensor remains the same value.

However, any value that’s above the 0.5 maximum threshold has now been clamped and updated to be 0.5.


Perfect - We were able to specify a PyTorch tensor’s maximum value threshold by using the torch.clamp operation.



Back to deep learning tutorial lesson list