在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
相关推荐
西柚与蓝莓1 小时前
【开源开放体系总结】
python
萱仔学习自我记录1 小时前
PEFT库和transformers库在NLP大模型中的使用和常用方法详解
人工智能·机器学习
hsling松子4 小时前
使用PaddleHub智能生成,献上浓情国庆福
人工智能·算法·机器学习·语言模型·paddlepaddle
belldeep4 小时前
python:reportlab 将多个图片合并成一个PDF文件
python·pdf·reportlab
正在走向自律4 小时前
机器学习框架
人工智能·机器学习
好吃番茄5 小时前
U mamba配置问题;‘KeyError: ‘file_ending‘
人工智能·机器学习
CV-King6 小时前
opencv实战项目(三十):使用傅里叶变换进行图像边缘检测
人工智能·opencv·算法·计算机视觉
禁默6 小时前
2024年计算机视觉与艺术研讨会(CVA 2024)
人工智能·计算机视觉
FreakStudio7 小时前
全网最适合入门的面向对象编程教程:56 Python字符串与序列化-正则表达式和re模块应用
python·单片机·嵌入式·面向对象·电子diy
whaosoft-1437 小时前
大模型~合集3
人工智能