PyTorch Clamp: Clip PyTorch Tensor Values To A Range

Use PyTorch clamp operation to clip PyTorch Tensor values to a specific range

Type: FREE   By: Sebastian Gutierrez, Instructor Sebastian Gutierrez   Duration: 1:48   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


First, we import PyTorch.

import torch

Then we print the PyTorch version we are using.


We are using PyTorch 0.3.1.post2.

Let’s now create a PyTorch tensor full of random floating point numbers.

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

So we use torch.rand, we pass in the shape of the tensor we want back which is 2x4x6, and we assign it to the Python variable pt_tensor_not_clipped_ex.

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


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

Next, let’s create a PyTorch tensor based on our pt_tensor_not_clipped_ex tensor example whose values will be clipped to the range from a minimum of 0.4 to a maximum of 0.6 by using the torch.clamp operation.

pt_tensor_yes_clipped_ex = torch.clamp(pt_tensor_not_clipped_ex, min=0.4, max=0.6)

We assign the result to pt_tensor_yes_clipped_ex Python variable.

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


We see that it’s a torch.FloatTensor of size 2x4x6, we see a lot of 0.4s, we see a lot of 0.6s, and we see numbers in between.

Visually checking, we can look at the second matrix.

So 0.2 is below 4 so this gets updated to 4.

0.4132, that’s between 0.4 and 0.6, so the value stays the same.

This value is 0.63 which is above our 0.6 range, so we see it clamped to 6.

So any value below 0.4 has been clamped and updated to be 0.4, any value above 0.6 has been clamped and updated to 0.6, and any value in between has been left alone.

Perfect - We were able to clip a PyTorch tensor’s values to a range by using the torch.clamp operation.

Back to PyTorch Tutorial Lesson List