在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
相关推荐
科技发布几秒前
拓氪科技 AI 内容引擎软文投放效果详解
人工智能·科技
nanawinona7 分钟前
2026年下半年量化学习,不同基础要查不同缺口
人工智能·python
海盗123413 分钟前
AI新闻日报_2026-07-22
人工智能
CTA量化套保23 分钟前
最新量化表达入门,从概念规则到简单实现
人工智能·python
AI应用苏大大26 分钟前
企业AI架构缺陷:低价工具堆叠,造成结构性效率浪费
人工智能
空中湖1 小时前
Spring AI Agent 编排:ReAct 模式 + 多 Agent 协作实战
人工智能·spring·react.js
only-qi1 小时前
RAG 工作机制详解:构建高质量知识库的技术全流程
网络·人工智能·rag
John_ToDebug1 小时前
Git Stash 完全指南:临时保存工作区的艺术
人工智能·git·agent
feibaoqq1 小时前
Atlas边端板卡AI识别:部署方法、技术实现、优劣及应用场景
人工智能·低空经济·低空安防
小保CPP1 小时前
OpenCV C++将多张图像合并为webp动图
c++·人工智能·opencv·计算机视觉