PyTorch – Reciprocal() | Code Underscored | ninjasquad

PyTorch – Reciprocal() returns a new tensor that contains the input elements’ reciprocal. Unlike torch, the reciprocal in NumPy. Integral inputs are supported by reciprocal. Reciprocal automatically promotes integral inputs to the default scalar type.

## PyTorch – Reciprocal() Syntax

According to the syntax above, the data is an array with several dimensions.

Torch.reciprocal()

The PyTorch function reciprocal() returns the reciprocal of each element in the tensor. It needs just a single parameter. The syntax is:

torch.reciprocal(tensor_object)

The parameter, tensor_object, is a tensor

### Parameters

The parameters include:

input (Tensor) – the input tensor.

### Keyword Arguments

out (Tensor, optional) – the output tensor.

Example

rand_val = torch.randn(4) print(rand_val) torch.reciprocal(rand_val)

### Example: One dimension tensor

In this example, we’ll make a tensor with one dimension and five elements, then return the tensor’s reciprocal of those five elements.

#first import the torch module import torch #create a 1D tensor tensor_data = torch.tensor([4.34,8.67,11.90,7.56,10.43]) #display print("The actual elements in the Tensor: ") print(tensor_data) print("The resultant reciprocals for the tensor are as follows") print(torch.reciprocal(tensor_data))

### Example: Generating a 2-dimensional tensor

To demonstrate how to generate a tensor with two dimensions and five elements per row, we’ll create a tensor and then return the inverse of the elements.

#first import the torch module import torch #create a 2D tensor tensor_data = torch.tensor([[1.34,5.67,8.90,4.56,7.43],[1,2,3,4,5]]) #display print("The actual elements in the Tensor are: ") print(tensor_data) print("The reciprocals are as follows:") print(torch.reciprocal(tensor_data))

### Utilizing a CPU

We must create a tensor with a cpu() function to execute a reciprocal() process on the CPU. It will operate on a computer with a CPU. This time, we can use the cpu() function when building a tensor.

The syntax is:

torch.tensor(tensor_data).cpu()

### Example: One dimensional tensor with five elements

In this example, we’ll generate a tensor with one dimension and five elements on the CPU, then return the tensor’s reciprocal.

#first import the torch module import torch #create a 1D tensor tensor_data = torch.tensor([4.34,8.67,11.90,7.56,10.43]).cpu() #display print("The actual elements in the Tensor are: ") print(tensor_data) print("The resulting reciprocals include") print(torch.reciprocal(tensor_data))

### Example: 2 Dimensional tensors with five components

In this example, we’ll generate a two-dimensional tensor with five components in each row on the computer and then return the inverse of the elements.

#first import the torch module import torch #create a 2D tensor tensor_data = torch.tensor([[4.34,8.67,11.90,7.56,10.43],[1,2,3,4,5]]).cpu() #display print("The actual elements in the Tensor comprise of ") print(tensor_data) print("The resulting reciprocals include the following") print(torch.reciprocal(tensor_data))

### Example: Establishing Normalization of Log

def normal_normalization_of_logs(x, mean, lg_var, avg=False, reduce=True, dim=None): new_log_norm = -(x - mean) * (x - mean) new_log_norm *= torch.reciprocal(2.*lg_var.exp()) new_log_norm += -0.5 * lg_var new_log_norm += -0.5 * torch.log(2. * PI) if reduce: if avg: return torch.mean(new_log_norm, dim) else: return torch.sum(new_log_norm, dim) else: return new_log_norm

### Example: Handling Laplacian Coordinates

def handle_laplacian_coordinates(self, pred, block_id): r''' provides the laplacian coordinates for the specified block and the forecasts. The surrounding vertices and the number of neighbors important to the weight matrix are found using the helper matrices. If a vertex has fewer neighbors than the maximum of 8, the index -1 is utilized, which points to the extra zero vertexes. Arguments: pred (tensor): responsible for handling vertex predictions block_id (int): deformation block id (1,2 or 3) ''' size_of_batch = pred.shape[0] number_of_vertices = pred.shape[1] # Add "zero vertexes" for vertices with less than eight neighbors var_vertex = torch.cat( [pred, torch.zeros(size_of_batch, 1, 3).to(self.device)], 1) assert(var_vertex.shape == (size_of_batch, number_of_vertices +1, 3)) # Get eight neighbors for each vertex; if a vertex has less, the # remaining indices are -1 var_indices = torch.from_numpy( self.lape_idx[block_id-1][:, :8]).to(self.device) assert(var_indices.shape == (num_vert, 8)) var_weights = torch.from_numpy( self.lape_idx[block_id-1][:, -1]).float().to(self.device) var_weights = torch.reciprocal(weights) var_weights = var_weights.view(-1, 1).expand(-1, 3) vertex_select = var_vertex[:, var_indices.long(), :] assert(vertex_select.shape == (size_of_batch, number_of_vertices, 8, 3)) var_laplace = vertex_select.sum(dim=2) # Add neighbours var_laplace = torch.mul(var_laplace, var_weights) # Multiply by weights var_laplace = torch.sub(pred, var_laplace) # Subtract from prediction assert(var_laplace.shape == (size_of_batch, number_of_vertices, 3)) return var_laplace

### torch.rsqrt() Method in Python PyTorch

