1. 张量 Tensor
张量是一个统称,其中包括很多类型:
0 阶张量:标量、常数,0-D Tensor
1 阶张量:向量,1-D Tensor
2 阶张量:矩阵,2-D Tensor
3 阶张量
...
n 阶张量
2. PyTorch 中张量的创建
使用 python 中的列表或序列创建张量
import torcha = torch.tensor([[1, -1], [2, 3]])
print(a, type(a))# 输出结果
tensor([[ 1, -1],[ 2, 3]])
使用 numpy 中的数组创建张量
import torch
import numpy as npa = torch.tensor(np.array([[1, -1], [2, 3]]))
print(a, type(a))# 输出结果
tensor([[ 1, -1],[ 2, 3]], dtype=torch.int32)
使用 torch 中的 api 创建张量
# 创建3x4的空张量,用无用数据填充
torch.empty(3, 4)
# 创建3x4的全是1的张量
torch.ones([3, 4])
# 创建3x4的全是0的张量
torch.zeros([3, 4])
# 创建3x4的全是随机数的张量,随机区间[0, 1)
torch.rand([3, 4])
# 创建3x4的随机整数张量,随机区间[low, high)
torch.randint(low=0, high=10, size=[3, 4])
# 创建3x4的随机数张量,随机值得分布均值为0,方差为1
torch.randn([3, 4])
3. PyTorch 中的常用方法
tensor.item() 从张量中获取数据(当张量中仅有一个数据可用)
import torch
import numpy as npa = torch.tensor(np.arange(1))
print(a)
print(a.item())# 输出结果
tensor([0], dtype=torch.int32)
0
转化为 numpy 数组
import torch
import numpy as npa = torch.tensor(np.array([[1, -1], [2, 3]]))
print(a)
print(a.numpy())# 输出结果
tensor([[ 1, -1],[ 2, 3]], dtype=torch.int32)
[[ 1 -1][ 2 3]]
tensor.size() 获取张量形状
import torch
import numpy as npa = torch.tensor(np.array([[1, -1], [2, 3]]))
print(a)
print(a.size())# 输出结果
tensor([[ 1, -1],[ 2, 3]], dtype=torch.int32)
torch.Size([2, 2])
tensor.view() 改变张量形状,浅拷贝,仅仅改变形状
import torch
import numpy as npa = torch.tensor(np.array([[1, -1], [2, 3]]))
print(a)
b = a.view((1, 4))
print(b)# 输出结果
tensor([[ 1, -1],[ 2, 3]], dtype=torch.int32)
tensor([[ 1, -1, 2, 3]], dtype=torch.int32)
tensor.dim() 获取维数
tensor.max() 获取最大值
tensor.min() 获取最小值
tensor.std() 获取标准差
tensor.t() / tensor.transpose() 转置
import torch
import numpy as npa = torch.tensor(np.array([[1, -1], [2, 3]]))
print(a)
print(a.dim())
print(a.max())
print(a.t())# 输出结果
tensor([[ 1, -1],[ 2, 3]], dtype=torch.int32)
2
tensor(3, dtype=torch.int32)
tensor([[ 1, 2],[-1, 3]], dtype=torch.int32)
tensor[1, 3] 获取张量中第一行第三列的值(从 0 行 0 列开始)
tensor[1, 3]=100 对张量中第一行第三列的位置赋值 100
tensor[1, 2, 0] 切片
import torch
import numpy as npa = torch.tensor(np.array([[1, -1], [2, 3]]))
print(a[1, 0])
a[1, 0] = 100
print(a)# 输出结果
tensor(2, dtype=torch.int32)
tensor([[ 1, -1],[100, 3]], dtype=torch.int32)
4. Tensor 的数据类型
常用的不同数据类型的 Tensor,有 32 位的浮点型 torch.FloatTensor, 64 位浮点型 torch.DoubleTensor, 16 位整形 torch.ShortTensor, 32 位整形 torch.IntTensor 和 64 位整形 torch.LongTensor。
关于数据类型的常用方法:
tensor.dtype 获取张量的数据类型
import torch
import numpy as npa = torch.tensor(np.array([[1, -1], [2, 3]]))
print(a, a.dtype)# 输出结果
tensor([[ 1, -1],[ 2, 3]], dtype=torch.int32) torch.int32
创建张量时指定数据类型
import torch
import numpy as npa = torch.tensor(np.array([[1, -1], [2, 3]]), dtype=torch.float32)
print(a, a.dtype)# 输出结果
tensor([[ 1., -1.],[ 2., 3.]]) torch.float32
修改数据类型
import torch
import numpy as npa = torch.tensor(np.array([[1, -1], [2, 3]]), dtype=torch.int32)
print(a, a.dtype)
a = a.type(torch.float)
print(a, a.dtype)# 输出结果
tensor([[ 1, -1],[ 2, 3]], dtype=torch.int32) torch.int32
tensor([[ 1., -1.],[ 2., 3.]]) torch.float32