Blucoris 2022-07-26 10:18 采纳率: 75%
浏览 123
已结题

图像识别代码添加cuda后跑不起来

问题遇到的现象和发生背景

想问下为什么我添加了cuda后它还是跑不起来,提示我好像运算的时候同时用了cpu和gpu所以报错

问题相关代码,请勿粘贴截图
# -*- coding: utf-8 -*-
"""
Created on Fri Jul 22 10:26:33 2022
@author: Blucoris Liang
"""

import torch
import torch.nn as nn
import torch.utils.data as Data
import torchvision.transforms as transforms
import torchvision.datasets as datasets
import torchvision.models as models

EPOCH=1
BATCH_SIZE=40
LR=0.001

normalize = transforms.Normalize(mean=[0.485, 0.456, 0.406],
                              std=[0.229, 0.224, 0.225])   

train_dataset = datasets.ImageFolder(
        'C:\\Users\\19544\\.spyder-py3\\leapGestRecog\\00',
        transforms.Compose([
                transforms.RandomResizedCrop(224),
                transforms.RandomHorizontalFlip(),
                transforms.ToTensor(),
                normalize,
                ]))

train_loader = Data.DataLoader(
        train_dataset,
        batch_size=BATCH_SIZE,
        shuffle=True)

test_loader = Data.DataLoader(
        datasets.ImageFolder(
                'C:\\Users\\19544\\.spyder-py3\\leapGestRecog\\03', 
                transforms.Compose([
                        transforms.Resize(256),
                        transforms.CenterCrop(224),
                        transforms.ToTensor(),
                        normalize,
                        ])),
        batch_size=BATCH_SIZE, shuffle=False,)

# 数据集长度
train_data_size = len(train_dataset)
print('训练集的长度为:{}'.format(train_data_size))



model = models.resnet18(pretrained=True)

################################
if torch.cuda.is_available():  #
    model = models.resnet18(pretrained=True).cuda()   #
################################



model.fc = torch.nn.Linear(in_features=512, out_features=10, bias=True)

fc_params = list(map(id, model.fc.parameters())) # map函数是将fc.parameters()的id返回并组成一个列表
base_params = filter(lambda p: id(p) not in fc_params, model.parameters()) # filter函数是将model.parameters()中地址不在fc.parameters的id中的滤出来
optimizer = torch.optim.SGD([ {'params': base_params}, {'params': model.fc.parameters(), 'lr': LR * 100}], lr=LR,)
loss_func=nn.CrossEntropyLoss()

################################
if torch.cuda.is_available():  #
    loss_func = loss_func.cuda()   #
################################


class AverageMeter(object):
    """Computes and stores the average and current value"""
    def __init__(self, name, fmt=':f'):
        self.name = name
        self.fmt = fmt
        self.reset()

    def reset(self):
        self.val = 0
        self.avg = 0
        self.sum = 0
        self.count = 0

    def update(self, val, n=1):
        self.val = val
        self.sum += val * n
        self.count += n
        self.avg = self.sum / self.count

    def __str__(self):
        fmtstr = '{name} {val' + self.fmt + '} ({avg' + self.fmt + '})'
        return fmtstr.format(**self.__dict__)
            
def accuracy(output, target, topk=(1,)):
    with torch.no_grad():
        maxk = max(topk)
        batch_size = target.size(0)

        _, pred = output.topk(maxk, 1, True, True)
        pred = pred.t()
        correct = pred.eq(target.view(1, -1).expand_as(pred))

        res = []
        for k in topk:
            correct_k = correct[:k].view(-1).float().sum(0, keepdim=True)
            res.append(correct_k.mul_(100.0 / batch_size))
        return res           
            
train_losses = AverageMeter('TrainLoss', ':.4e')
train_top1 = AverageMeter('TrainAccuracy', ':6.2f')
test_losses = AverageMeter('TestLoss', ':.4e')
test_top1 = AverageMeter('TestAccuracy', ':6.2f')

