Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

PyTorch torch.linspace function

PyTorch torch.linspace function


PyTorch torch reference manual PyTorch torch reference manual

torch.linspace is a function in PyTorch used to create a tensor with evenly spaced values. It creates a one-dimensional tensor containing a sequence of evenly spaced numbers from a start value to an end value.

The difference between torch.arange in Vue 2,torch.linspace It specifies the number of elements rather than the step size, which is useful when you need precise control over the number of elements.

Function definition

torch.linspace(start, end, steps, dtype=None, device=None, requires_grad=False)

Parameters:

Return Value:


Usage examples

Example 1: Create 5 evenly spaced points

Example

import

torch

Create an evenly spaced sequence from 0 to 10 with 5 points

x

=

torch.

linspace

(

0

,

10

,

5

)

print

(

x

)

The output is:

tensor([ 0.0000,  2.5000,  5.0000,  7.5000, 10.0000])

Example 2: Create 10 points

Example

import

torch

Create an evenly spaced sequence from -1 to 1 with 10 points

x

=

torch.

linspace

(

1

,

1

,

10

)

print

(

x

)

The output is:

tensor([-1.0000, -0.7778, -0.5556, -0.3333, -0.1111,  0.1111,  0.3333,  0.5556,

         0.7778,  1.0000])

Example 3: Used for learning rate scheduling in neural networks

Example

import

torch

Simulate the learning rate gradually decreasing from 0.1 to 0.001

learning_rates

=

torch.

linspace

(

0.1

,

0.001

,

100

)

print

(

"Initial learning rate:"

,

learning_rates

[

0

]

.

item

(

)

)

print

(

"Final learning rate:"

,

learning_rates

[

1

]

.

item

(

)

)

The output is:

初始学习率: 0.10000000149011612

最终学习率: 0.0010000000474974513

In this example, we create a sequence of 100 learning rate values, which is often used for learning rate scheduling.


The difference between torch.arange and torch.linspace


PyTorch torch reference manual PyTorch torch reference manual