深度学习 / 55.1

PyTorch张量:形状、运算与设备

张量、模型与训练过程。 PyTorch张量:形状、运算与设备。

阅读说明: 保留原笔记的编号与章节顺序;代码只供查看,没有在本站运行。历史输出不代表当前版本的复现结果。截图/外链图以独立整理的公式、表格、示意或文字替换;纠错与必要补充均作说明。

PYTHON · 仅供阅读
%matplotlib inline

0. What is PyTorch?

It’s a Python-based scientific computing package targeted at two sets of audiences:

  • A replacement for NumPy to use the power of GPUs
  • A deep learning research platform that provides maximum flexibility and speed

1. Getting Started

Tensors are similar to NumPy’s ndarrays, with the addition being that Tensors can also be used on a GPU to accelerate computing.

PYTHON · 仅供阅读
from torch.autograd import Variable 已被废弃
直接:
x = torch.randn(N, D_in)
PYTHON · 仅供阅读
# from __future__ import print_function
import torch
import numpy as np

Construct a 5x3 matrix, uninitialized:

PYTHON · 仅供阅读
x = torch.empty(5, 3)
print(x)
原笔记输出 · 本次未执行
tensor([[2.1619e-33, 6.4600e-43, 2.1619e-33],
        [6.4600e-43, 2.1620e-33, 6.4600e-43],
        [2.1620e-33, 6.4600e-43, 2.1618e-33],
        [6.4600e-43, 2.1618e-33, 6.4600e-43],
        [2.1616e-33, 6.4600e-43, 2.1616e-33]])

整理注: torch.empty为未初始化内存;打印的值没有数学含义,不可作为随机初始化。这里仅保留原输出,不在站点分配或读取未初始化内存。

Construct a randomly initialized matrix:

PYTHON · 仅供阅读
x = torch.rand(5, 3)
print(x)
原笔记输出 · 本次未执行
tensor([[0.3949, 0.2483, 0.7308],
        [0.5197, 0.0942, 0.2607],
        [0.0216, 0.9783, 0.0192],
        [0.8772, 0.2504, 0.5289],
        [0.5290, 0.3911, 0.1284]])

Construct a matrix filled zeros and of dtype long:

PYTHON · 仅供阅读
x = torch.zeros(5, 3, dtype=torch.long)
print(x)
原笔记输出 · 本次未执行
tensor([[0, 0, 0],
        [0, 0, 0],
        [0, 0, 0],
        [0, 0, 0],
        [0, 0, 0]])

Construct a tensor directly from data:

PYTHON · 仅供阅读
x = torch.tensor([5.5, 3])
print(x)
原笔记输出 · 本次未执行
tensor([5.5000, 3.0000])

or create a tensor based on an existing tensor. These methods will reuse properties of the input tensor, e.g. dtype, unless new values are provided by user

PYTHON · 仅供阅读
x = x.new_ones(5, 3, dtype=torch.double)      # new_* methods take in sizes
print(x)
原笔记输出 · 本次未执行
tensor([[1., 1., 1.],
        [1., 1., 1.],
        [1., 1., 1.],
        [1., 1., 1.],
        [1., 1., 1.]], dtype=torch.float64)
PYTHON · 仅供阅读
x = torch.randn_like(x, dtype=torch.float)    # override dtype!
print(x)                                      # result has the same size
原笔记输出 · 本次未执行
tensor([[ 1.5208, -0.0597, -0.0905],
        [-1.4642, -0.1585,  1.1798],
        [-0.7855,  0.1995,  0.5058],
        [ 1.1318, -0.8209,  0.6122],
        [ 2.1100, -0.0974,  0.1178]])

Get its size:

PYTHON · 仅供阅读
print(x.size())
原笔记输出 · 本次未执行
torch.Size([5, 3])
PYTHON · 仅供阅读
x = torch.Tensor([1., 2., 3.])

print(x)
print(x.shape)
print(torch.ones(2, 1))
print(torch.zeros_like(x))
原笔记输出 · 本次未执行
tensor([1., 2., 3.])
torch.Size([3])
tensor([[1.],
        [1.]])
tensor([0., 0., 0.])
PYTHON · 仅供阅读
y = np.array([0, 1, 2, 3])
print(y)

x = torch.from_numpy(y)
print(x)
原笔记输出 · 本次未执行
[0 1 2 3]
tensor([0, 1, 2, 3], dtype=torch.int32)

2. Data types in Pytorch and Casting

