在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
相关推荐
数据智能老司机44 分钟前
精通 Python 设计模式——分布式系统模式
python·设计模式·架构
逛逛GitHub1 小时前
飞书多维表“独立”了!功能强大的超出想象。
人工智能·github·产品
机器之心1 小时前
刚刚,DeepSeek-R1论文登上Nature封面,通讯作者梁文锋
人工智能·openai
数据智能老司机2 小时前
精通 Python 设计模式——并发与异步模式
python·设计模式·编程语言
数据智能老司机2 小时前
精通 Python 设计模式——测试模式
python·设计模式·架构
数据智能老司机2 小时前
精通 Python 设计模式——性能模式
python·设计模式·架构
c8i2 小时前
drf初步梳理
python·django
每日AI新事件2 小时前
python的异步函数
python
这里有鱼汤3 小时前
miniQMT下载历史行情数据太慢怎么办?一招提速10倍!
前端·python
aneasystone本尊3 小时前
学习 Chat2Graph 的知识库服务
人工智能