TypeError: conv2d() received an invalid combination of arguments

完整报错:

TypeError: conv2d() received an invalid combination of arguments - got (str, Parameter, NoneType, tuple, tuple, tuple, int), but expected one of:
 * (Tensor input, Tensor weight, Tensor bias, tuple of ints stride, tuple of ints padding, tuple of ints dilation, int groups)
      didn't match because some of the arguments have invalid types: (str, Parameter, NoneType, tuple, tuple, tuple, int)
 * (Tensor input, Tensor weight, Tensor bias, tuple of ints stride, str padding, tuple of ints dilation, int groups)
      didn't match because some of the arguments have invalid types: (str, Parameter, NoneType, tuple, tuple, tuple, int)

场景:在模型训练完用模型做预测的时候报错,预测代码:

def predict_process(root_path, transform):
    imgs = os.listdir(root_path)
    res=[]
    label_arry=['ant','bee']
    for img in imgs:
        img_path = root_path+'/'+img
        print(img_path)
        img_item = Image.open(img_path)
        img_item = transform(img_item)
        # 将输入图片的shape修改成符合输入条件的shape
        img_item = torch.reshape(img_item, (1,3, 224, 224))
        img_item=img_item.to(device)
        print(type(img_item))
        mymodel.eval()
        with torch.no_grad():
            output = mymodel(img)
            ret,index=torch.max(output,1)
            index=index.data
            res.append(label_arry[index])
    return res

原因分析:在卷积的时候接收到了无效的参数,所以要么就是输入的参数有问题,要么就是卷积层有问题,但是这里的mymodel我用的是pytorch中自带的resnet50所以卷积层肯定是没有问题的,所以问题就定位在我输入图片的格式,因为我在训练的时候是没有报错的,所以我只需要保证我在做预测的时候输入图片的格式和我训练的时候输入的图片格式是一样的就可以了,然后我把做预测的时候的图片img_item的shape和自身都输出了一遍,print(img_item.shape),print(img_item)去和训练的时候的图片做对比,发现是一模一样的,于是我开始疯狂改预测时输入的img_item的格式,希望能试出看看什么格式是ok的,就这样搞了一天还是不行,后来发现我搞了半天的img_item,最后输入模型做预测的时候用的是img,output = mymodel(img)img是一个str类型的变量"xxx.png",所以我浪费了一天的生命,但如果有类似的问题以上的分析步骤是没问的,问题一般就出在输入图片和卷积层上。

猜你喜欢

转载自blog.csdn.net/weixin_44747173/article/details/127461026
今日推荐