Tensor Creation:
torch.tensor(data)
– Creates a tensor from data (e.g., list or NumPy array).torch.zeros(size)
– Creates a tensor filled with zeros.torch.ones(size)
– Creates a tensor filled with ones.torch.arange(start, end, step)
– Returns a tensor with values from start to end with a specific step.torch.linspace(start, end, steps)
– Creates a 1D tensor of evenly spaced values between start and end.torch.eye(n)
– Creates a 2D identity matrix (n x n).torch.rand(size)
– Returns a tensor with random numbers between 0 and 1.torch.randn(size)
– Returns a tensor with random numbers from a normal distribution.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:
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]])
torch.zeros(size)
- Creates a tensor filled with zeros.
tensor = torch.zeros(2, 3)
print(tensor)
Output:
tensor([[0., 0., 0.],
[0., 0., 0.]])
torch.ones(size)
- Creates a tensor filled with ones.
tensor = torch.ones(2, 3)
print(tensor)
Output:
tensor([[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])
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])
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.]])
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]])
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]])
torch.randint(low, high, size)
- Returns a tensor with random integers between
low
andhigh
.
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.