๐ŸŽ“ A1Learner
๐Ÿ”

PyTorch Tensor Ranges

Tensor ranges build rows of numbers that follow a counting pattern. They suit labels, positions, and quick test data.

Counting with arange

Arange counts from a start value. It stops before the end value and steps by the given step.

import torch
print(torch.arange(0, 10, 2))

Even spacing with linspace

Linspace spreads values evenly between two ends. Both end values are included in the row.

print(torch.linspace(0, 1, 5))

An identity table with eye

Eye builds a square table of ones on the diagonal. The diagonal runs from the top left to the bottom right.

print(torch.eye(3))

Scaling a range

Multiplying a range scales every value at once. Each value in the row is multiplied by 3.

row = torch.arange(1, 6)
print(row * 3)

Example

import torch

numbers = torch.arange(1, 11)
print(numbers)
print(numbers * 7)

Key points

  • A range tensor holds numbers that follow a counting pattern
  • Use arange(start, end, step) to count with a fixed step
  • Use linspace(start, end, count) to spread values evenly
  • Use eye(n) to build a square table with ones on the diagonal
  • Arange stops before its end value, while linspace includes both ends

In this example, the program builds a range from 1 to 10. Arange includes 1 and stops before 11, so 10 is included. The range prints as one row of ten numbers. The next line multiplies every value by 7. That product is the seven times table row.

Try it Yourself

Edit the code, then press Run.

Running is simulated ยท Python Playground

Exercise

What does torch.arange(0, 10, 2) return?