Pytorch如何将嵌套的dict类型数据加载到GPU

在PyTorch中,您可以使用.to(device)方法将嵌套的字典中的所有支持的Tensor对象转移到GPU。以下是一个简单的例子

python 复制代码
import torch
 
# 假设您已经有了一个名为device的GPU设备对象
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
 
# 嵌套的字典,其中包含一些Tensors
nested_dict = {
    'a': torch.randn(2, 2),
    'b': {
        'b1': torch.randn(2, 2),
        'b2': torch.randn(2, 2)
    },
    'c': torch.randn(2, 2)
}
 
# 将嵌套字典中的所有Tensors移动到GPU
def to_gpu(data):
    if isinstance(data, dict):
        return {k: to_gpu(v) for k, v in data.items()}
    elif isinstance(data, list):
        return [to_gpu(i) for i in data]
    elif isinstance(data, tuple):
        return tuple([to_gpu(i) for i in data])
    elif torch.is_tensor(data) and data.device != device:
        return data.to(device)
    else:
        return data
 
nested_dict_gpu = to_gpu(nested_dict)
 
# 检查是否所有Tensors都已移动到GPU
for k, v in nested_dict_gpu.items():
    if torch.is_tensor(v):
        assert v.device == device

这个函数to_gpu会递归地检查字典中的每个元素,如果是Tensor类型并且不在GPU上,就会使用.to(device)方法转移它。您需要先设置device变量指向您的GPU设备。如果没有GPU可用,它会默认使用CPU。

相关推荐
AI浩4 小时前
UNIV:红外与可见光模态的统一基础模型
人工智能·深度学习
Coding茶水间7 小时前
基于深度学习的安检危险品检测系统演示与介绍(YOLOv12/v11/v8/v5模型+Pyqt5界面+训练代码+数据集)
图像处理·人工智能·深度学习·yolo·目标检测·机器学习·计算机视觉
Niuguangshuo9 小时前
自编码器与变分自编码器:【2】自编码器的局限性
pytorch·深度学习·机器学习
likerhood9 小时前
3. pytorch中数据集加载和处理
人工智能·pytorch·python
haiyu_y9 小时前
Day 46 TensorBoard 使用介绍
人工智能·深度学习·神经网络
不惑_10 小时前
通俗理解卷积神经网络
人工智能·windows·python·深度学习·机器学习
rayufo11 小时前
自定义数据在深度学习中的应用方法
人工智能·深度学习
人工智能培训11 小时前
DNN案例一步步构建深层神经网络(3)
人工智能·深度学习·神经网络·大模型·dnn·具身智能·智能体
youngfengying11 小时前
先验知识融入深度学习
人工智能·深度学习·先验知识
A林玖11 小时前
【深度学习】目标检测
人工智能·深度学习·目标检测