Learn practical skills, build real-world projects, and advance your career
Updated 3 years ago
5 Basic PyTorch Tensor Functions.
PyTorch is a deep learning python library. It is known for providing two of the most high-level features; namely, tensor computations with strong GPU acceleration support and building deep neural networks on a tape-based autograd systems.
PyTorch Tensor Functions are very helpful to make our program easy to handle and gives opportunity to reduce to effort level of cpu and save time.
- new_tensor()
- new_zeros()
- fill_diagonal_()
- torch.arange()
- torch.flip()
Before we begin, let's install and import PyTorch
# Uncomment and run the appropriate command for your operating system, if required
# Linux / Binder
# !pip install numpy torch==1.7.0+cpu torchvision==0.8.1+cpu torchaudio==0.7.0 -f https://download.pytorch.org/whl/torch_stable.html
# Windows
!pip install numpy torch==1.7.0+cpu torchvision==0.8.1+cpu torchaudio==0.7.0 -f https://download.pytorch.org/whl/torch_stable.html
# MacOS
# !pip install numpy torch torchvision torchaudio
# Import torch and other required modules
import torch
import numpy as np
Function 1 - new_tensor
With the help of new_tensor functions, we can create a new tensor from a stored data already like numpy array.
# Example 1 - working (change this)
num = [[5,8,2,8],[5,9,4,6],[5,7,6,1],[5,4,8,3]]
tensor = torch.ones((4,), dtype=torch.int16)
new = tensor.new_tensor(num)
print(new)
tensor([[5, 8, 2, 8],
[5, 9, 4, 6],
[5, 7, 6, 1],
[5, 4, 8, 3]], dtype=torch.int16)