(二)Tensor 的数据、形状与类型
先把两条记录、每条三个数存起来。NumPy 用 ndarray 表达这件事,PyTorch 使用 Tensor,中文通常称为张量。
# 项目文件:demos/tensors.py
import torch
# 第一维是两条样本,第二维是每条样本的三个特征。
x = torch.tensor([[1, 2, 3], [4, 5, 6]], dtype=torch.float32)
print("形状", tuple(x.shape), "维数", x.ndim, "元素数", x.numel())
print("类型", x.dtype, "设备", x.device)
print("第二条", x[1].tolist(), "第二个特征", x[:, 1].tolist())
print("按特征均值", x.mean(dim=0).tolist())
print("增加通道", tuple(x.unsqueeze(1).shape))这里的 shape=(2, 3) 表示外层两条、每条三个数;ndim=2 表示有两根轴;numel()=6 表示总共有六个元素。轴的含义来自我们怎样组织数据,张量本身只保存长度、布局、类型和所在设备等信息。
dtype=torch.float32 指定单精度浮点数。模型的输入和可训练参数常用浮点数;类别编号使用整数,后面会把它与分类损失联系起来。device=cpu 表示数据当前在内存中由 CPU 处理。
dim 对应 NumPy 中的 axis。对这份 (2, 3) 数据执行 mean(dim=0),会合并两条记录,留下三个特征均值 [2.5, 3.5, 4.5]。unsqueeze(1) 在编号为 1 的位置插入长度为 1 的轴,形状变为 (2, 1, 3),元素数量仍是六个。