dtype含义常用别名
float3232位浮点torch.float
float6464位浮点torch.double
uint88位无符号整数torch.uint8
int88位有符号整数torch.int8
int3232位有符号整数torch.int
int6464位有符号整数torch.long
bool布尔值torch.bool

类型转换可能丢精度;旧式FloatTensor等类型构造器与device管理应区分。

A tensor can be cast to any data type, with possible loss of precision:

PYTHON · 仅供阅读
print(x.dtype)
原笔记输出 · 本次未执行
torch.int32
PYTHON · 仅供阅读
x = x.type(torch.FloatTensor)
print(x.dtype)
原笔记输出 · 本次未执行
torch.float32
PYTHON · 仅供阅读
print(x.float())
print(x.float().dtype)
原笔记输出 · 本次未执行
tensor([0., 1., 2., 3.])
torch.float32
PYTHON · 仅供阅读
print(x.type(torch.DoubleTensor))
原笔记输出 · 本次未执行
tensor([0., 1., 2., 3.], dtype=torch.float64)
PYTHON · 仅供阅读
print(x.type(torch.LongTensor))
原笔记输出 · 本次未执行
tensor([0, 1, 2, 3])

3. Tensor Arithmetic

Addition: syntax 1

PYTHON · 仅供阅读
x = torch.randn(5, 3, dtype=torch.float)
y = torch.rand(5, 3)

print(x + y)
原笔记输出 · 本次未执行
tensor([[-0.7963,  0.5517, -1.0351],
        [ 0.5931,  0.3763, -0.5903],
        [-0.2743,  0.6772,  0.4807],
        [ 2.4802,  1.9205,  0.1098],
        [ 1.3044,  2.1340,  0.6395]])

Addition: syntax 2

PYTHON · 仅供阅读
print(torch.add(x, y))
原笔记输出 · 本次未执行
tensor([[-0.7963,  0.5517, -1.0351],
        [ 0.5931,  0.3763, -0.5903],
        [-0.2743,  0.6772,  0.4807],
        [ 2.4802,  1.9205,  0.1098],
        [ 1.3044,  2.1340,  0.6395]])

Addition: providing an output tensor as argument

PYTHON · 仅供阅读
result = torch.empty(5, 3)
torch.add(x, y, out=result)
print(result)
原笔记输出 · 本次未执行
tensor([[-0.7963,  0.5517, -1.0351],
        [ 0.5931,  0.3763, -0.5903],
        [-0.2743,  0.6772,  0.4807],
        [ 2.4802,  1.9205,  0.1098],
        [ 1.3044,  2.1340,  0.6395]])

Addition: in-place

PYTHON · 仅供阅读
# adds x to y
y.add_(x)
print(y)
原笔记输出 · 本次未执行
tensor([[-0.7963,  0.5517, -1.0351],
        [ 0.5931,  0.3763, -0.5903],
        [-0.2743,  0.6772,  0.4807],
        [ 2.4802,  1.9205,  0.1098],
        [ 1.3044,  2.1340,  0.6395]])

Note

Any operation that mutates a tensor in-place is post-fixed with an _. For example: x.copy_(y), x.t_(), will change x.

PYTHON · 仅供阅读
x = torch.randn(5, 3, dtype=torch.float)
y = torch.rand(5, 3)

print(x - y)
原笔记输出 · 本次未执行
tensor([[-0.3067, -1.9665, -0.9493],
        [-0.5383, -1.5818, -1.5131],
        [ 0.7852, -1.2541, -0.1374],
        [ 0.0908, -2.7448, -0.9767],
        [-0.5671,  0.2215, -1.6113]])
PYTHON · 仅供阅读
print(x.sub(y))
原笔记输出 · 本次未执行
tensor([[-0.3067, -1.9665, -0.9493],
        [-0.5383, -1.5818, -1.5131],
        [ 0.7852, -1.2541, -0.1374],
        [ 0.0908, -2.7448, -0.9767],
        [-0.5671,  0.2215, -1.6113]])

4. Matrix Multiplication vs. Element-wise Multiplication

PYTHON · 仅供阅读
x = torch.tensor([[1, 2, 3]])
y = torch.tensor([[2, 2, 2]])
PYTHON · 仅供阅读
x.shape
原笔记输出 · 本次未执行
torch.Size([1, 3])
PYTHON · 仅供阅读
x.t().shape  # transpose
原笔记输出 · 本次未执行
torch.Size([3, 1])
PYTHON · 仅供阅读
y.shape
原笔记输出 · 本次未执行
torch.Size([1, 3])
PYTHON · 仅供阅读
torch.mul(x, y)
原笔记输出 · 本次未执行
tensor([[2, 4, 6]])
PYTHON · 仅供阅读
x.t().mm(y)
原笔记输出 · 本次未执行
tensor([[2, 2, 2],
        [4, 4, 4],
        [6, 6, 6]])
