Install
Can install from pip
pip install torch
Programming
Before starting, you need to import PyTorch Library
import torch
PyTorch uses Tensor (unique class for PyTorch) for calculation, PyTorch supports auto differential calculation
Basic Programming
- Create 0 dim tensor
- Create 1 dim tensor from numpy array
- Create 2 dim tensor from numpy matrix (array of array)
- Create 3 dim tensor from normal distribution
- Create 4 dim tensor from torch.ones
- Convert PyTorch Tensor to Numpy
- view (reshape)
Create 0 dim tensor
import numpy as np
np1 = np.array([1,3,5,7,9])
# Convert tensor from Numpy
tensor1 = torch.tensor(np1).float()
Create 1 dim tensor from numpy array
np2 = np.array([[1,2,3], [4,5,6]])
tensor2 = torch.tensor(np2).float()
Create 2 dim tensor from numpy matrix (array of array)
# Random
torch.manual_seed(234)
# create shape=[3,2,2] normal distribution tensor 3 x 2 x 2
tensor3 = torch.randn([3,2,2])
# shape
print(tensor3.shape) # torch.Size([3, 2, 2])
# data
print(tensor3.data)
Create 4 dim tensor from torch.ones
# create shape=[2,3,2,2] all one
tensor4 = torch.ones([2,3,2,2])
# shape
print(tensor4.shape) # torch.Size([2, 3, 2, 2])
# data
print(tensor4.data)
Convert PyTorch Tensor to Numpy
Use .data.numpy()
np1 = tensor1.data.numpy()
# Check Type
print(type(np1)) # <class 'numpy.ndarray'>
# Check Value
print(np1)
View
# create shape=[3,2,2] normal distribution tensor 3 x 2 x 2
tensor3 = torch.randn([3,2,2])
# set element -1, adjust auto
tensor2 = tensor3.view(3, -1) # 2 dim
# shape
print(tensor2.shape) # 3 x 4 (12 elements)
# value
print(tensor2.data)
Tensor Attributes
dtype | Get Tensor data type (torch.float32) |
shape | Get shape (same as Numpy shape) |
data | Get value |
required_grad | Whether this tensor supports grad or not |
device | Support device for calculation (CPU, GPU) |
item | Get value (scalar tensor can return actual value) Only 0 dim tensor |
max | Get max value (return tensor) |
コメント