大数跨境

Tensor:PyTorch中最基础的计算单元

Tensor:PyTorch中最基础的计算单元 知识代码AI
2026-08-20
5
导读:Tensor:PyTorch中最基础的计算单元一、什么是TensorTensor(张量) 是 PyTorch

Tensor:PyTorch中最基础的计算单元


一、什么是Tensor

Tensor(张量) 是 PyTorch 中极为基础的数据存储和处理结构,也是深度学习框架中最核心的概念之一。

标量、向量、矩阵与Tensor的关系

名称
英文
说明
Rank(秩)
标量
Scalar
只有大小、没有方向的量,如1.8、e、10
Rank 0 阶 Tensor
向量
Vector
有大小也有方向的量,如(1,2,3,4)
Rank 1 阶 Tensor
矩阵
Matrix
多个向量合并在一起,如[(1,2,3),(4,5,6)]
Rank 2 阶 Tensor

标量可以组合成向量,向量可以组合成矩阵。在 PyTorch 中,统一称为张量(Tensor),用 Rank(秩) 表示"维度"。


二、Tensor的常用数据类型

数据类型
dtype
CPU tensor
32-bit 浮点
torch.float32
 或 torch.float
torch.FloatTensor
64-bit 浮点
torch.float64
 或 torch.double
torch.DoubleTensor
16-bit 浮点
torch.float16
 或 torch.half
torch.HalfTensor
8-bit 无符号整数
torch.uint8
torch.ByteTensor
8-bit 有符号整数
torch.int8
torch.CharTensor
16-bit 整数
torch.int16
 或 torch.short
torch.ShortTensor
32-bit 整数
torch.int32
 或 torch.int
torch.IntTensor
64-bit 整数
torch.int64
 或 torch.long
torch.LongTensor
布尔型
torch.bool
torch.BoolTensor

实际使用中,torch.float32torch.float64torch.uint8 和 torch.int64 用得相对较多,需根据实际情况选择。


三、Tensor的创建方式

1. 直接创建:torch.tensor()

torch.tensor(data, dtype=None, device=None, requires_grad=False)

参数说明:

  • data:支持 list、tuple、numpy array、scalar 等多种类型传入并转换为 tensor
  • dtype:指定返回的 Tensor 类型
  • device:指定数据返回到的设备(CPU/GPU)
  • requires_grad:是否保留梯度信息,训练时设为 True,验证/测试时设为 False

2. 从NumPy创建

torch.from_numpy(ndarry)

3. 创建特殊形式的Tensor

函数
用途
torch.zeros(*size)
创建全零矩阵
torch.eye(size)
创建单位矩阵(主对角线为1)
torch.ones(*size)
创建全一矩阵

4. 创建随机矩阵Tensor

函数
说明
torch.rand(size)
0~1 区间均匀分布的浮点型随机数
torch.randn(size)
均值为0、方差为1的标准正态分布
torch.normal(mean, std, size)
可指定均值和标准差的正态分布
torch.randint(low, high, size)
在 [low, high) 均匀生成的随机整数

四、Tensor的转换操作

1. Int ↔ Tensor

a = torch.tensor(1)   # 数字(标量)→ Tensor
b = a.item()          # Tensor → Python number

2. List ↔ Tensor

a = [123]
b = torch.tensor(a)          # list → Tensor
c = b.numpy().tolist()       # Tensor → NumPy → list

3. NumPy ↔ Tensor

使用 torch.tensor() 即可将 NumPy 转换为 Tensor。

4. CPU ↔ GPU

CPU → GPU: data.cuda()
GPU → CPU: data.cpu()

五、Tensor的常用操作

1. 获取形状

a = torch.zeros(235)
a.shape         # torch.Size([2, 3, 5])
a.size()        # torch.Size([2, 3, 5])
a.numel()       # 30(统计元素总数)

2. 矩阵转置(维度转换)

permute() — 对任意高维矩阵进行转置:

x = torch.rand(235)
x = x.permute(210)
x.shape         # torch.Size([5, 3, 2])

x.permute(2,1,0) 中,2表示原来的第2个维度现在放在第0个维度,依此类推。

transpose() — 每次只能交换两个维度:

x = torch.rand(234)
x = x.transpose(10)
x.shape         # torch.Size([3, 2, 4])

⚠️ 重要注意:经过 transpose 或 permute 处理后,数据在内存中不再连续。

3. 形状变换

view() — 改变形状,但要求 Tensor 内存连续:

x = torch.randn(44)
x = x.view(28)
x.shape         # torch.Size([2, 8])

view 的局限:不能处理内存不连续的 Tensor。

x = x.permute(10)       # 内存不再连续
x.view(44)              # 报错!RuntimeError

reshape() — 解决内存不连续问题:

x = x.reshape(44)
x.shape         # torch.Size([4, 4])

原理reshape 相当于先执行 contiguous() 将内存捋顺,再执行 view()

4. 增减维度

squeeze() — 删除指定维度(要求该维度值为1):

x = torch.rand(213)
y = x.squeeze(1)
y.shape         # torch.Size([2, 3])

z = y.squeeze(1)   # 第1维度大小为3,删除失败
z.shape         # torch.Size([2, 3])

unsqueeze() — 在指定位置增加维度(值为1):

x = torch.rand(213)
y = x.unsqueeze(2)
y.shape         # torch.Size([2, 1, 1, 3])

六、NumPy与Tensor的对比

对比项
NumPy
Tensor
数据表示形式
科学计算通用工具
GPU加速
❌ 不支持
✅ 支持

七、每课一练

问题torch.Tensor() 和 torch.tensor() 两种函数有何区别?

解答

  • torch.Tensor 是默认 tensor 类型(torch.FloatTensor)的别名,无论输入什么类型,都输出 FloatTensor
  • torch.tensor 会根据输入的数据类型自动判断,创建对应类型的 tensor。例如输入 int 类型时,输出 torch.int32
  • torch.Tensor() 是 Tensor 类的构造方法;torch.tensor() 是 Tensor 类内部的方法,调用后会对参数中的数据做拷贝。

八、小结

  1. Tensor 是 PyTorch 的基础计算单元,对标量、向量、矩阵进行了统一表示,使用 Rank(秩)表示维度。
  2. 创建方式多样:直接创建、从NumPy创建、特殊形式(zeros/ones/eye)、随机矩阵(rand/randn/normal/randint)。
  3. 类型转换灵活:支持 int、list、NumPy、CPU/GPU 之间的相互转换。
  4. 核心操作
    • 形状相关:shapesize()numel()
    • 维度变换:permute()(任意维度)、transpose()(两两交换)
    • 形状变换:view()(需内存连续)、reshape()(自动处理不连续)
    • 增减维度:squeeze()(删减)、unsqueeze()(增加)
  5. 内存连续性是使用 view() 时需特别注意的坑点,可用 contiguous() 解决或直接用 reshape()


【声明】内容源于网络
0
0
知识代码AI
技术基底 机器视觉全栈 × 光学成像 × 图像处理算法 编程栈 C++/C#工业开发 | Python智能建模 工具链 Halcon/VisionPro工业部署 | PyTorch/TensorFlow模型炼金术 | 模型压缩&嵌入式移植
内容 403
粉丝 0
知识代码AI 技术基底 机器视觉全栈 × 光学成像 × 图像处理算法 编程栈 C++/C#工业开发 | Python智能建模 工具链 Halcon/VisionPro工业部署 | PyTorch/TensorFlow模型炼金术 | 模型压缩&嵌入式移植
总阅读6.6k
粉丝0
内容403