【PyTorch】张量转Numpy
【PyTorch】张量转Numpy
一、常用 4 种方式(按推荐优先级排序)
1. 最标准:.detach().numpy() ✅ 首选
适合:有梯度、计算图里的张量
python
运行
import torch
x = torch.randn(3,4, requires_grad=True)
arr = x.detach().numpy()
-
.detach():脱离计算图,切断梯度关联 - 安全不报错,日常开发、模型推理必用
2. 先关梯度再转:.cpu().numpy()
适合:GPU 上的张量
python
运行
# 张量在GPU
x = torch.randn(3,4).cuda()
arr = x.cpu().numpy()
- 必须先挪到 CPU,GPU 张量不能直接转 numpy
3. 无梯度直接转:.numpy()
适合:不需要梯度、普通 CPU 张量
python
运行
x = torch.randn(3,4)
arr = x.numpy()
- 注意:带
requires_grad=True 直接.numpy() 会报错
4. 万能兜底:tensor.numpy(force=True)(PyTorch 1.13+)
python
运行
x = torch.randn(3,4, requires_grad=True)
arr = x.numpy(force=True)
-
force=True强制脱离计算图转 numpy - 懒人写法,不用写
.detach()
二、容易踩的坑
- GPU 张量不能直接 .numpy () 报错:can't convert cuda tensor to numpy解决:先
.cpu() - 带梯度张量直接 .numpy () 报错解决:加
.detach() 或force=True - 共享内存张量转 numpy 后,修改 numpy 数组会同步改原张量想断开关联:
arr = x.detach().numpy().copy()深拷贝
三、一句话总结
- 普通有梯度 CPU: .detach().numpy()
- GPU 张量: .cpu().detach().numpy()
- 懒人简写: .numpy(force=True)

浙公网安备 33010602011771号