【问题标题】:conv2d getting bad inputconv2d 输入错误
【发布时间】:2021-06-27 07:07:57
【问题描述】:

我已经训练了一个分类器,现在尝试加载它并运行一些预测 我收到下面提供的错误

....
    return self._conv_forward(input, self.weight, self.bias)
  File "/usr/local/lib/python3.9/site-packages/torch/nn/modules/conv.py", line 439, in _conv_forward
    return F.conv2d(input, weight, bias, self.stride,
TypeError: conv2d() received an invalid combination of arguments - got (list, Parameter, Parameter, 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: (list, Parameter, Parameter, 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: (list, Parameter, Parameter, tuple, tuple, tuple, int)

这里是代码

import torch
import torch.nn as nn
import numpy as np
from PIL import Image
from torchvision.transforms import transforms
from torch.utils.data import DataLoader

Transformer - 用于对图像进行编码

transformer = transforms.Compose([
        transforms.RandomHorizontalFlip(0.5),
        transforms.ToTensor(),
    ])

获取文件并转换为张量

def get_file_as_tensor(file_path):
    with np.load(file_path) as f:
        melspec_image_array = f['arr_0']
        image = Image.fromarray(melspec_image_array, mode='RGB')
        image_tensor = transformer(image).div_(255).float()
        return image_tensor.clone().detach()

栈顶的预测函数,因为我运行model([tensor])时发生错误

def predict(tensor, model):
    yhat = model([tensor])
    yhat = yhat.clone().detach()
    return yhat

class ConvBlock(nn.Module):
    def __init__(self, in_channels, out_channels):
        super().__init__()

        self.conv1 = nn.Sequential(
            nn.Conv2d(in_channels, out_channels, 3, 1, 1),
            nn.BatchNorm2d(out_channels),
            nn.ReLU(),
        )
        self.conv2 = nn.Sequential(
            nn.Conv2d(out_channels, out_channels, 3, 1, 1),
            nn.ReLU(),
            nn.Dropout(0.5)
        )

        self._init_weights()

    def _init_weights(self):
        for m in self.modules():
            if isinstance(m, nn.Conv2d):
                nn.init.kaiming_normal_(m.weight)
                if m.bias is not None:
                    nn.init.zeros_(m.bias)
            elif isinstance(m, nn.BatchNorm2d):
                nn.init.constant_(m.weight, 1)
                nn.init.zeros_(m.bias)

    def forward(self, x):
        x = self.conv1(x)
        x = self.conv2(x)
        x = F.avg_pool2d(x, 2)
        return x

class Classifier(nn.Module):
    def __init__(self, num_classes=10):
        super().__init__()

        self.conv = nn.Sequential(
            ConvBlock(in_channels=3, out_channels=64),
            ConvBlock(in_channels=64, out_channels=128),
            ConvBlock(in_channels=128, out_channels=256),
            ConvBlock(in_channels=256, out_channels=512),
        )

        self.fc = nn.Sequential(
            nn.Dropout(0.4),
            nn.Linear(512, 128),
            nn.PReLU(),
            #nn.BatchNorm1d(128),
            nn.Dropout(0.2),
            nn.Linear(128, num_classes),
        )

    def forward(self, x):
        x = self.conv(x)
        x = torch.mean(x, dim=3)
        x, _ = torch.max(x, dim=2)
        x = self.fc(x)
        return x

PATH = "models/model.pt"
model = Classifier()
model.load_state_dict(torch.load(PATH))

model.eval()

cry_file_path = "processed_np/car_file.npz"
car_tensor = get_file_as_tensor(car_file_path)

no_car_file_path = "raw_negative_processed/nocar-1041.npz"
no_car_tensor = get_file_as_tensor(no_car_file_path)

car_prediction = predict(car_tensor, model)
no_cry_prediction = predict(no_car_tensor, model)

print("car", car_prediction)
print("no car", no_car_prediction)

代码是不言自明的,但 SO 不断要求更多文本 非常感谢一些帮助,因为我是 ML 新手

【问题讨论】:

    标签: python machine-learning pytorch


    【解决方案1】:
    def predict(tensor, model):
        yhat = model(tensor.unsqueeze(0))
        yhat = yhat.clone().detach()
        return yhat
    

    使用这个方法定义而不是你的

    【讨论】:

    • 这绝对有效,谢谢!你能帮我理解我得到的预测car tensor([[ 3.4698, 46.3546, -15.1995, 7.4773, -16.1046, 4.3731, -11.0522, -11.9843, 7.8179, -2.0419]]) no car tensor([[19.6270, 2.4702, -8.4636, -5.1912, -1.6616, -0.9092, 1.1438, -1.1953, -1.4171, -3.4278]])我怎么知道它是否做出了正确的预测,这里的置信度是多少?
    • 使用torch.max()。
    • 如果你想要自信...使用nn.Softmax层
    • 感谢您所做的一切!
    【解决方案2】:

    为什么要将模型应用到[tensor],即应用到包含单个元素tensor 的python 列表?
    您应该将您的模型直接应用于tensor:model(tensor)。

    您可能需要向tensor 添加一个单独的“批量维度”。详情请见this answer。

    【讨论】:

      【解决方案3】:

      错误是关于 conv2d() 函数而不是模块。

      我在这里唯一能想到的是您的输入数据不正确。确保它是 (B, C, H, W) 形式的张量。

      【讨论】:

        猜你喜欢
        • 2018-08-15
        • 1970-01-01
        • 2020-04-29
        • 1970-01-01
        • 1970-01-01
        • 2017-09-04
        • 2019-01-11
        • 1970-01-01
        • 2018-09-24
        相关资源
        最近更新 更多