在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
相关推荐
山楂树下懒猴子18 分钟前
ChatAI项目-ChatGPT-SDK组件工程
人工智能·chatgpt·junit·https·log4j·intellij-idea·mybatis
Learn Beyond Limits38 分钟前
The learning process of Decision Tree Model|决策树模型学习过程
人工智能·深度学习·神经网络·学习·决策树·机器学习·ai
AI360labs_atyun40 分钟前
2025世界智博会,揭幕AI触手可及的科幻生活
人工智能·ai·音视频·生活
luoganttcc44 分钟前
小鹏汽车 vla 算法最新进展和模型结构细节
人工智能·算法·汽车
sinat_602035361 小时前
模块与包的导入
运维·服务器·开发语言·python
计算机学姐1 小时前
基于Python的旅游数据分析可视化系统【2026最新】
vue.js·后端·python·数据分析·django·flask·旅游
算家计算1 小时前
面壁智能开源多模态大模型——MiniCPM-V 4.5本地部署教程:8B参数开启多模态“高刷”时代!
人工智能·开源
居然JuRan1 小时前
从零开始学大模型之大语言模型
人工智能
恋雨QAQ1 小时前
python函数和面向对象
开发语言·python
扑克中的黑桃A1 小时前
AI 对话高效输入指令攻略(一):了解AI对话指令
人工智能