From the course: PyTorch Essential Training: Deep Learning

Different ways to create tensors

- [Instructor] Sometimes we want to construct tensors directly from Python objects like lists, tuples or NumPy arrays. We can also create tensors by using different functions in case we want to generate a particular type of tensor. Let's first learn how to create a tensor from a Python list and a tuple. To do that, open notebook 0301, we have already imported PyTorch and numpy as np. I will create a tensor from a list and call it tensor from list by using a torch.tensor method, and this list will contain integers from one to five. This method is used to create a tensor from an existing data structure. Now to create a tensor from a tuple. Tuples are lists that are immutable, meaning that once defined, the individual elements of a tuple cannot be changed. You can easily spot a difference between a tuple and a list because a tuple is written in a sequence of numbers and closed in the round parenthesis. Let's call this tensor tensor_from_tuple. We will call the same torch.tensor method, but this time we'll pass a tuple instead of a list. Go ahead and display these two tensors. Now to create a tensor from a NumPy array, we will call torch.tensor and pass a NumPy array instead of a list or a tuple. Let's display our tensor. PyTorch also has different functions that we can use to create an initialized tensors. The most useful ones are torch.empty(), torch.ones() and torch.zeros(). As you can see, each one of them is used with a torch namespace. These functions take integers as the first two arguments, which specified the size of a tensor. You can easily guess what they do from their name. As you can see in our example using the empty function, we create a tensor from uninitialized elements. If you use a torch.zero function, it creates a tensor with elements initialized with zeros and torch.ones function creates a tensor with all elements initialized to ones. Sometimes you want to initialize the tensor with random values, and PyTorch has a few useful functions called torch.rand, torch.randn and torch.randint. As you can see in our code, the difference between them is that the first one returns a tensor filled with random numbers from uniform distribution. The second one used normal distribution, and the third one returns the tensor filled with random integers using uniform distributions. These functions take integers as first two arguments, which specify the size of a tensor. We can also pass in an optional arguments data type or dtype and device. Often we want to create tensors that have similar properties to another tensor, including the dtype device and layout properties to facilitate calculations. For example, torch.ones_like will create a tensor with all ones with a dtype device and layout properties of tensor X. You can learn more about additional functions used for tensor creation at the official PyTorch documentation page.

Contents