Skip to content
masterclassBuddyTech Buzz5 fresh blogs · 5:00 AM IST

PyTorch · Function

torch.log

Computes the element-wise natural logarithm of a tensor. It returns a new tensor and optionally accepts an output tensor.

How it works

torch.log applies the natural logarithm independently to every element of a tensor. It returns a tensor containing the transformed values and can optionally write into a supplied output tensor.

Syntax

torch.log(input, *, out=None)

Parameters

NameTypeDescription
inputTensorTensor containing the values to transform element-wise.
outTensor, optionalOptional destination tensor for the result.

Returns

A new Tensor containing the natural logarithm of each element of input.

Key points

  • Computes natural logarithms element by element and returns a new tensor.
  • For each element, the result is defined as \(y_i = \log_e(x_i)\).
  • input is the tensor whose elements are transformed.
  • out is an optional keyword argument that supplies the destination tensor.
  • The documented example creates a five-element random tensor scaled by 5 before applying the function.

Common mistakes

  • The function returns a new tensor by default; use the optional out argument when an output tensor is explicitly desired.

Example: Element-wise natural logarithm

import torch

x = torch.tensor([1.0, 2.0, 0.5])
y = torch.log(x)
print(y)

Computes the element-wise natural logarithm of a positive tensor.

When to use it

Log-space transformation

Transforming positive tensor values into log space for numerical or modeling workflows.

Element-wise math

Applying the same natural-log operation across every tensor element.

指定 output storage

Reusing caller-managed storage for the computed result.

Interview questions

QWhat does torch.log compute?

torch.log computes the natural logarithm element by element, so each output value is \(\log_e(x_i)\). It accepts a tensor as input and returns a tensor.

Follow-up: How would you avoid invalid logarithms? Ensure the input values are positive before applying the operation; the page's example uses positive values.

QWhat arguments does torch.log accept?

The required argument is input, a Tensor. The optional keyword-only argument out specifies an output Tensor.

Follow-up: What is the purpose of out? It lets the caller provide the destination tensor for the result.

QHow is torch.log used on a tensor?

For an input tensor containing [1.0, 2.0, 0.5], torch.log produces the element-wise natural-log values. The operation preserves the tensor-shaped, element-wise structure.

Follow-up: Which related operation performs the transformation in place? torch.log_ is the in-place version of torch.log.

  • torch.log_
  • torch._foreach_log
  • torch._foreach_log_

Source: torch.log — PyTorch 2.14 documentation. Checked 2026-10-16.