以下内容全部来自 PyTorch tutorials of Tensors
Ⅰ. Tensors 介绍
Tensors 是一种类似于数组和矩阵的数据结构。在 PyTorch 中,通常使用 Tensors 对模型的输入和输出以及模型的参数进行编码。
Tensors 跟 Numpy 的 array 有点类似,但是 Tensor 可以在 GPU 或者其他硬件上加速,除此之外,Tensor 还可以进行自动求导(Autograd)。
导入包:
import torch
import numpy as np
Ⅱ. Tensor 初始化
Tensor 有很多种初始化的方式,如下所示:
1. 直接用数据定义
data = [[1, 2], [3, 4]]
x_data = torch.tensor(data)
2. numpy array 转换
np_array = np.array(data)
x_np = torch.from_numpy(np_array)
3. 来自另一个 Tensor
x_ones = torch.ones_like(x_data)
print(f"Ones Tensor: \n {x_ones} \n")
x_rand = torch.rand_like(x_data, dtype=torch.float)
print(f"Random Tensor: \n {x_rand} \n")
Out:
Ones Tensor:
tensor([[1, 1],
[1, 1]])
Random Tensor:
tensor([[0.2009, 0.8362],
[0.8396, 0.5719]])
注意:除非显式覆盖,否则新的 tensor 保留原来 tensor 的属性(形状、数据类型)
4. 随机初始化或者一些恒定的数值
shape = (2, 3, )
rand_tensor = torch.rand(shape)
ones_tensor = torch.ones(shape)
zeros_tensor = torch.zeros(shape)
print(f"Random Tensor: \n {rand_tensor} \n")
print(f"Ones Tensor: \n {ones_tensor} \n")
print(f"Zeros Tensor: \n {zeros_tensor} \n")
Out:
Random Tensor:
tensor([[0.5702, 0.7394, 0.0426],
[0.3312, 0.7481, 0.9213]])
Ones Tensor:
tensor([[1., 1., 1.],
[1., 1., 1.]])
Zeros Tensor:
tensor([[0., 0., 0.],
[0., 0., 0.]])
Ⅲ. Tensor 的属性
一个 Tensor 有大小,数据类型和存放在哪个设备上。
tensor = torch.rand(3, 4)
print(f"Shape of tensor: {tensor.shape}")
print(f"Datatype of tensor: {tensor.dtype}")
print(f"Device tensor is stored on: {tensor.device}")
Out:
Shape of tensor: torch.Size([3, 4])
Datatype of tensor: torch.float32
Device tensor is stored on: cpu
Ⅳ. Tensors 操作
Tensor 有大量的张量运算方法,包括算术,线性代数,矩阵操作(转置,索引,切片),采样等。
每一个操作都可以在 GPU 上运行,但是默认 Tensor 被创建在 CPU 上,需要手动的移动 Tensor 到 GPU 上进行运算。
注:跨设备复制大 Tensor 很耗时间和内存!
if torch.cuda.is_available():
tensor = tensor.to("cuda")
1. 切片
tensor = torch.ones(4, 4)
print(f"First row: {tensor[0]}")
print(f"First column: {tensor[:, 0]}")
print(f"Last column: {tensor[..., -1]}")
tensor[:,1] = 0
print(tensor)
Out:
First row: tensor([1., 1., 1., 1.])
First column: tensor([1., 1., 1., 1.])
Last column: tensor([1., 1., 1., 1.])
tensor([[1., 0., 1., 1.],
[1., 0., 1., 1.],
[1., 0., 1., 1.],
[1., 0., 1., 1.]])
切片类似于 NumPy 的切片,可以参考科学计算NumPy
2. Tensor 拼接
t1 = torch.cat([tensor, tensor, tensor], dim=1)
print(t1)
Out:
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.]])
除了 Tensor 拼接外,还一个 torch.stack Tensor 连接操作,这个是一个与 torch.cat 有所不同的操作。
简而言之:torch.cat
和 toch.stack
的区别在于 cat 会增加现有维度的值,可以理解为续接,stack 会新加增加一个维度,可以理解为叠加。
3. 算术运算
y1 = tensor @ tensor.T
y2 = tensor.matmul(tensor.T)
y3 = torch.rand_like(y1)
torch.matmul(tensor, tensor.T, out=y3)
z1 = tensor * tensor
z2 = tensor.mul(tensor)
z3 = torch.rand_like(tensor)
torch.mul(tensor, tensor, out=z3)
Out:
tensor([[1., 0., 1., 1.],
[1., 0., 1., 1.],
[1., 0., 1., 1.],
[1., 0., 1., 1.]])
4. 单个元素 Tensor
对于单张 Tensor ,通过 .sum()
可以将其聚合成一个值,然后使用 item()
将其转换为数值。
agg = tensor.sum()
print(f"agg {agg}")
agg_item = agg.item()
print(agg_item, type(agg_item))
Out:
agg 12.0
12.0 <class 'float'>
5. 原地操作
若一个操作以 _
作为后缀就表示这是一个原地操作。比如:x.copy_(x), x.t_()
这些都将改变 x
的值。
print(f"{tensor} \n")
tensor.add_(5)
print(tensor)
Out:
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.]])
Ⅴ. Tensor 与 NumPy 之间的桥梁
1. Tensor to NumPy array
由 Tensor 转换成的 Numpy array,若是 Tensor 变化,则 Numpy array 也会改变。
t = torch.ones(5)
print(f"t: {t}")
n = t.numpy()
print(f"n: {n}")
Out:
t: tensor([1., 1., 1., 1., 1.])
n: [1. 1. 1. 1. 1.]
t.add_(1)
print(f"t: {t}")
print(f"n: {n}")
Out:
t: tensor([2., 2., 2., 2., 2.])
n: [2. 2. 2. 2. 2.]
2. NumPy array to Tensor
反过来,由 NumPy array 转换成的 Tensor,若是 Numpy array 变化,则 Tensor 也会改变。
n = np.ones(5)
t = torch.from_numpy(n)
np.add(n, 1, out=n)
print(f"t: {t}")
print(f"n: {n}")
Out:
t: tensor([2., 2., 2., 2., 2.], dtype=torch.float64)
n: [2. 2. 2. 2. 2.]