How to compute the Logarithm of elements of a tensor in PyTorch?
Published January 02, 2022To calculate the logarithm of tensor elements in PyTorch, we use the torch.log() method. This function returns a new tensor with the natural log values of the elements of the original input tensor. It takes a tensor as an input argument and outputs a tensor.
How to compute the Logarithm of elements of a tensor in PyTorch
Step 1: Import the necessary torch library and ensure it is already installed.
Step 2: Build and print a tensor.
Step 3: Run torch.log (input).
Step 4: Print the tensor with the natural logarithm values of the original input tensor's components.
Example
The Python program below demonstrates how to calculate the natural logarithm of a PyTorch tensor.
import torch t = torch.Tensor([2.3,3,2.3,4,3.4]) print("Initial values:\n", t) log = torch.log(t) print("Logarithm solutions:\n", log)
|
Output:
Initial values: tensor([2.3000, 3.0000, 2.3000, 4.0000, 3.4000]) Logrithm solutions: tensor([0.8329, 1.0986, 0.8329, 1.3863, 1.2238])
|
Article Contributed By :
|
|
|
|
456 Views |