在pytorch中,读取GPU上张量的数值 (数据从GPU到CPU) 的几种常用方法

1、.cpu() 方法:

使用 .cpu() 方法可以将张量从 GPU 移动到 CPU。这是一种简便的方法,常用于在进行 CPU 上的操作之前将数据从 GPU 取回

python 复制代码
import torch

# 在 GPU 上创建一个张量
gpu_tensor = torch.tensor([1, 2, 3], device='cuda')

# 将 GPU 上的张量移动到 CPU
cpu_tensor = gpu_tensor.cpu()


# 打印输出
print("GPU Tensor:", gpu_tensor)
print("CPU Tensor:", cpu_tensor)
python 复制代码
GPU Tensor: tensor([1,2,3],device='cuda:')
CPU Array: tensor([1,2,3])

2、.to('cpu') 方法:

使用 .to('cpu') 方法也可以将张量移动到 CPU。这是一个通用的设备转移方法,可以指定目标设备和其他参数。

python 复制代码
import torch

# 在 GPU 上创建一个张量
gpu_tensor = torch.tensor([1, 2, 3], device='cuda')

# 将 GPU 上的张量移动到 CPU
cpu_tensor = gpu_tensor.to('cpu')

# 打印输出
print("GPU Tensor:", gpu_tensor)
print("CPU Tensor:", cpu_tensor)
python 复制代码
GPU Tensor: tensor([1,2,3],device='cuda:')
CPU Array: tensor([1,2,3])

3、.numpy() 方法:

使用 .numpy() 方法将 GPU 上的张量转换为 NumPy 数组。这个方法实际上是先将张量移动到 CPU,然后转换为 NumPy 数组。

python 复制代码
import torch

# 在 GPU 上创建一个张量
gpu_tensor = torch.tensor([1, 2, 3], device='cuda')

# 将 GPU 上的张量移动到 CPU,并转换为 NumPy 数组
cpu_array = gpu_tensor.cpu().numpy()

# 打印输出
print("GPU Tensor:", gpu_tensor)
print("CPU Array:", cpu_array)
python 复制代码
GPU Tensor: tensor([1,2,3],device='cuda:')
CPU Array: array([1,2,3])

4、.tolist() 方法:

使用 .tolist() 方法将张量转换为 Python 列表。

python 复制代码
import torch

# 在 GPU 上创建一个张量
gpu_tensor = torch.tensor([1, 2, 3], device='cuda')

# 将张量转换为 Python 列表
python_list = gpu_tensor.tolist()

# 打印输出
print("GPU Tensor:",gpu_tensor)
print("\nPython_list:",python_list)
python 复制代码
GPU Tensor: tensor([1,2,3],device='cuda:')
Python_list: [1,2,3]

5、.item() 方法:

如果张量只包含一个元素,可以使用 .item() 方法直接获取该元素的 Python 数值。

python 复制代码
import torch

# 在 GPU 上创建一个张量
gpu_tensor = torch.tensor(3, device='cuda')

# 获取张量的数值
value = gpu_tensor.item()

# 打印输出
print("GPU Tensor:", gpu_tensor)
print("Value:", value)
python 复制代码
GPU Tensor: tensor(3,device='cuda:')
Value: 3
相关推荐
kkcodeer3 分钟前
大模型Prompt原理、编写原则与技巧以及衡量方法
人工智能·prompt·ai大模型
卡洛斯(编程版4 分钟前
(1) 哈希表全思路-20天刷完Leetcode Hot 100计划
python·算法·leetcode
DevSecOps选型指南13 分钟前
SBOM风险预警 | NPM前端框架 javaxscript 遭受投毒窃取浏览器cookie
前端·人工智能·前端框架·npm·软件供应链安全厂商·软件供应链安全工具
rocksun15 分钟前
MCP利用流式HTTP实现实时AI工具交互
人工智能·mcp
伊织code25 分钟前
PyTorch API 7
pytorch·api·张量·稀疏
FreakStudio30 分钟前
一文速通 Python 并行计算:教程总结
python·pycharm·嵌入式·面向对象·并行计算
群联云防护小杜34 分钟前
从一次 DDoS 的“死亡回放”看现代攻击链的进化
开发语言·python·linq
xiaok39 分钟前
docker network create langbot-network这条命令在dify输入还是在langbot中输入
人工智能
Ice__Cai39 分钟前
Flask 入门详解:从零开始构建 Web 应用
后端·python·flask·数据类型