PYTHON · 仅供阅读
x.mm(y.t())
原笔记输出 · 本次未执行
tensor([[12]])
PYTHON · 仅供阅读
torch.mm(x, y.t())
原笔记输出 · 本次未执行
tensor([[12]])
PYTHON · 仅供阅读
torch.matmul(x, y.t())
原笔记输出 · 本次未执行
tensor([[12]])

5. Other helpful transcendental functions

PyTorch support cos(), sin(), exp() just like Numpy.

PYTHON · 仅供阅读
np.pi
原笔记输出 · 本次未执行
3.141592653589793
PYTHON · 仅供阅读
torch.cos(torch.tensor(np.pi))
原笔记输出 · 本次未执行
tensor(-1.)
PYTHON · 仅供阅读
torch.sin(torch.tensor(np.pi/2))
原笔记输出 · 本次未执行
tensor(1.)
PYTHON · 仅供阅读
torch.exp(torch.tensor(1.))
原笔记输出 · 本次未执行
tensor(2.7183)

6. Logical Operations

PYTHON · 仅供阅读
x = torch.tensor([True, False, False])
y = torch.tensor([True, False, False])

x.shape
原笔记输出 · 本次未执行
torch.Size([3])
PYTHON · 仅供阅读
y.dtype
原笔记输出 · 本次未执行
torch.bool
PYTHON · 仅供阅读
x & y
原笔记输出 · 本次未执行
tensor([ True, False, False])
PYTHON · 仅供阅读
x | y
原笔记输出 · 本次未执行
tensor([ True, False, False])
PYTHON · 仅供阅读
x = torch.tensor([0, 1, 2])
y = torch.tensor([2, 3, 4])

(x > 1) & (y > 1)
原笔记输出 · 本次未执行
tensor([False, False,  True])

7. More logical operations

PYTHON · 仅供阅读
torch.where(condition, input, other)

looks at each index i of 3 input tensors. It will return input if condition true, else will return other:

PYTHON · 仅供阅读
x = torch.tensor([0, 1, 2])
y = torch.tensor([6, 5, 4])

torch.where((x > 0) & (x < 2), x, y)
原笔记输出 · 本次未执行
tensor([6, 1, 4])

Logical operations can be combined with tensor.nonzero() to retrueve relevant array indices. .nonzero() will return the indices of all non_zero elements of the input. It can be used much like np.argwhere(), in the following manner:

PYTHON · 仅供阅读
x = torch.tensor([0, 1, 3, 3])

x == 3
原笔记输出 · 本次未执行
tensor([False, False,  True,  True])
PYTHON · 仅供阅读
(x == 3).nonzero()
原笔记输出 · 本次未执行
tensor([[2],
        [3]])

8. Sorting Operations

PYTHON · 仅供阅读
x = torch.tensor([3, 0, 1, 2])

torch.argsort(x)
原笔记输出 · 本次未执行
tensor([1, 2, 3, 0])

9. Combing Tensors

Tensors can be combined along any dimension, as long as the dimensions align properly. Concatenating(torch.cat()) or stacking(torch.stack()) tensors are considered different operations in PyTorch.
torch.stack() will combine a sequence of tensors along a new dimension, whereas torch.cat() will concatenates tensors along a default dimension dim=0.

PYTHON · 仅供阅读
x = torch.tensor([1, 2, 3])
y = torch.tensor([2, 2, 2])
PYTHON · 仅供阅读
torch.stack([x, y])
原笔记输出 · 本次未执行
tensor([[1, 2, 3],
        [2, 2, 2]])
PYTHON · 仅供阅读
torch.cat([x, y])
原笔记输出 · 本次未执行
tensor([1, 2, 3, 2, 2, 2])
PYTHON · 仅供阅读
x = torch.tensor([[1, 2], [3, 4]])
y = torch.tensor([[2, 2], [2, 2]])
PYTHON · 仅供阅读
torch.stack([x, y])
原笔记输出 · 本次未执行
tensor([[[1, 2],
         [3, 4]],

        [[2, 2],
         [2, 2]]])
PYTHON · 仅供阅读
torch.cat([x, y])
原笔记输出 · 本次未执行
tensor([[1, 2],
        [3, 4],
        [2, 2],
        [2, 2]])

10. NumPy-like Indexing

