PyTorch torch.logspace() Method

PyTorch torch.logspace() method is “used to create a one-dimensional tensor of logarithmically spaced points between two given exponent values, typically for the base 10.”

The torch.logspace() method returns a one-dimensional tensor of steps logarithmically spaced points between base**start and base**end.

Syntax

torch.logspace(start, end, steps=100, base=10, out=None)

Parameters

  1. start: The starting value for the set of points.
  2. end: The ending value for the set of points
  3. steps: Number of points to sample between start and end. Default: 100.
  4. base: Base of the logarithm function. Default: 10.0
  5. out(Tensor, optional): The output tensor.

Example 1: How to Use torch.logspace() function

import torch

# Create a tensor of 5 points between 10^0 and 10^3
tensor = torch.logspace(0, 3, 5)
print(tensor)

Output

tensor([ 1.0000, 5.6234, 31.6228, 177.8279, 1000.0000])

Example 2: Different Base for Logarithm

Generate a tensor with 4 points between 2**0 and 2**4.

import torch

# Create a tensor of 4 points between 2^0 and 2^4 using base 2
tensor1 = torch.logspace(0, 4, 4, base=2)
print(tensor1)

Output

tensor([ 1.0000, 2.5198, 6.3496, 16.0000])

Example 3: Using Negative Exponents

Generate a tensor with 6 points between 10**-1 and 10**-3.

import torch

# Create a tensor of 6 points between 10^-1 and 10^-3
tensor2 = torch.logspace(-1, -3, 6)
print(tensor2)

Output

tensor([0.1000, 0.0398, 0.0158, 0.0063, 0.0025, 0.0010])

That’s it!

Related posts

torch.linspace()

torch.arange()

Leave a Comment