Pytorch tensors creation methods
A short introduction about PyTorch and about the chosen functions.
What is Pytorch?
PyTorch is a machine learning and deep learning tool developed by Facebook’s artificial intelligence division to process large-scale image analysis, including object detection, segmentation, classification and complex algorithms. PyTorch provides a great framework to write functions that automatically run in a GPU environment.
What is tensor?
A PyTorch Tensor is basically the same as a numpy array: it does not know anything about deep learning or computational graphs or gradients, and is just a generic n-dimensional array to be used for arbitrary numeric computation.
About this notebook.
In this notebook I am trying to explain some basic tensor creation functions and each one explained with the help of examples. For each function I am using two examples to show how it works and one example to show how it not works.
- TORCH.AS_TENSOR
- TORCH.FULL
- TORCH.COMPLEX
- TORCH.LINSPACE
- TORCH.RAND
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
Function 1 - torch.as_tensor
torch.as_tensor(data, dtype=None, device=None) → Tensor
Convert the data into a torch.Tensor.
Parameters
data
(array_like) – Initial data for the tensor. Can be a list, tuple, NumPy ndarray, scalar, and other types.dtype
(torch.dtype, optional) – the desired data type of returned tensor. Default: if None, infers data type from data.
# Example 1
a = [1,2,3,4,5,6]
torch.as_tensor(data = a)
tensor([1, 2, 3, 4, 5, 6])