【问题标题】:Input type and Bias type for basic CNN giving error基本 CNN 给出错误的输入类型和偏置类型
【发布时间】:2023-01-30 01:49:14
【问题描述】:

我正在尝试遵循使用 pytorch (Link) 制作 CNN 的指南。我没有使用 CIFAR-10 数据集,而是自己制作了数据集。我认为这就是问题所在,但我不知道发生了什么。

这是我的错误:

听起来很傻,但我尝试按照预期成功的指南进行操作,却遇到了这些错误。我曾尝试在线研究任何可能的解决方案,并努力寻找可能对我有帮助的任何资源。

我还将与您分享我的数据集类:

class ASLDataset(torch.utils.data.Dataset): # inheritin from Dataset class
    def __init__(self, csv_file, root_dir="", transform=None):
        self.annotation_df = pd.read_csv(csv_file)
        self.root_dir = root_dir # root directory of images, leave "" if using the image path column in the __getitem__ method
        self.transform = transform

    def __len__(self):
        return len(self.annotation_df) # return length (numer of rows) of the dataframe

    def __getitem__(self, idx):
        image_path = os.path.join(self.root_dir, self.annotation_df.iloc[idx, 1]) #use image path column (index = 1) in csv file
        image = cv2.imread(image_path) # read image by cv2
        image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) # convert from BGR to RGB for matplotlib
        class_name = self.annotation_df.iloc[idx, 2] # use class name column (index = 2) in csv file
        class_index = self.annotation_df.iloc[idx, 3] # use class index column (index = 3) in csv file
        if self.transform:
            image = self.transform(image)
        return image, class_index #, class_name

train_dataset = ASLDataset('./train.csv') #, train_transform)
train_dataloader = DataLoader(train_dataset, batch_size=batch_size, shuffle=True, num_workers=num_workers)

val_dataset = ASLDataset('./test.csv')  # val.csv
val_dataloader = DataLoader(val_dataset, batch_size=batch_size, shuffle=False, num_workers=num_workers)

classes = ('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'nothing', 'O', 'P', 'Q', 'R', 'S', 'space', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z')

以下是错误代码中出现的行以及指南中的网络:

class Network(nn.Module):
    def __init__(self):
        super(Network, self).__init__()

        self.conv1 = nn.Conv2d(in_channels=3, out_channels=12, kernel_size=5, stride=1, padding=1)
        self.bn1 = nn.BatchNorm2d(12)
        self.conv2 = nn.Conv2d(in_channels=12, out_channels=12, kernel_size=5, stride=1, padding=1)
        self.bn2 = nn.BatchNorm2d(12)
        self.pool = nn.MaxPool2d(2, 2)
        self.conv4 = nn.Conv2d(in_channels=12, out_channels=24, kernel_size=5, stride=1, padding=1)
        self.bn4 = nn.BatchNorm2d(24)
        self.conv5 = nn.Conv2d(in_channels=24, out_channels=24, kernel_size=5, stride=1, padding=1)
        self.bn5 = nn.BatchNorm2d(24)
        self.fc1 = nn.Linear(24 * 10 * 10, 10)

    def forward(self, input):
        output = F.relu(self.bn1(self.conv1(input)))
        output = F.relu(self.bn2(self.conv2(output)))
        output = self.pool(output)
        output = F.relu(self.bn4(self.conv4(output)))
        output = F.relu(self.bn5(self.conv5(output)))
        output = output.view(-1, 24 * 10 * 10)
        output = self.fc1(output)

        return output
def train(num_epochs):
    best_accuracy = 0.0

    # Define your execution device
    device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
    print("The model will be running on", device, "device")
    # Convert model parameters and buffers to CPU or Cuda
    model.to(device)

    for epoch in range(num_epochs):  # loop over the dataset multiple times
        running_loss = 0.0
        running_acc = 0.0

        for i, (images, labels) in enumerate(train_dataloader, 0):

            # get the inputs
            images = Variable(images.to(device))
            print(type(labels))
            labels = Variable(labels.to(device))

            # zero the parameter gradients
            optimizer.zero_grad()
            # predict classes using images from the training set
            outputs = model(images)
            # compute the loss based on model output and real labels
            loss = loss_fn(outputs, labels)
            # backpropagate the loss
            loss.backward()
            # adjust parameters based on the calculated gradients
            optimizer.step()

#Code goes on from here

【问题讨论】:

    标签: python machine-learning pytorch conv-neural-network


    【解决方案1】:

    通过进一步的工作和一些外部帮助,我能够得到这个问题的答案。我的问题部分出在我的类定义以及我稍后在代码中调用某些项目的方式。而不是在中定义没有转换的 ASLDataset 类在里面我应该有以下内容:

    class ASLDataset(torch.utils.data.Dataset): # inheritin from Dataset class
        def __init__(self, csv_file, root_dir="", transform=transforms.ToTensor()):
            self.annotation_df = pd.read_csv(csv_file)
            self.root_dir = root_dir # root directory of images, leave "" if using the image path column in the __getitem__ method
            self.transform = transform
            
            ....
    

    当我开始将输入转换为张量时,我还必须更改稍后调用 returns 的方式。每当我调用图像或标签(我将 class_index 重命名为)时,我都必须这样称呼它们:

                #Define the device which will be used for processing
                device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
    
                #Modify both the images and the labels so that they are stored as tensors
                images = images.to(device)
                labels = labels.to(device)
    

    请记住,图像和标签是我的 ASL 数据集类的回报获取项目:

        def __getitem__(self, idx):
            image_path = os.path.join(self.root_dir, self.annotation_df.iloc[idx, 1]) #use image path column (index = 1) in csv file
            # image = read_image(image_path)
    
            print("Got item")
    
            image = cv2.imread(image_path) # read image by cv2
            image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) # convert from BGR to RGB for matplotlib
            label = self.annotation_df.iloc[idx, 3]
            if self.transform:
                image = self.transform(image)
            return image, label
    

    我希望这个答案对那些现在和将来为这个问题或类似问题而苦苦挣扎的人有所帮助,上帝保佑大家!

    【讨论】:

      猜你喜欢
      • 2020-04-22
      • 1970-01-01
      • 1970-01-01
      • 2016-10-08
      • 2022-08-04
      • 1970-01-01
      • 2019-10-29
      • 1970-01-01
      • 2016-11-09
      相关资源
      最近更新 更多