pytorch:to(device)

def get_pseudo_labels(dataset, model, threshold=0.65):
    # This functions generates pseudo-labels of a dataset using given model.
    # It returns an instance of DatasetFolder containing images whose prediction confidences exceed a given threshold.
    # You are NOT allowed to use any models trained on external data for pseudo-labeling.
    device = "cuda" if torch.cuda.is_available() else "cpu"

    # Construct a data loader.
    data_loader = DataLoader(dataset, batch_size=batch_size, shuffle=False)

    # Make sure the model is in eval mode.
    model.eval()
    # Define softmax function.
    softmax = nn.Softmax(dim=-1)
    x=torch.Tensor([])
    y=torch.Tensor([])
    # Iterate over the dataset by batches.
    for batch in tqdm(data_loader):
        img, _ = batch


        # Forward the data
        # Using torch.no_grad() accelerates the forward process.
        with torch.no_grad():
            logits = model(img.to(device))

        # Obtain the probability distributions by applying softmax on logits.
        probs = softmax(logits)

        # ---------- TODO ----------
        # Filter the data and construct a new dataset.
        value,indices=probs.max(dim=-1)
        i=0
        for yk in value:
          if yk>threshold:
            data=img[i].reshape(1,3,128,128)
            lable=indices[i].reshape(1)
            x=torch.cat((x,data),dim=0)
            y=torch.cat((y,lable),dim=0)
          i=i+1
        
    dataset=unlableDataset(x,y)
    # # Turn off the eval mode.
    model.train()
    return dataset

今天在跑神经网络时报错:
一开始我好奇为什么x不报错,y却报错,但是也没太当回事。
因为是小白,不清楚cpu与cuda的关系,于是给每个数据都加了to(device),搞了一个多小时都没搞明白。正当放弃的时候,改回了最开始的代码,又细想起来刚才的疑惑,才发现x的数据来源于cpu,而y的最初始数据上传给了GPU,经过了一系列计算得到了y,于是报了这个错。之后我给lable改为lable.to(device)就解决了。


所以,重点来了: 将数据上传给cuda后,对该数据进行的操作所得到的数据均保存在GPU上!


  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值