1. 文章
  2. 文章详情

PyTorch入门-张量

Tensors (张量)创建

几何代数中定义的张量是基于向量和矩阵的推广,我们可以将标量视为零阶张量,矢量视为一阶张量,那么矩阵就是二阶张量。在PyTorch中,张量Tensor是最基础的运算单位,与NumPy中的NDArray类似,张量表示的是一个多维矩阵。不同的是,PyTorch中的Tensor可以运行在GPU上,而NumPy的NDArray只能运行在CPU上。由于Tensor能在GPU上运行,因此大大加快了运算速度。

from __future__ import print_function
import torch

构造一个5x3矩阵,不初始化。

x = torch.empty(5, 3)
print(x)

输出:

tensor(1.00000e-04 *
       [[-0.0000,  0.0000,  1.5135],
        [ 0.0000,  0.0000,  0.0000],
        [ 0.0000,  0.0000,  0.0000],
        [ 0.0000,  0.0000,  0.0000],
        [ 0.0000,  0.0000,  0.0000]])

构造一个随机初始化的矩阵:

x = torch.rand(5, 3)
print(x)

输出:

tensor([[ 0.6291,  0.2581,  0.6414],
        [ 0.9739,  0.8243,  0.2276],
        [ 0.4184,  0.1815,  0.5131],
        [ 0.5533,  0.5440,  0.0718],
        [ 0.2908,  0.1850,  0.5297]])

构造一个矩阵全为 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]])

构造一个张量,直接使用数据:

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

输出:

tensor([ 5.5000,  3.0000])

创建一个 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([[ 1.,  1.,  1.],
        [ 1.,  1.,  1.],
        [ 1.,  1.,  1.],
        [ 1.,  1.,  1.],
        [ 1.,  1.,  1.]], dtype=torch.float64)
tensor([[-0.2183,  0.4477, -0.4053],
        [ 1.7353, -0.0048,  1.2177],
        [-1.1111,  1.0878,  0.9722],
        [-0.7771, -0.2174,  0.0412],
        [-2.1750,  1.3609, -0.3322]])

获取它的维度信息:

print(x.size())

输出:

torch.Size([5, 3])

注意

torch.Size  是一个元组,所以它支持左右的元组操作。

NumPy数组与Tensors

张量可以由GPU(或TPU)支持。

张量是不可变的。

NumPy兼容性: 在TensorFlow tf.Tensors和NumPy ndarray之间转换很容易。

Tensor可以保持在GPU显存中,而NumPy阵列总是由主机内存支持,并且转换涉及从GPU到主机内存的复制。

Tensor与Numpy的转化

张量和Numpy array数组在CPU上可以共用一块内存区域, 改变其中一个另一个也会随之改变。 

1. 由张量变换为Numpy array数组

t = torch.ones(5)
print(f"t: {t}")
n = t.numpy()
print(f"n: {n}")

显示:

t: tensor([1., 1., 1., 1., 1.])
n: [1. 1. 1. 1. 1.]

修改张量的值,则Numpy array数组值也会随之改变。

t.add_(1)
print(f"t: {t}")
print(f"n: {n}")

显示:

t: tensor([2., 2., 2., 2., 2.])
n: [2. 2. 2. 2. 2.]

2. 由Numpy array数组转为张量

n = np.ones(5)
t = torch.from_numpy(n)

修改Numpy array数组的值,则张量值也会随之改变。

np.add(n, 1, out=n)
print(f"t: {t}")
print(f"n: {n}")

显示:

t: tensor([2., 2., 2., 2., 2.], dtype=torch.float64)
n: [2. 2. 2. 2. 2.]

张量的运算

有超过100种张量相关的运算操作, 例如转置、索引、切片、数学运算、线性代数、随机采样等。更多的运算可以在这里查看

所有这些运算都可以在GPU上运行(相对于CPU来说可以达到更高的运算速度)。如果你使用的是Google的Colab环境, 可以通过 Edit > Notebook Settings 来分配一个GPU使用。

# 判断当前环境GPU是否可用, 然后将tensor导入GPU内运行
if torch.cuda.is_available():
  tensor = tensor.to('cuda')

1. 张量的索引和切片

tensor = torch.ones(4, 4)
tensor[:,1] = 0            # 将第1列(从0开始)的数据全部赋值为0
print(tensor)

显示:

tensor([[1., 0., 1., 1.],
        [1., 0., 1., 1.],
        [1., 0., 1., 1.],
        [1., 0., 1., 1.]])

2. 张量的拼接

你可以通过torch.cat方法将一组张量按照指定的维度进行拼接, 也可以参考torch.stack方法。这个方法也可以实现拼接操作, 但和torch.cat稍微有点不同。

