在数学中,一个单独的数可以成为标量,一列或者一行数组可以称为向量,一个二维数组成为矩阵,矩阵中的每一个元素都可以被行和列的索引唯一确定,如果数组的维度超过2,那么我们可以称该数组为张量。但是在 pytorch 中,张量属于一种数据结构,它可以是一个标量、一个向量、一个矩阵,甚至是更高维的数组,所以 pytorch 中 tensor 和 numpy 库中的数组 ndarray 非常相似,在使用时也会经常将 pytorch 的相关计算和优化都是在 tensor 的基础上完成的。
在 torch 中 CPU 和 GPU 张量分别有 8 种数据类型
| 数据类型 | dtype | CPU tensor | GPU tensor |
|---|---|---|---|
| 32 位浮点型 | torch.float32 或 torch.float | torch.FloatTensor | torch.cuda.FloatTensor |
| 64 位浮点型 | torch.float64 或 torch.double | torch.DoubleTensor | torch.cuda.DoubleTensor |
| 16 位浮点型 | torch.float16 或 torch.half | torch.HalfTensor | torch.cuda.HalfTensor |
| 8 位无符号整型 | torch.uint8 | torch.ByteTensor | torch.cuda.ByteTensor |
| 8 位有符号整型 | torch.int8 | torch.CharTensor | torch.cuda.CharTensor |
| 16 位有符号整型 | torch.int16 或 torch.short | torch.ShortTensor | torch.cuda.ShortTensor |
| 32 位有符号整型 | torch.int32 或 torch.int | torch.IntTensor | torch.cuda.IntTensor |
| 64 位有符号整型 | torch.int64 或 torch.long | torch.LongTensor | torch.cuda.LongTensor |