PYTHON · 仅供阅读
x = torch.arange(4*3)
print(x)
原笔记输出 · 本次未执行
tensor([ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11])
PYTHON · 仅供阅读
x = x.reshape(3, 2, 2)
print(x)
原笔记输出 · 本次未执行
tensor([[[ 0,  1],
         [ 2,  3]],

        [[ 4,  5],
         [ 6,  7]],

        [[ 8,  9],
         [10, 11]]])
PYTHON · 仅供阅读
x[0, :, :]
原笔记输出 · 本次未执行
tensor([[0, 1],
        [2, 3]])
PYTHON · 仅供阅读
x[1, 1:, :]
原笔记输出 · 本次未执行
tensor([[6, 7]])
PYTHON · 仅供阅读
x[2, 0, 1]
原笔记输出 · 本次未执行
tensor(9)

Resizing: If you want to resize/reshape tensor, you can use torch.view:

PYTHON · 仅供阅读
x = torch.randn(4, 4)
y = x.view(16)
z = x.view(-1, 8)  # the size -1 is inferred from other dimensions
print(x.size(), y.size(), z.size())
原笔记输出 · 本次未执行
torch.Size([4, 4]) torch.Size([16]) torch.Size([2, 8])

reshape() vs view()

  • 相同之处
    都可以用来重新调整 tensor 的形状。
  • 不同之处
    • view 函数只能用于 contiguous 后的 tensor 上,也就是只能用于内存中连续存储的 tensor。
      如果对 tensor 调用过 transpose, permute 等操作的话会使该 tensor 在内存中变得不再连续,此时就不能再调用 view 函数。因此,需要先使用 contiguous 来返回一个 contiguous copy。
    • reshape 则不需要依赖目标 tensor 是否在内存中是连续的。

整理注: view是否可行取决于目标形状与stride兼容性,并非所有非连续张量都不可view;reshape可能返回视图,也可能复制。

If you have a one element tensor, use .item() to get the value as a Python number

PYTHON · 仅供阅读
x = torch.randn(1)
print(x)
print(x.item())
原笔记输出 · 本次未执行
tensor([0.1756])
0.1756105273962021

11. NumPy Bridge

Converting a Torch Tensor to a NumPy array and vice versa is a breeze.

The Torch Tensor and NumPy array will share their underlying memory locations, and changing one will change the other.

整理注: 共享内存依赖设备、dtype与转换方式;示例是兼容CPU张量。GPU转CPU等复制不保证共享。

  • Converting Torch Tensor to NumPy Array
PYTHON · 仅供阅读
a = torch.ones(5)
print(a)
原笔记输出 · 本次未执行
tensor([1., 1., 1., 1., 1.])
PYTHON · 仅供阅读
b = a.numpy()
print(b)
原笔记输出 · 本次未执行
[1. 1. 1. 1. 1.]

See how the numpy array changed in value.

PYTHON · 仅供阅读
a.add_(1)
print(a)
print(b)
原笔记输出 · 本次未执行
tensor([2., 2., 2., 2., 2.])
[2. 2. 2. 2. 2.]
  • Converting NumPy Array to Torch Tensor

See how changing the np array changed the Torch Tensor automatically

PYTHON · 仅供阅读
a = np.ones(5)
b = torch.from_numpy(a)
np.add(a, 1, out=a)
print(a)
print(b)
原笔记输出 · 本次未执行
[2. 2. 2. 2. 2.]
tensor([2., 2., 2., 2., 2.], dtype=torch.float64)

12. CUDA Tensors

Tensors can be moved onto any device using the .to method.

PYTHON · 仅供阅读
x = torch.tensor([[1,2,3]])
y = torch.tensor([[2,2,2]])
PYTHON · 仅供阅读
# let us run this cell only if CUDA is available
# We will use ``torch.device`` objects to move tensors in and out of GPU
if torch.cuda.is_available():
    device = torch.device("cuda")          # a CUDA device object
    y = torch.ones_like(x, device=device)  # directly create a tensor on GPU
    x = x.to(device)                       # or just use strings ``.to("cuda")``
    z = x + y
    print(z)
    print(z.to("cpu", torch.double))       # ``.to`` can also change dtype together!
原笔记输出 · 本次未执行
tensor([[2, 3, 4]], device='cuda:0')
tensor([[2., 3., 4.]], dtype=torch.float64)

教程出处

本篇部分示例对应PyTorch入门教程,整理时保留章节与代码,修正说明已标注。原许可见PyTorch tutorials BSD-3-Clause。

整理参考资料