张量(Tensor)是一种特殊的数据结构,与数组和矩阵非常相似。在PyTorch中,我们使用张量来编码模型的输入和输出,以及模型的参数。
张量类似于NumPy的ndarrays,除了张量可以在GPU或其他硬件加速器上运行。事实上,张量和NumPy数组通常可以共享相同的底层内存,从而消除了复制数据的需要。Tensor还针对自动微分进行了优化。
1. Tensor初始化
1. 直接使用数据初始化tensor
import torch
import numpy as np
data = [[1, 2],[3, 4]]
x_data = torch.tensor(data)
2. 用np数组初始化tensor
np_array = np.array(data)
x_np = torch.from_numpy(np_array)
3. 使用一个tensor初始化另一个tensor
3.1 创建tensor x_ones,并且值全部为1,x_ones的形状与x_data相同;ones_like这个函数可以方便的根据某个张量的形状创建一个值为全1的tensor
x_ones = torch.ones_like(x_data)
print(f"Ones Tensor: \n {x_ones} \n")
输出:
Ones Tensor:
tensor([[1, 1],
[1, 1]])
3.2 使用x_data创建tensor x_rand,rand_like这个函数使此张量内的值是0-1之间的随机数,dtype可以设置张量的数据类型。
x_rand = torch.rand_like(x_data, dtype=torch.float)
print(f"Random Tensor: \n {x_rand} \n")
输出:
Random Tensor:
tensor([[0.9329, 0.2087],
[0.1134, 0.1782]])
2. 张量的维度
shape是张量维度的元组。在下面的函数中,它决定了输出张量的维度。
shape = (2,3,) #2行、3列
rand_tensor = torch.rand(shape) #值是0-1的随机数
ones_tensor = torch.ones(shape) #值全1
zeros_tensor = torch.zeros(shape) #值全0
print(f"Random Tensor: \n {rand_tensor} \n")
print(f"Ones Tensor: \n {ones_tensor} \n")
print(f"Zeros Tensor: \n {zeros_tensor}")
输出:
Random Tensor:
tensor([[0.2715, 0.6069, 0.7522],
[0.5290, 0.5572, 0.3015]])
Ones Tensor:
tensor([[1., 1., 1.],
[1., 1., 1.]])
Zeros Tensor:
tensor([[0., 0., 0.],
[0., 0., 0.]])
3. 张量的属性
张量属性描述了它们的形状、数据类型和存储它们的设备。
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}") #输出存储张量的设备
输出:
Shape of tensor: torch.Size([3, 4])
Datatype of tensor: torch.float32
Device tensor is stored on: cpu
4. 对张量的操作
有超过100个张量操作,包括算术,线性代数,矩阵操作(转置,索引,切片),采样等。
这些操作中的每一个都可以在GPU上运行(通常比在CPU上运行的速度更高)。
默认情况下,张量在CPU上创建。我们需要使用.to方法显式地将张量移动到GPU(在检查GPU可用性之后)。跨设备复制大型张量在时间和内存方面可能是昂贵的!
# We move our tensor to the GPU if available
if torch.cuda.is_available():
tensor = tensor.to('cuda')
1. 类似Numpy的索引和切片
tensor = torch.ones(4, 4)
print('First row: ',tensor[0])
print('First column: ', tensor[:, 0])
print('Last column:', tensor[..., -1])
tensor[:,1] = 0
print(tensor)
输出:
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.]])
2. 连接张量
使用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. 数学运算
3.1 矩阵乘
# 计算两个张量之间的矩阵乘法。y1, y2, y3将具有相同的值
y1 = tensor @ tensor.T
y2 = tensor.matmul(tensor.T)
y3 = torch.rand_like(tensor)
torch.matmul(tensor, tensor.T, out=y3)
print('y1: ',y1)
print('y2: ',y2)
print('y3: ',y3)
输出:
y1: tensor([[3., 3., 3., 3.],
[3., 3., 3., 3.],
[3., 3., 3., 3.],
[3., 3., 3., 3.]])
y2: tensor([[3., 3., 3., 3.],
[3., 3., 3., 3.],
[3., 3., 3., 3.],
[3., 3., 3., 3.]])
y3: tensor([[3., 3., 3., 3.],
[3., 3., 3., 3.],
[3., 3., 3., 3.],
[3., 3., 3., 3.]])
3.2 矩阵元素乘
# 计算逐元素乘积。z1、z2、z3将具有相同的值
z1 = tensor * tensor
z2 = tensor.mul(tensor)
z3 = torch.rand_like(tensor)
torch.mul(tensor, tensor, out=z3)
print('z1: ',z1)
print('z2: ',z2)
print('z3: ',z3)
输出:
z1: tensor([[1., 0., 1., 1.],
[1., 0., 1., 1.],
[1., 0., 1., 1.],
[1., 0., 1., 1.]])
z2: tensor([[1., 0., 1., 1.],
[1., 0., 1., 1.],
[1., 0., 1., 1.],
[1., 0., 1., 1.]])
z3: tensor([[1., 0., 1., 1.],
[1., 0., 1., 1.],
[1., 0., 1., 1.],
[1., 0., 1., 1.]])
4. 单元素张量
如果你有一个单元素张量,例如通过将张量的所有值聚合成一个值,你可以使用item()将其转换为Python数值:
agg = tensor.sum()
agg_item = agg.item()
print(tensor)
print(agg_item, type(agg_item))
输出:
tensor([[1., 0., 1., 1.],
[1., 0., 1., 1.],
[1., 0., 1., 1.],
[1., 0., 1., 1.]])
12.0 <class 'float'>
5. 就地操作
将结果存储到操作数中的操作称为就地操作。它们用_后缀表示。例如: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. 与Numpy关联
1. CPU和NumPy数组上的张量可以共享它们的底层内存位置,改变一个会改变另一个。
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.]
2. 对tensor的改变,也会反映到numpy数组上
t.add_(1)
print(f"t: {t}")
print(f"n: {n}")
输出:
t: tensor([2., 2., 2., 2., 2.])
n: [2. 2. 2. 2. 2.]
3. 用numpy array初始化tensor
n = np.ones(5)
t = torch.from_numpy(n)
4. 改变numpy array也会改变tensor
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.]