5 pytorch tensor functions

Original article was published on Deep Learning on Medium

5 pytorch tensor functions

This post is a part of the Jovian ML’s, “Deep Learning : Zero to GANs”course. pytorch developed by Facebook is a widely used deep learning framework besides Google’s Tensorflow. We’ll look at 5 different tensor functions from the pytorch library.

torch.cumsum

torch.cumsum(input, dim, out=None, dtype=None) → Tensor
Example: Let’s suppose you hold AAPL stock for 5 years. You want to find out the cumulative return you made at the end of each holding year. The code below provides solution in 2 steps.

torch.randn

torch.randn(input, dim, out=None, dtype=None) → Tensor
Example: Let’s suppose you are learning about images and would like to create an image with random noise to view it. The code below provides a way to generate random values from a normal distribution. Observe output below the code.

torch.index_select

torch.index_select(input, dim, index, out=None) → Tensor
Example: Let’s suppose you have a RGB image and would like to view only the R channel using matplotlib. The code below provides a solution.

torch.from_numpy

torch.from_numpy(ndarray) → Tensor
This function could come in handy when dealing with numerical datasets. The returned tensor and ndarray share the same memory. This doesn’t consume excess memory once loaded.

output : array([10, 99, 12, 13])

torch.flip

torch.flip(input, dims) → Tensor
Let’s suppose for an image augmentation problem you are looking to flip image. The code below provides the solution to flip the image.

Original image
flipped image

Reference Links

pytorch documentation : https://pytorch.org/docs/stable/tensors.html