[Pytorch框架] 1.3、张量

PyTorch是什么?

基于Python的科学计算包,服务于以下两种场景:

  • 作为NumPy的替代品,可以使用GPU的强大计算能力
  • 提供最大的灵活性和高速的深度学习研究平台

Tensors(张量)

Tensors与Numpy中的 ndarrays类似,但是在PyTorch中
Tensors 可以使用GPU进行计算.

from __future__ import print_function
import torch

创建一个 5x3 矩阵, 但是未初始化:

x = torch.empty(5, 3)
print(x)
tensor([[0., 0., 0.],
        [0., 0., 0.],
        [0., 0., 0.],
        [0., 0., 0.],
        [0., 0., 0.]])

创建一个随机初始化的矩阵:

x = torch.rand(5, 3)
print(x)
tensor([[0.9150, 0.7657, 0.8546],
        [0.3395, 0.7662, 0.0313],
        [0.7757, 0.0178, 0.3521],
        [0.3413, 0.9466, 0.1630],
        [0.8141, 0.1705, 0.0776]])

创建一个0填充的矩阵,数据类型为long:

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]])

创建tensor并使用现有数据初始化:

x = torch.tensor([5.5, 3])
print(x)
tensor([5.5000, 3.0000])

根据现有的张量创建张量。 这些方法将重用输入张量的属性,例如, dtype,除非设置新的值进行覆盖

x = x.new_ones(5, 3, dtype=torch.double)      # new_* 方法来创建对象
print(x)

x = torch.randn_like(x, dtype=torch.float)    # 覆盖 dtype!
print(x)                                      #  对象的size 是相同的,只是值和类型发生了变化
tensor([[1., 1., 1.],
        [1., 1., 1.],
        [1., 1., 1.],
        [1., 1., 1.],
        [1., 1., 1.]], dtype=torch.float64)
tensor([[ 1.1297,  0.1577, -0.7850],
        [ 0.5521,  1.1847,  0.6533],
        [ 1.0695, -0.6460,  0.1133],
        [ 0.1926, -0.5291, -0.7003],
        [ 0.4813, -1.7848, -1.0248]])

获取 size

译者注:使用size方法与Numpy的shape属性返回的相同,张量也支持shape属性,后面会详细介绍

print(x.size())
torch.Size([5, 3])

Note

``torch.Size`` 返回值是 tuple类型, 所以它支持tuple类型的所有操作.

操作

操作有多种语法。

我们将看一下加法运算。

加法1:

y = torch.rand(5, 3)
print(x + y)
tensor([[ 1.2431,  0.5113, -0.1128],
        [ 0.5706,  1.3514,  0.7406],
        [ 1.1418,  0.2117,  0.6874],
        [ 0.9976, -0.1778, -0.5245],
        [ 1.1259, -1.3210, -0.4456]])

加法2

print(torch.add(x, y))
tensor([[ 1.2431,  0.5113, -0.1128],
        [ 0.5706,  1.3514,  0.7406],
        [ 1.1418,  0.2117,  0.6874],
        [ 0.9976, -0.1778, -0.5245],
        [ 1.1259, -1.3210, -0.4456]])

提供输出tensor作为参数

result = torch.empty(5, 3)
torch.add(x, y, out=result)
print(result)
tensor([[ 1.2431,  0.5113, -0.1128],
        [ 0.5706,  1.3514,  0.7406],
        [ 1.1418,  0.2117,  0.6874],
        [ 0.9976, -0.1778, -0.5245],
        [ 1.1259, -1.3210, -0.4456]])

替换

# adds x to y
y.add_(x)
print(y)
tensor([[ 1.2431,  0.5113, -0.1128],
        [ 0.5706,  1.3514,  0.7406],
        [ 1.1418,  0.2117,  0.6874],
        [ 0.9976, -0.1778, -0.5245],
        [ 1.1259, -1.3210, -0.4456]])

Note

任何 以``_`` 结尾的操作都会用结果替换原变量. 例如: ``x.copy_(y)``, ``x.t_()``, 都会改变 ``x``.

你可以使用与NumPy索引方式相同的操作来进行对张量的操作

print(x[:, 1])
tensor([ 0.1577,  1.1847, -0.6460, -0.5291, -1.7848])

torch.view: 可以改变张量的维度和大小

译者注:torch.view 与Numpy的reshape类似

x = torch.randn(4, 4)
y = x.view(16)
z = x.view(-1, 8)  #  size -1 从其他维度推断
print(x.size(), y.size(), z.size())
torch.Size([4, 4]) torch.Size([16]) torch.Size([2, 8])

如果你有只有一个元素的张量,使用.item()来得到Python数据类型的数值

x = torch.randn(1)
print(x)
print(x.item())
tensor([2.3180])
2.317981481552124

Read later:

100+ Tensor operations, including transposing, indexing, slicing,
mathematical operations, linear algebra, random numbers, etc.,
are described
here <https://pytorch.org/docs/torch>_.

NumPy 转换

将一个Torch Tensor转换为NumPy数组是一件轻松的事,反之亦然。

Torch Tensor与NumPy数组共享底层内存地址,修改一个会导致另一个的变化。

将一个Torch Tensor转换为NumPy数组

a = torch.ones(5)
print(a)
tensor([1., 1., 1., 1., 1.])
b = a.numpy()
print(b)
[1. 1. 1. 1. 1.]

观察numpy数组的值是如何改变的。

a.add_(1)
print(a)
print(b)
tensor([2., 2., 2., 2., 2.])
[2. 2. 2. 2. 2.]

NumPy Array 转化成 Torch Tensor

使用from_numpy自动转化

import numpy as np
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)

所有的 Tensor 类型默认都是基于CPU, CharTensor 类型不支持到
NumPy 的转换.

CUDA 张量

使用.to 方法 可以将Tensor移动到任何设备中

# is_available 函数判断是否有cuda可以使用
# ``torch.device``将张量移动到指定的设备中
if torch.cuda.is_available():
    device = torch.device("cuda")          # a CUDA 设备对象
    y = torch.ones_like(x, device=device)  # 直接从GPU创建张量
    x = x.to(device)                       # 或者直接使用``.to("cuda")``将张量移动到cuda中
    z = x + y
    print(z)
    print(z.to("cpu", torch.double))       # ``.to`` 也会对变量的类型做更改
posted @ 2021-01-22 20:03  野哥李  阅读(4)  评论(0编辑  收藏  举报  来源