神经网络训练有问题。损失不减

mkm*_*ell 4 python machine-learning pytorch

我主要关注这个项目,但正在做像素级分类。我有 8 个班级和 9 个乐队图像。我的图像被网格化为 9x128x128。我的损失并没有减少,训练准确性也没有太大波动。我猜我的模型有问题。非常感谢任何建议!我使用随机森林获得了至少 91% 的准确率。

我的班级非常不平衡,因此我尝试根据训练数据中的班级比例调整训练权重。

# get model
learning_rate = 0.0001
model = unet.UNetSmall(8)
optimizer = optim.Adam(model.parameters(), lr=learning_rate)

# set up weights based on data proportion
weights = np.array([0.79594768, 0.07181202, 0.02347426, 0.0042031, 0.00366211, 0.00764327, 0.07003923, 0.02321833])
weights = (1 - weights)/7
print('Weights of training data based on proportion of the training labels.  Not compted here')
print(weights)
print(sum(weights))
criterion = nn.CrossEntropyLoss(weight = weight)
lr_scheduler = optim.lr_scheduler.StepLR(optimizer, step_size=5, gamma=0.1)
Run Code Online (Sandbox Code Playgroud)

基于训练标签比例的训练数据权重。此处未计算 [0.02915033 0.13259828 0.13950368 0.1422567 0.14233398 0.14176525 0.13285154 0.139540200002] 10000002

我已经使用 transforms.functional.normalize 函数对数据进行了标准化。我计算了训练数据的均值和标准差,并将这种增强添加到我的数据加载器中。

dataset_train = data_utils.SatIn(data_path, 'TrainValTest.csv', 'train', transform=transforms.Compose([aug.ToTensorTarget(), aug.NormalizeTarget(mean=popmean, std=popstd)]))
Run Code Online (Sandbox Code Playgroud)

我通过旋转和翻转图像在预处理中增加了我的训练数据。1个图像网格然后变成了8个。

我检查了我的训练数据是否与我的课程相匹配,并且一切都已检查。由于我使用了 8 个类,因此我选择使用 CrossEntropyLoss,因为它内置了 Softmax。

当前型号

class UNetSmall(nn.Module):
    """
    Main UNet architecture
    """
    def __init__(self, num_classes=1):
        super().__init__()
        # encoding
        self.conv1 = encoding_block(9, 32)
        self.maxpool1 = nn.MaxPool2d(kernel_size=2)
        self.conv2 = encoding_block(32, 64)
        self.maxpool2 = nn.MaxPool2d(kernel_size=2)
        self.conv3 = encoding_block(64, 128)
        self.maxpool3 = nn.MaxPool2d(kernel_size=2)
        self.conv4 = encoding_block(128, 256)
        self.maxpool4 = nn.MaxPool2d(kernel_size=2)

        # center
        self.center = encoding_block(256, 512)

        # decoding
        self.decode4 = decoding_block(512, 256)
        self.decode3 = decoding_block(256, 128)
        self.decode2 = decoding_block(128, 64)
        self.decode1 = decoding_block(64, 32)

        # final
        self.final = nn.Conv2d(32, num_classes, kernel_size=1)

    def forward(self, input):

        # encoding
        conv1 = self.conv1(input)
        maxpool1 = self.maxpool1(conv1)
        conv2 = self.conv2(maxpool1)
        maxpool2 = self.maxpool2(conv2)
        conv3 = self.conv3(maxpool2)
        maxpool3 = self.maxpool3(conv3)
        conv4 = self.conv4(maxpool3)
        maxpool4 = self.maxpool4(conv4)

        # center
        center = self.center(maxpool4)

        # decoding
        decode4 = self.decode4(conv4, center)
        decode3 = self.decode3(conv3, decode4)
        decode2 = self.decode2(conv2, decode3)
        decode1 = self.decode1(conv1, decode2)
        # final
        final = nn.functional.upsample(self.final(decode1), input.size()[2:], mode='bilinear')
        return final
