0
0
PyTorchml~5 mins

Tensor creation (torch.tensor, zeros, ones, rand) in PyTorch

Choose your learning style9 modes available
Introduction
Tensors are like multi-dimensional arrays that store data for machine learning. Creating tensors is the first step to work with data in PyTorch.
When you want to convert a list or array of numbers into a tensor to use in a model.
When you need a tensor filled with zeros to initialize weights or biases.
When you want a tensor filled with ones for masks or initial values.
When you want to create a tensor with random numbers for testing or initialization.
Syntax
PyTorch
torch.tensor(data, dtype=None, device=None)
torch.zeros(size, dtype=None, device=None)
torch.ones(size, dtype=None, device=None)
torch.rand(size, dtype=None, device=None)
Use torch.tensor() to create a tensor from existing data like lists or arrays.
Use torch.zeros(), torch.ones(), and torch.rand() to create tensors with specific values and shapes.
Examples
Creates a 1D tensor with values 1, 2, 3.
PyTorch
import torch

# Create tensor from list
t = torch.tensor([1, 2, 3])
Creates a 2x3 tensor filled with zeros.
PyTorch
t = torch.zeros((2, 3))
Creates a 1D tensor of length 4 filled with ones.
PyTorch
t = torch.ones((4,))
Creates a 2x2 tensor with random numbers between 0 and 1.
PyTorch
t = torch.rand((2, 2))
Sample Model
This program shows how to create tensors from a list, and how to create tensors filled with zeros, ones, and random values. It prints each tensor so you can see the results.
PyTorch
import torch

# Create tensor from list
tensor_from_list = torch.tensor([5, 10, 15])

# Create a 3x3 tensor of zeros
tensor_zeros = torch.zeros((3, 3))

# Create a 2x4 tensor of ones
tensor_ones = torch.ones((2, 4))

# Create a 2x2 tensor with random values
tensor_rand = torch.rand((2, 2))

print("Tensor from list:")
print(tensor_from_list)
print("\nTensor of zeros:")
print(tensor_zeros)
print("\nTensor of ones:")
print(tensor_ones)
print("\nTensor of random values:")
print(tensor_rand)
OutputSuccess
Important Notes
The random values in torch.rand() will be different each time you run the code.
You can specify the data type with the dtype argument, for example dtype=torch.float32.
Tensors can be created on different devices like CPU or GPU using the device argument.
Summary
Tensors are the main data structure in PyTorch for storing numbers.
Use torch.tensor() to convert data into tensors.
Use torch.zeros(), torch.ones(), and torch.rand() to create tensors with specific values and shapes.