for epoch in range(EPOCH):
    
    model.train()
    for i,(images,target) in enumerate(train_loader):
        ################################
        if torch.cuda.is_available():  #
            images = images.cuda()         #
            target = target.cuda()   #
        ################################
        output=model(images)
        loss= loss_func(output,target)
        
        acc1, = accuracy(output, target, topk=(1,))
        train_losses.update(loss.item(), images.size(0))
        train_top1.update(acc1[0], images.size(0))

        optimizer.zero_grad()
        loss.backward()
        optimizer.step()
        
        print('Epoch[{}/{}],TrainLoss:{}, TrainAccuracy:{}'.format(epoch,EPOCH,train_losses.val, train_top1.val))
           
    model.eval()
    with torch.no_grad():
        for i,(images,target) in enumerate(test_loader):
            ################################
            if torch.cuda.is_available():  #
                images = images.cuda()         #
                target = target.cuda()   #
            ################################
            output=model(images)
            loss= loss_func(output,target)
            
            acc1, = accuracy(output, target, topk=(1,))
            test_losses.update(loss.item(), images.size(0))
            test_top1.update(acc1[0], images.size(0))
            
    print('TestLoss:{}, TestAccuracy:{}'.format(test_losses.avg, test_top1.avg))


import visdom

# 新建一个连接客户端
# 指定env = u'test1', 默认端口为8097,host是localhost
vis = visdom.Visdom(env = u'test1')
vis.line(X = train_top1.val , Y = train_losses.val)

运行结果及报错内容
runfile('C:/Users/19544/.spyder-py3/成功对手势识别用resnet进行了第一次训练.py', wdir='C:/Users/19544/.spyder-py3')
训练集的长度为:2000
Traceback (most recent call last):

  File "C:\Users\19544\.spyder-py3\成功对手势识别用resnet进行了第一次训练.py", line 126, in <module>
    output=model(images)

  File "D:\ANACONDA\envs\MyEnv\lib\site-packages\torch\nn\modules\module.py", line 1110, in _call_impl
    return forward_call(*input, **kwargs)

  File "D:\ANACONDA\envs\MyEnv\lib\site-packages\torchvision\models\resnet.py", line 283, in forward
    return self._forward_impl(x)

  File "D:\ANACONDA\envs\MyEnv\lib\site-packages\torchvision\models\resnet.py", line 278, in _forward_impl
    x = self.fc(x)

  File "D:\ANACONDA\envs\MyEnv\lib\site-packages\torch\nn\modules\module.py", line 1110, in _call_impl
    return forward_call(*input, **kwargs)

  File "D:\ANACONDA\envs\MyEnv\lib\site-packages\torch\nn\modules\linear.py", line 103, in forward
    return F.linear(input, self.weight, self.bias)

RuntimeError: Expected all tensors to be on the same device, but found at least two devices, cpu and cuda:0! (when checking argument for argument mat1 in method wrapper_addmm)

我的解答思路和尝试过的方法

我尝试过在几处补上了cuda项,可是还是没有成功

我想要达到的结果

希望用cuda跑起来。

  • 写回答

3条回答 默认 最新

  • 万里鹏程转瞬至 人工智能领域优质创作者 2022-07-26 11:39
    关注

    Expected all tensors to be on the same device。
    也就是说,有的data在cpu上,而有的在cuda上。通过观察代码可以发现你的model是cuda对象,但是model.fc却不是。第61行这里应该改成:model.fc = torch.nn.Linear(in_features=512, out_features=10, bias=True).cuda()

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

问题事件

  • 系统已结题 8月3日
  • 已采纳回答 7月26日
  • 创建了问题 7月26日

悬赏问题

  • ¥15 软件定义网络mininet和onos控制器问题
  • ¥15 微信小程序 用oss下载 aliyun-oss-sdk-6.18.0.min client报错
  • ¥15 ArcGIS批量裁剪
  • ¥15 labview程序设计
  • ¥15 为什么在配置Linux系统的时候执行脚本总是出现E: Failed to fetch http:L/cn.archive.ubuntu.com
  • ¥15 Cloudreve保存用户组存储空间大小时报错
  • ¥15 伪标签为什么不能作为弱监督语义分割的结果?
  • ¥15 编一个判断一个区间范围内的数字的个位数的立方和是否等于其本身的程序在输入第1组数据后卡住了(语言-c语言)
  • ¥15 Mac版Fiddler Everywhere4.0.1提示强制更新
  • ¥15 android 集成sentry上报时报错。