Tensor computation (like numpy) with strong GPU acceleration
PyTorch is an optimized tensor library for deep learning using GPUs and CPUs.
It has a CUDA counterpart, that enables you to run your tensor computations on an NVIDIA GPU with compute capability >= 3.0.
1 2 3 4 5 6 7 8 9 10
from __future__ import print_function import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim import torch.autograd as autograd from torch.autograd import Variable
import numpy as np print("Import success.\nTorch Version:{}".format(torch.__version__))
Import success.
Torch Version:0.2.1+a4fc05a
Package
Description
torch
a Tensor library like NumPy, with strong GPU support
torch.autograd
a tape based automatic differentiation library that supports all differentiable Tensor operations in torch
torch.nn
a neural networks library deeply integrated with autograd designed for maximum flexibility
torch.optim
an optimization package to be used with torch.nn with standard optimization methods such as SGD, RMSProp, LBFGS, Adam etc.
torch.multiprocessing
python multiprocessing, but with magical memory sharing of torch Tensors across processes. Useful for data loading and hogwild training.
torch.utils
DataLoader, Trainer and other utility functions for convenience
torch.legacy(.nn/.optim)
legacy code that has been ported over from torch for backward compatibility reasons
Brief view in pytorch
1 2 3 4 5 6 7 8
torch.set_printoptions( precision=None, # Number of digits of precision for floating point output (default 8). threshold=None, # Total number of array elements which trigger summarization rather than full repr (default 1000). edgeitems=None, # Number of array items in summary at beginning and end of each dimension (default 3). linewidth=None, # The number of characters per line for the purpose of inserting line breaks (default 80). # Thresholded matricies will ignore this parameter. profile=None, # Sane defaults for pretty printing. Can override with any of the above options. (default, short, full) )
torch.set_printoptions(precision=5) # change print options, just link numpy print("\nTorch Matrix:", tc_mat) torch.set_printoptions(profile='default') # back to default_pretty_printing # print("\nTorch Matrix:", tc_mat)
torch.from_numpy() creates a Tensor from a numpy.ndarray.
The returned tensor and ndarray share the same memory. Modifications to the tensor will be reflected in the ndarray and vice versa. The returned tensor is not resizable.
mask = a.gt(0.5) # if element is greater than 0.5 print('\nMask for greater_than_0.5:', mask) print('\nAfter torch.masked_select(a, mask):', torch.masked_select(a, mask))
Original Matrix a:
-0.0708 0.7695 0.4194 -0.2349
-1.6515 0.4604 0.7691 0.3826
-0.7259 -0.0289 -0.7962 0.5046
[torch.FloatTensor of size 3x4]
Mask for greater_than_0.5:
0 1 0 0
0 0 1 0
0 0 0 1
[torch.ByteTensor of size 3x4]
After torch.masked_select(a, mask):
0.7695
0.7691
0.5046
[torch.FloatTensor of size 3]
We select index: select = torch.LongTensor([0, 2])
After torch.index_select(a, axis=0, select):
-0.0708 0.7695 0.4194 -0.2349
-0.7259 -0.0289 -0.7962 0.5046
[torch.FloatTensor of size 2x4]
After torch.index_select(a, axis=1, select):
-0.0708 0.4194
-1.6515 0.7691
-0.7259 -0.7962
[torch.FloatTensor of size 3x2]
Data Squeeze
torch.squeeze
You can select which axis to be squeezed
1 2 3 4 5
z = torch.zeros(4,5,1,2) print("Size of Z: \t ", z.size()) print("Size of Z after squeeze(z):\t ", torch.squeeze(z).size()) print("Size of Z after squeeze(z, 1):\t ", torch.squeeze(z, 1).size()) print("Size of Z after squeeze(z, 2):\t ", torch.squeeze(z, 2).size())
Size of Z: torch.Size([4, 5, 1, 2])
Size of Z after squeeze(z): torch.Size([4, 5, 2])
Size of Z after squeeze(z, 1): torch.Size([4, 5, 1, 2])
Size of Z after squeeze(z, 2): torch.Size([4, 5, 2])
There are a few more in-place random sampling functions defined on Tensors as well. Click through to refer to their documentation:
Distribution
description
torch.Tensor.bernoulli_()
in-place version of torch.bernoulli()
torch.Tensor.cauchy_()
numbers drawn from the Cauchy distribution
torch.Tensor.exponential_()
numbers drawn from the exponential distribution
torch.Tensor.geometric_()
elements drawn from the geometric distribution
torch.Tensor.log_normal_()
samples from the log-normal distribution
torch.Tensor.normal_()
in-place version of torch.normal()
torch.Tensor.random_()
numbers sampled from the discrete uniform distribution
torch.Tensor.uniform_()
numbers sampled from the uniform distribution
Variable for requires_grad or not
1 2 3 4 5 6 7 8 9
from torch.autograd import Variable # http://pytorch.org/docs/master/autograd.html#torch.autograd.Function x = Variable(torch.randn(5, 5)) y = Variable(torch.randn(5, 5)) z = Variable(torch.randn(5, 5), requires_grad=True) a = x + y b = a + z print("Variable a=x+y requires grad: ", a.requires_grad) print("Variable b=a+z requires grad: ", b.requires_grad)