Updated 4 years ago
5 Basic PyTorch functions
Pytorch is a famous python library for processing tensors. The following are some of the basic functions that are used often in pytorch.
- torch.from_numpy
- torch.reshape
- torch.arange
- torch.numel
- torch.where
Before we begin, let's install and import PyTorch
# 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
Looking in links: https://download.pytorch.org/whl/torch_stable.html
Requirement already satisfied: numpy in /usr/local/lib/python3.6/dist-packages (1.19.4)
Collecting torch==1.7.0+cpu
Downloading https://download.pytorch.org/whl/cpu/torch-1.7.0%2Bcpu-cp36-cp36m-linux_x86_64.whl (159.3MB)
|████████████████████████████████| 159.3MB 42kB/s
Collecting torchvision==0.8.1+cpu
Downloading https://download.pytorch.org/whl/cpu/torchvision-0.8.1%2Bcpu-cp36-cp36m-linux_x86_64.whl (11.8MB)
|████████████████████████████████| 11.8MB 132kB/s
Collecting torchaudio==0.7.0
Downloading https://files.pythonhosted.org/packages/3f/23/6b54106b3de029d3f10cf8debc302491c17630357449c900d6209665b302/torchaudio-0.7.0-cp36-cp36m-manylinux1_x86_64.whl (7.6MB)
|████████████████████████████████| 7.6MB 5.3MB/s
Requirement already satisfied: dataclasses in /usr/local/lib/python3.6/dist-packages (from torch==1.7.0+cpu) (0.8)
Requirement already satisfied: typing-extensions in /usr/local/lib/python3.6/dist-packages (from torch==1.7.0+cpu) (3.7.4.3)
Requirement already satisfied: future in /usr/local/lib/python3.6/dist-packages (from torch==1.7.0+cpu) (0.16.0)
Requirement already satisfied: pillow>=4.1.1 in /usr/local/lib/python3.6/dist-packages (from torchvision==0.8.1+cpu) (7.0.0)
Installing collected packages: torch, torchvision, torchaudio
Found existing installation: torch 1.7.0+cu101
Uninstalling torch-1.7.0+cu101:
Successfully uninstalled torch-1.7.0+cu101
Found existing installation: torchvision 0.8.1+cu101
Uninstalling torchvision-0.8.1+cu101:
Successfully uninstalled torchvision-0.8.1+cu101
Successfully installed torch-1.7.0+cpu torchaudio-0.7.0 torchvision-0.8.1+cpu
# Import torch and other required modules
import torch
import numpy as np
Function 1 - torch.from_numpy
This function creates tensors from numpy arrays. It is a very useful function as most numerical data are stored in numpy arrays after extraction.
# Example 1 - working
a = np.array([1,4,5])
torch.from_numpy(a)
tensor([1, 4, 5])