Run Code Online (Sandbox Code Playgroud)

训练方法

def train(train_loader, model, criterion, optimizer, scheduler, epoch_num):

    correct = 0
    totalcount = 0

    scheduler.step()

    # iterate over data
    for idx, data in enumerate(tqdm(train_loader, desc="training")):
        # get the inputs and wrap in Variable
        if torch.cuda.is_available():
            inputs = Variable(data['sat_img'].cuda())
            labels = Variable(data['map_img'].cuda())
        else:
            inputs = Variable(data['sat_img'])
            labels = Variable(data['map_img'])

        optimizer.zero_grad()
        outputs = model(inputs)
        loss = criterion(outputs, labels.long())
        loss.backward()
        optimizer.step()

        test = torch.max(outputs.data, 1)[1] == labels.long()
        correct += test.sum().item()
        totalcount += test.size()[0] * test.size()[1] * test.size()[2]

    print('Training Loss: {:.4f}, Accuracy: {:.2f}'.format(loss.data[0], correct/totalcount))
    return {'train_loss': loss.data[0], 'train_acc' : correct/totalcount}
Run Code Online (Sandbox Code Playgroud)

epoch 循环中的训练调用

lr_scheduler.step()
train_metrics = train(train_dataloader, model, criterion, optimizer, lr_scheduler, epoch)
Run Code Online (Sandbox Code Playgroud)

一些纪元迭代输出

#### 纪元 0/19

---------- 培训:100%|???????????????????????????????????? ??????????????????????????????????????????| 84/84 [00:17<00:00, 5.77it/s] Training Loss: 0.8901, Accuracy: 0.83 当前经过时间 2m 6s

#### 纪元 1/19

---------- 培训:100%|???????????????????????????????????? ??????????????????????????????????????????| 84/84 [00:17<00:00, 5.72it/s] Training Loss: 0.7922, Accuracy: 0.83 当前经过时间 2m 24s

#### 纪元 2/19

---------- 培训:100%|???????????????????????????????????? ??????????????????????????????????????????| 84/84 [00:18<00:00, 5.44it/s] Training Loss: 0.8753, Accuracy: 0.84 当前经过时间 2m 42s

#### 时代 3/19

---------- 培训:100%|???????????????????????????????????? ??????????????????????????????????????????| 84/84 [00:18<00:00, 5.53it/s] Training Loss: 0.7741, Accuracy: 0.84 当前经过时间 3m 1s

Szy*_*zke 8

很难用这些信息调试你的模型,但也许其中一些想法会以某种方式帮助你:

  1. 尝试在更小的数据上过度拟合您的网络,并在许多时期内进行过拟合,而不先进行扩充,例如许多时期的一到两个批次。如果这个不起作用,那么您的模型无法对数据和所需目标之间的关系进行建模,或者您在某处出错。此外,以这种方式调试它更容易。
  2. 我不确定权重的想法,也许尝试对代表性不足的类进行上采样以使其更加平衡(在数据集中重复一些代表性不足的示例)。好奇这个想法是从哪里来的,从来没有听说过。
  3. 在应用您自己的自定义之前,您是否尝试过从您提供的存储库中运行模型?它的表现如何,你能复制他们的发现吗?根据我的理解,您为什么认为这种架构非常适合您的不同情况?您提供的链接中的损失函数不同,而架构是相同的。我没有读过这篇论文,也没有尝试过你的模型,但似乎有点奇怪。
  4. GitHub 存储库内的链接指向一篇博客文章,建议使用更大的批次,因为它可以稳定训练,您的批次大小是多少?
  5. 也许从更小更简单的模型开始,然后从那里开始工作?

最重要的最后来了;我不认为 SO 是解决此类问题的最佳场所(尤其是因为它是面向研究的),但我看到您已经在 GitHub 问题上询问过它,也许可以尝试直接联系作者?

如果我是你,我会从最后一点开始,彻底了解操作及其对你的目标的影响,祝你好运。