Each member of the input tensor’s square-root reciprocal is calculated using the torch.rsqrt() method. It accepts inputs with real and complex values. The matching element in the output tensor is NaN if an element in the input tensor is zero.

The syntax is as follows:

#### Parameters

The torch.rsqrt() takes a single parameter, i.e., input which refers to the input tensor

#### Output

The resultant output is a tensor with a reciprocal of square root.

### Steps

Add the necessary library. The essential Python library for each of the ensuing examples is the torch. Please make certain that it is already installed.

Subsequently, start by creating a torch tensor and printing it as follows:

var_input = torch.randn(3,4) print("Tensor Input is:\n", var_input)

Use the torch to calculate the reciprocal of the square root of each input tensor torch. rsqrt(input). The input tensor is called input here.

var_reciprocal = torch.rsqrt(input)

Prepare the reciprocal values for the computed tensor to be displayed.

print("SQRT of the Reciprocal Tensor:\n", var_reciprocal)

#### Example: Using real and complex values to calculate the reciprocal of the square root

This Python application calculates the reciprocal of the square root of input tensors with real and complex values.

# Import the required library import torch # define an input tensor var_input = torch.tensor([1.2, 3., 4., 4.2, -3.2]) # print the above-defined tensor print("The Tensor input is:\n", var_input) # compute the reciprocal of the square root var_reciprocal = torch.rsqrt(var_input) # print the above-computed tensor print("Reciprocal SQRT Tensor:\n", var_reciprocal) print("............................") # define a complex input tensor var_input = torch.tensor([1.2+2j, 3.+4.j, 4.2-3.2j]) # print the above-defined tensor print("Tensor Input Variable:\n", var_input) # compute the reciprocal of the square root var_reciprocal = torch.rsqrt(var_input) # print the above-computed tensor print("The Reciprocal SQRT Tensor:\n", var_reciprocal)

Note that the Reciprocal SQRT tensor member that corresponds to a zero in the input tensor is NaN.

#### Example: Computing the reciprocal of the square root

# Import the required library import torch # define an input tensor var_input = torch.randn(3,4) # print the above-defined tensor print("The Tensor's Input is:\n", var_input) # compute the reciprocal of the square root var_reciprocal = torch.rsqrt(var_input) # print the above-computed tensor print("The Reciprocal SQRT Tensor:\n", var_reciprocal) print("......................................") # define a complex input tensor var_real = torch.randn(3,3) var_imag = torch.randn(3,3) var_input = torch.complex(var_real, var_imag) # print the above-defined tensor print("The Tensor's Input is:\n", var_input) # compute the reciprocal of the square root var_reciprocal = torch.rsqrt(var_input) # print the above-computed tensor print("The Reciprocal SQRT Tensor:\n", var_reciprocal)

#### Example: Using torch.rsqrt() to compute reciprocal of 1-dimensional float tensor

In this example, the reciprocal of the square root of a one-dimensional float tensor is computed using the torch.rsqrt() method. Additionally, there are negative and zero values in the tensor. The input tensor, in this case, has a third element that is zero and an rsqrt of inf, and a fourth element that is a negative number and an rsqrt of nan.

# Python program to compute the reciprocal of # square root of a tensor # importing torch import torch # define the input tensor var_a = torch.tensor([1.2, 0.32, 0., -32.3, 4.]) # print the input tensor print("The tensor is:\n", var_a) # compute the reciprocal square root var_result = torch.rsqrt(a) # printing the results computed print("rsqrt of the tensor is:\n", var_a result)

#### Example: rsqrst of a complex 1-dimensional tensor

In the example ensuing, the torch calculates the rsqrt of a one-dimensional complex tensor.rsqrt() function. You might notice that you obtain a different number with each run because the complex numbers are generated using a random number generator.

# Python program to compute the reciprocal of # square root of a complex tensor # importing torch import torch # define the input tensor var_a a = torch.randn(4, dtype=torch.cfloat) # print the input tensor print("The original tensor is:\n", var_a a) # compute reciprocal square root var_a result = torch.rsqrt(var_a a) # print the computed result print("rsqrt of the tensor is:\n", var_a result)

**Example: 3-D tensor’s rsqrt**

In the example below, we use torch.rsqrt() function to calculate a 3-D tensor’s rsqrt. You might note that you obtain a different number with each run because we will also engage the services of a random number generator in generating the numbers in this case. The rsqrt of a multidimensional tensor element is computed similarly to one-dimensional tensors.

# Python program to compute the reciprocal of # square root of a multi-dimensional tensor # importing torch import torch # define the input tensor var_a a = torch.randn(5, 6, 5) # print the input tensor print("tensor a:\n", var_a a) # compute reciprocal square root var_a result = torch.rsqrt(var_a a) # print the computed result print("The rsqrt of the given tensor is :\n", var_a result)

### Conclusion

In this PyTorch article, we have used the reciprocal() method to return the reciprocal of each element in the tensor.

An open-source framework called PyTorch is offered together with the Python programming language. The data is kept in a multidimensional array called a tensor. We additionally imported the torch module to use the tensor. Further, the function responsible for producing a tensor is called tensor().

The rsqrt() method in PyTorch calculates the square root reciprocal of each input tensor member. Tensors with real and complex values are both acceptable. The square root’s reciprocal of a negative number is returned as “NaN” (not a number), and “inf” is produced for zero. A mathematical formula determines the reciprocal of a number’s square root input.

Source: Internet