4. PyTorch基础

Tensors

Tensor类似与NumPy的ndarray,唯一的区别是Tensor可以在GPU上加速运算。

构建Tensor

  • 导入
from __future__ import print_function
import torch
  • 构造未初始化的5x3矩阵
x = torch.empty(5, 3)
print(x)

未初始化的5x3矩阵

  • 构建一个随机初始化的5x3矩阵
x = torch.rand(5, 3)
print(x)

随机初始化的5x3矩阵

  • 构建一个全部为0,类型为long的矩阵
x = torch.zeros(5, 3, dtype=torch.long)
print(x)

全部为0,类型为long的矩阵

  • 从数据直接直接构建tensor
x = torch.tensor([5.5, 3])
print(x)

从数据直接直接构建

  • 从一个已有的tensor构建一个tensor。这些方法会重用原来tensor的特征,例如,数据类型,除非提供新的数据。
x = x.new_ones(5, 3, dtype=torch.double)      # new_* methods take in sizes
print(x)

x = torch.randn_like(x, dtype=torch.float)    # override dtype!
print(x)                                      # result has the same size

从一个已有的tensor构建

  • 得到tensor的形状
print(x.size())

形状

torch.Size 返回的是一个元组(tuple)

Tensor运算

  • 加法运算
y = torch.rand(5, 3)
print(x + y)

x+y

  • 另一种着加法的写法
print(torch.add(x, y))

x+y

  • 把输出作为一个变量
result = torch.empty(5, 3)
torch.add(x, y, out=result)
print(result)

result

  • in-place加法
# adds x to y
y.add_(x)
print(y)

add_()

任何in-place的运算都会以_结尾。 举例来说:x.copy_(y), x.t_(), 会改变 x

  • 各种类似NumPy的indexing都可以在PyTorch tensor上面使用
print(x)
print(x[:, 1])

切片

  • 如果你希望resize/reshape一个tensor,可以使用torch.view
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())

resize

  • 如果你有一个只有一个元素的tensor,使用.item()方法可以把里面的value变成Python数值。
x = torch.randn(1)
print(x)
print(x.item())

.item()

  • 各种Tensor operations, 包括transposing, indexing, slicing, mathematical operations, linear algebra, random numbers
    https://pytorch.org/docs/torch

Numpy和Tensor之间的转化

在Torch Tensor和NumPy array之间相互转化非常容易。

Torch Tensor和NumPy array会共享内存,所以改变其中一项也会改变另一项。
共享内存展示

  • 把Torch Tensor转变成NumPy Array
a = torch.ones(5)
print(a)

Torch Tensor

b = a.numpy()
print(b)

array

  • 改变numpy array里面的值
a.add_(1)
print(a)
print(b)

change_val

  • 把NumPy array转成Torch Tensor
import numpy as np
a = np.ones(5)
b = torch.from_numpy(a)
np.add(a, 1, out=a)
print(a)
print(b)

array -> tensor

所有CPU上的Tensor都支持转成numpy或者从numpy转成Tensor

CUDA Tensors

使用.to方法,Tensor可以被移动到别的device上。

# 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!

.to()

如果tensor在GPU上,无法使用转换为numpy。
cpu_numpy

在gpu运算模型

发布了12 篇原创文章 · 获赞 0 · 访问量 38

猜你喜欢

转载自blog.csdn.net/qq_35283167/article/details/104639814
今日推荐