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.
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)
import torch # Create tensor from list t = torch.tensor([1, 2, 3])
t = torch.zeros((2, 3))
t = torch.ones((4,))t = torch.rand((2, 2))
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)
torch.zeros() creates a tensor filled with zeros, torch.ones() creates ones, torch.rand() creates random values, and torch.tensor() converts data to tensor.torch.zeros() is the correct choice.torch.ones(2, 3) uses separate ints (valid). torch.ones([2 3]) missing comma (syntax error). torch.ones{2, 3} invalid braces. torch.ones((2 3)) missing comma (syntax error).torch.ones(2, 3) is valid Python syntax.torch.rand(3, 2)?torch.rand(3, 2) creates a tensor with shape (3, 2) filled with random floats between 0 and 1.import torch t = torch.zeros(2 3)
torch.zeros(2 3) missing a comma between 2 and 3, which is a syntax error.[[1,2], [3,4]] and then create a tensor of the same shape filled with ones. Which code correctly does this?torch.tensor(list_data) correctly converts the nested Python list to a (2,2) tensor.torch.ones(t1.shape) creates a tensor filled with ones matching the shape of t1 ((2,2)).import torch list_data = [[1,2], [3,4]] t1 = torch.ones(list_data) t2 = torch.tensor(t1.shape)misuses torch.ones() with nested list (ValueError),
import torch list_data = [[1,2], [3,4]] t1 = torch.tensor(list_data) t2 = torch.ones(len(t1))uses length=2 instead of shape (creates (2,) not (2,2)),
import torch list_data = [[1,2], [3,4]] t1 = torch.ones(len(list_data)) t2 = torch.tensor(t1.shape)creates t1 wrong (ones not data) and t2 not ones tensor.
Pass the test and this pattern moves unknown