2021SC@SDUSC
张量如同数组和矩阵一样, 是一种特殊的数据结构。在PyTorch
中, 神经网络的输入、输出以及网络的参数等数据, 都是使用张量来进行描述。
张量的使用和Numpy
中的ndarrays
很类似, 区别在于张量可以在GPU
或其它专用硬件上运行, 这样可以得到更快的加速效果
张量的初始化:
1.直接生成张量
data = [[1, 2], [3, 4]]
x_data = torch.tensor(data)
2.通过numpy数组来生成张量
np_array = np.array(data)
x_np = torch.from_numpy(np_array)
3.通过已有的张量来生成新的张量(新的张量将会继承原来张量的属性类型,也可以对其进行重写)
x_ones = torch.ones_like(x_data) # 保留 x_data 的属性
print(f"Ones Tensor: \n {x_ones} \n")
x_rand = torch.rand_like(x_data, dtype=torch.float) # 重写 x_data 的数据类型
int -> float
print(f"Random Tensor: \n {x_rand} \n")
4.通过指定数据维度来生成张量
shape
是元组类型, 用来描述张量的维数, 下面3个函数通过传入shape
来指定生成张量的维数。
shape = (2,3,)
rand_tensor = torch.rand(shape)
ones_tensor = torch.ones(shape)
zeros_tensor = torch.zeros(shape)
张量的属性(维度,数据类型,存储设备)
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 # 存储设备
张量运算
有超过100种张量相关的运算操作, 例如转置、索引、切片、数学运算、线性代数、随机采样等。
# 判断当前环境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
方法将一组张量按照指定的维度进行拼接
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.]])
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.]])
参考https://pytorch.apachecn.org/#/https://pytorch.apachecn.org/#/