0. 目录
- Tensor 简介
- 创建 Tensor
- 单个 Tensor 的操作
- 两个 Tensor 间操作
- Tensor 和 Numpy 互操作
- Tensor 转为 GPU Tensor
1. Tensor 简介
Tensor 是 PyTorch 中重要的数据结构。可以把 Tensor 理解为一个高维数组。
Tensor 可以是一个数(标量)、一维数组(向量)、二维数组(矩阵)或更高维的数组。
import torch
2. 创建 Tensor
① 直接构造:
x = torch.tensor([5, 2, 0])
print(x)
tensor([5, 2, 0])
x = torch.tensor([[5, 2, 0], [2, 5, 0]])
print(x)
tensor([[5, 2, 0],
[2, 5, 0]])
② [0, 1] 均匀分布随机初始化 Tensor:
x = torch.rand([3, 4])
print(x)
tensor([[0.2243, 0.9589, 0.1012, 0.5025],
[0.2722, 0.6426, 0.8190, 0.3579],
[0.4929, 0.7538, 0.0033, 0.7509]])
③ 初始化元素全部为 0 的 Tensor:
x = torch.zeros([5, 3])
print(x)
tensor([[0., 0., 0.],
[0., 0., 0.],
[0., 0., 0.],
[0., 0., 0.],
[0., 0., 0.]])
创建一个 Tensor 后,如下方法判断变量是否为 Tensor:
print(torch.is_tensor(x))
True
3. 单个 Tensor 的操作
① 查看 Tensor 的形状:
x = torch.zeros([3, 4]) # 创建一个 Tensor
print(x.size()) # 打印 x 的形状
torch.Size([3, 4])
② 修改 Tensor 的形状:(元素的个数保持一致)
x_view = x.view([4, -1]) # 修改该 Tensor 的形状,-1表示自动补齐,这里 -1 相当于 3
print(x_view.size()) # 打印修改后 Tensor 的形状
print(x.size()) # 注意 x 本身的形状不发生改变
torch.Size([4, 3])
torch.Size([3, 4])
③ 修改 Tensor 部分元素的值:
x = torch.ones([2, 3]) # 创建一个元素值都为一的 Tensor
print(x)
x[1,1] = 0 # 下标为[1, 1]的元素值改为 0
print(x)
x[0, :] = 2 # 切片操作,与numpy中的操作类似,这里是将第一行所有元素值改为 2
print(x)
tensor([[1., 1., 1.],
[1., 1., 1.]])
tensor([[1., 1., 1.],
[1., 0., 1.]])
tensor([[2., 2., 2.],
[1., 0., 1.]])
4. 两个 Tensor 间操作
两个 Tensor 相加:
x = torch.tensor([[1, 2], [3, 4]])
y = torch.tensor([[2, 3], [4, 5]])
z1 = x + y
z2 = torch.add(x, y)
print(z1)
print(z2)
tensor([[3, 5],
[7, 9]])
tensor([[3, 5],
[7, 9]])
print(x)
# 观察一下两种方式有何区别
x.add(y)
print(x)
x.add_(y)
print(x)
tensor([[1, 2],
[3, 4]])
tensor([[1, 2],
[3, 4]])
tensor([[3, 5],
[7, 9]])
注:函数名后面带“”的函数会修改 Tensor 本身。不带“”的会返回一个新的 Tensor,而本身不变。
其他操作读者可举一反三:
tensor3 = torch.sub(tensor1, tensor2) # 减
tensor4 = torch.mul(tensor1, tensor2) # 乘
tensor5 = torch.div(tensor1, tensor2) # 矩阵点除
tensor6 = torch.matmul(tensor1, tensor2) # 矩阵乘
5. Tensor 和 Numpy 互操作
Tensor 和 numpy 间的互操作十分容易和快速。Tensor 不支持的操作,可以先转为 numpy 数组处理,之后再转回 Tensor
① Tensor 转 numpy:
x = torch.rand([2, 2]) # 随机初始化一个 Tensor
y = x.numpy() # Tensor 转 numpy
print(x)
print(y)
tensor([[0.5345, 0.5730],
[0.4347, 0.8068]])
[[0.53450364 0.5730201 ]
[0.43467194 0.8068322 ]]
② numpy 转 Tenosr:
import numpy as np
x = np.ones([2, 2]) # 随机初始化一个 numpy
y = torch.from_numpy(x) # numpy 转 Tensor
print(x)
print(y)
[[1. 1.]
[1. 1.]]
tensor([[1., 1.],
[1., 1.]], dtype=torch.float64)
6. Tensor 转为 GPU Tensor
Tensor 可通过 .cuda 方法转为 GPU 的 Tensor,从而可以享受 GPU 带来的加速运算:
x = torch.ones([3, 3])
y = torch.ones([3, 3])
if torch.cuda.is_available(): # 支持GPU返回True,不支持返回False
x.cuda()
y.cuda()
z = x + y
print(z)
tensor([[2., 2., 2.],
[2., 2., 2.],
[2., 2., 2.]])
文章转载自:https://blog.csdn.net/qq_41805511/article/details/92412778