PyTorch torch.linspace() method is **“used to create a one-dimensional tensor of size steps whose values are evenly spaced from start to end, inclusive.”**

From PyTorch 1.11, linspace requires the steps argument. Use steps=100 to restore the previous behavior.

**Syntax**

`torch.linspace(start, end, steps=100, out=None)`

**Parameters**

**start:**The starting value for the set of points.

**end:**The ending value for the set of points.

**steps:**The gap between each pair of adjacent points. Default: 100.

**out(Tensor, optional):**The output tensor.

**Example 1: How to Use torch.linspace() method**

```
import torch
# Create a tensor of 10 points between 0 and 1
tensor = torch.linspace(0, 1, 10)
print(tensor)
```

**Output**

```
tensor([0.0000, 0.1111, 0.2222, 0.3333, 0.4444, 0.5556, 0.6667, 0.7778, 0.8889,
1.0000])
```

**Example 2: Generating Negative Ranges**

Generate a tensor with 5 points between -1 and -5.

```
import torch
# Create a tensor of 5 points between -1 and -5
tensor1 = torch.linspace(-1, -5, 5)
print(tensor1)
```

**Output**

```
tensor([-1., -2., -3., -4., -5.])
```

**Example 3: Using the requires_grad Parameter**

Generate a tensor with 7 points between 2 and 10 and set **requires_grad=True** to be part of the computation with gradient tracking.

```
import torch
# Create a tensor of 7 points between 2 and 10
# with gradient computation enabled
tensor2 = torch.linspace(2, 10, 7, requires_grad=True)
print(tensor2)
```

**Output**

```
tensor([ 2.0000, 3.3333, 4.6667, 6.0000, 7.3333, 8.6667, 10.0000],
requires_grad=True)
```

That’s it!

**Related posts**

Krunal Lathiya is a seasoned Computer Science expert with over eight years in the tech industry. He boasts deep knowledge in Data Science and Machine Learning. Versed in Python, JavaScript, PHP, R, and Golang. Skilled in frameworks like Angular and React and platforms such as Node.js. His expertise spans both front-end and back-end development. His proficiency in the Machine Learning frameworks like PyTorch and Tensorflow is a testament to his versatility and commitment to the craft.