Learn practical skills, build real-world projects, and advance your career
Updated 4 years ago
A quick overview of inplace operators in PyTorch
Inplace operations in PyTorch are marked with an underscore(_)
at the end of the function
and are exactly the same as their non-inplace counterparts,
with the exception that we don't need to assign their returned values
back to the original variables.
Here we present seven examples of the following inplace operators for tensors in PyTorch
- zero_
- fill_ and fill_diagonal_
- uniform_
- abs_
- sigmoid_
- sqrt_
- clamp_
# Import torch and other required modules
import torch
import matplotlib.pyplot as plt
import seaborn as sns
Function 1 - zero_
Fills a tensor with zeros
We start by creating a new random tensor of dimensions 4*4
tensorA = torch.empty(4,4)
tensorA
tensor([[9.1837e-39, 4.6837e-39, 9.9184e-39, 9.0000e-39],
[1.0561e-38, 1.0653e-38, 4.1327e-39, 8.9082e-39],
[9.8265e-39, 9.4592e-39, 1.0561e-38, 1.0561e-38],
[8.9082e-39, 1.0194e-38, 1.0102e-38, 1.0745e-38]])