PyTorch Tensor Creation song & examples

Tensor Creation:

  1. torch.tensor(data) – Creates a tensor from data (e.g., list or NumPy array).
  2. torch.zeros(size) – Creates a tensor filled with zeros.
  3. torch.ones(size) – Creates a tensor filled with ones.
  4. torch.arange(start, end, step) – Returns a tensor with values from start to end with a specific step.
  5. torch.linspace(start, end, steps) – Creates a 1D tensor of evenly spaced values between start and end.
  6. torch.eye(n) – Creates a 2D identity matrix (n x n).
  7. torch.rand(size) – Returns a tensor with random numbers between 0 and 1.
  8. torch.randn(size) – Returns a tensor with random numbers from a normal distribution.
  9. torch.randint(low, high, size) – Returns a tensor with random integers.

Example: Here are examples for each of the basic tensor creation functions in PyTorch:

  1. torch.tensor(data)
  • Creates a tensor from data such as a list or NumPy array.
import torch

data = [[1, 2], [3, 4]]
tensor = torch.tensor(data)
print(tensor)

Output:

tensor([[1, 2],
        [3, 4]])

  1. torch.zeros(size)
  • Creates a tensor filled with zeros.
tensor = torch.zeros(2, 3)
print(tensor)

Output:

tensor([[0., 0., 0.],
        [0., 0., 0.]])

  1. torch.ones(size)
  • Creates a tensor filled with ones.
tensor = torch.ones(2, 3)
print(tensor)

Output:

tensor([[1., 1., 1.],
        [1., 1., 1.]])

  1. torch.arange(start, end, step)
  • Returns a tensor with values from start to end with a specified step.
tensor = torch.arange(0, 10, 2)
print(tensor)

Output:

tensor([0, 2, 4, 6, 8])

  1. torch.linspace(start, end, steps)
  • Creates a 1D tensor of evenly spaced values between start and end.
tensor = torch.linspace(0, 1, 5)
print(tensor)

Output:

tensor([0.0000, 0.2500, 0.5000, 0.7500, 1.0000])

  1. torch.eye(n)
  • Creates a 2D identity matrix (n x n).
tensor = torch.eye(3)
print(tensor)

Output:

tensor([[1., 0., 0.],
        [0., 1., 0.],
        [0., 0., 1.]])

  1. torch.rand(size)
  • Returns a tensor with random numbers between 0 and 1.
tensor = torch.rand(2, 3)
print(tensor)

Output:

tensor([[0.7097, 0.4939, 0.9877],
        [0.4185, 0.2481, 0.4788]])

  1. torch.randn(size)
  • Returns a tensor with random numbers from a normal distribution (mean 0, std 1).
tensor = torch.randn(2, 3)
print(tensor)

Output:

tensor([[-0.6979, -0.2655,  0.0286],
        [ 1.4759,  0.0384, -1.4901]])

  1. torch.randint(low, high, size)
  • Returns a tensor with random integers between low and high.
tensor = torch.randint(0, 10, (2, 3))
print(tensor)

Output:

tensor([[5, 8, 7],
        [9, 4, 6]])


Discover more from Science Comics

Subscribe to get the latest posts sent to your email.

Leave a Reply

error: Content is protected !!