t1 = torch.cat([tensor, tensor, tensor], dim=1)
print(t1)

显示:

tensor([[1., 0., 1., 1., 1., 0., 1., 1., 1., 0., 1., 1.],
        [1., 0., 1., 1., 1., 0., 1., 1., 1., 0., 1., 1.],
        [1., 0., 1., 1., 1., 0., 1., 1., 1., 0., 1., 1.],
        [1., 0., 1., 1., 1., 0., 1., 1., 1., 0., 1., 1.]])

3. 张量的乘积和矩阵乘法

# 逐个元素相乘结果
print(f"tensor.mul(tensor): \n {tensor.mul(tensor)} \n")
# 等价写法:
print(f"tensor * tensor: \n {tensor * tensor}")

显示:

tensor.mul(tensor):
 tensor([[1., 0., 1., 1.],
        [1., 0., 1., 1.],
        [1., 0., 1., 1.],
        [1., 0., 1., 1.]])

tensor * tensor:
 tensor([[1., 0., 1., 1.],
        [1., 0., 1., 1.],
        [1., 0., 1., 1.],
        [1., 0., 1., 1.]])

下面写法表示张量与张量的矩阵乘法:

print(f"tensor.matmul(tensor.T): \n {tensor.matmul(tensor.T)} \n")
# 等价写法:
print(f"tensor @ tensor.T: \n {tensor @ tensor.T}")

显示:

tensor.matmul(tensor.T):
 tensor([[3., 3., 3., 3.],
        [3., 3., 3., 3.],
        [3., 3., 3., 3.],
        [3., 3., 3., 3.]])

tensor @ tensor.T:
 tensor([[3., 3., 3., 3.],
        [3., 3., 3., 3.],
        [3., 3., 3., 3.],
        [3., 3., 3., 3.]])

4. 自动赋值运算

自动赋值运算通常在方法后有 _ 作为后缀, 例如: x.copy_(y)x.t_()操作会改变 x 的取值。

print(tensor, "\n")
tensor.add_(5)
print(tensor)

显示:

tensor([[1., 0., 1., 1.],
        [1., 0., 1., 1.],
        [1., 0., 1., 1.],
        [1., 0., 1., 1.]])

tensor([[6., 5., 6., 6.],
        [6., 5., 6., 6.],
        [6., 5., 6., 6.],
        [6., 5., 6., 6.]])

注意:

自动赋值运算虽然可以节省内存, 但在求导时会因为丢失了中间过程而导致一些问题, 所以我们并不鼓励使用它。

5. 张量加法

加法: 方式 1

y = torch.rand(5, 3)
print(x + y)

Out:

tensor([[-0.1859,  1.3970,  0.5236],
        [ 2.3854,  0.0707,  2.1970],
        [-0.3587,  1.2359,  1.8951],
        [-0.1189, -0.1376,  0.4647],
        [-1.8968,  2.0164,  0.1092]])

加法: 方式2

print(torch.add(x, y))

Out:

tensor([[-0.1859,  1.3970,  0.5236],
        [ 2.3854,  0.0707,  2.1970],
        [-0.3587,  1.2359,  1.8951],
        [-0.1189, -0.1376,  0.4647],
        [-1.8968,  2.0164,  0.1092]])

加法: 提供一个输出 tensor 作为参数

result = torch.empty(5, 3)
torch.add(x, y, out=result)
print(result)

Out:

tensor([[-0.1859,  1.3970,  0.5236],
        [ 2.3854,  0.0707,  2.1970],
        [-0.3587,  1.2359,  1.8951],
        [-0.1189, -0.1376,  0.4647],
        [-1.8968,  2.0164,  0.1092]])

加法: in-place

# adds x to y
y.add_(x)
print(y)

Out:

tensor([[-0.1859,  1.3970,  0.5236],
        [ 2.3854,  0.0707,  2.1970],
        [-0.3587,  1.2359,  1.8951],
        [-0.1189, -0.1376,  0.4647],
        [-1.8968,  2.0164,  0.1092]])

Note

注意 任何使张量会发生变化的操作都有一个前缀 '_'。例如:x.copy_(y)x.t_(), 将会改变 x.

你可以使用标准的  NumPy 类似的索引操作

print(x[:, 1])

Out:

tensor([ 0.4477, -0.0048,  1.0878, -0.2174,  1.3609])

改变大小:如果你想改变一个 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())

Out:

torch.Size([4, 4]) torch.Size([16]) torch.Size([2, 8])

如果你有一个元素 tensor ,使用 .item() 来获得这个 value 。

x = torch.randn(1)
print(x)
print(x.item())

Out:

tensor([ 0.9422])
0.9422121644020081

发表评论

登录后才能评论

评论列表(0条)