Pytorch知识点与问题解决

文|Seraph

01 | 知识点

  1. torcht.is_tensor(a) 判断是否为张量
  2. Pytorch GPU环境是否正常测试代码:
import torch
flag = torch.cuda.is_available()
print(flag)

ngpu= 1
# Decide which device we want to run on
device = torch.device("cuda:0" if (torch.cuda.is_available() and ngpu > 0) else "cpu")
print(device)
print(torch.cuda.get_device_name(0))
print(torch.rand(3,3).cuda())
  1. cuDNN使用非确定算法设置torch.backends.cudnn.enabled = False可以关闭。
    当设置
torch.backends.cudnn.enabled = true
torch.backends.cudnn.benchmark = true

cuDNN使用的非确定性算法就会自动寻找最适合当前配置的高效算法,来达到优化运行效率的问题。
适用场景是网络结构固定、输入形状不变的情况。如卷积层的设置一直变化,会导致程序不断再优化,从而耗费更多的时间。

  1. torch.manual_seed(args.seed) #为CPU设置种子用于生成随机数
    torch.cuda.manual_seed(args.seed)#为当前GPU设置随机种子;如果使用多个GPU,应该使用torch.cuda.manual_seed_all()为所有的GPU设置种子。
    之所以设置种子,是因为可以复现结果。

99 | 问题解决

  1. 执行loss.data[0]报错:IndexError: invalid index of a 0-dim tensor. Use tensor.item() to convert a 0-dim tensor to a Python number
    解决:将loss.data[0]换成loss.item()
  2. 使用DistributedSampler()后再Dataloader()参数中加入了shuffle=True报错:Dataloader BUG ValueError: sampler option is mutually exclusive with shuffle
    解决:去掉该参数。因为torch.utils.data.distributed.DistributedSampler是默认使用shuffle=True的,所以不能多次使用。
  3. Expected object of scalar type Float but got scalar type Long for argument #2 ‘target’
    解决:将target类型转换为float:
    target = target.float()
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值