首页 > 解决方案 > 使用 CrossEntropyLoss 的 PyTorch 多类分类 - 不收敛

问题描述

我试图获得一个简单的网络来输出一个数字属于三个类别之一的概率。这些是小于 1.1、介于 1.1 和 1.5 之间以及大于 1.5。我正在使用类别标签为 0、1 和 2 的交叉熵损失,但无法解决问题。

每次我训练时,无论输入如何,网络都会输出第 2 类的最大概率。我似乎能够达到的最低损失是 0.9ish。任何关于我哪里出错的建议将不胜感激!所有代码如下。

class gating_net(nn.Module):
    def __init__(self, input_dim, output_dim):
        super(gating_net, self).__init__()
        self.linear1 = nn.Linear(input_dim, 32)
        self.linear2 = nn.Linear(32, output_dim)

    def forward(self, x):
        # The original input (action) is used as the residual.
        x = F.relu(self.linear1(x))
        x = F.sigmoid(self.linear2(x))
        return x

learning_rate = 0.01
batch_size = 64
epochs = 500
test = 1

gating_network = gating_net(1,3)

optimizer = torch.optim.SGD(gating_network.parameters(), lr=learning_rate, momentum=0.9)
scheduler = ReduceLROnPlateau(optimizer, mode='max', factor=0.5, patience=20, verbose=True)

for epoch in range (epochs):
    input_ = []
    label_ = []

    for i in range (batch_size):
        scale = random.randint(10,20)/10

        input = scale
        if scale < 1.1:
            label = np.array([0])
        elif 1.1 < scale < 1.5:
            label = np.array([1])
        else:
            label = np.array([2])

        input_.append(np.array([input]))
        label_.append(label)

    optimizer.zero_grad()

    # get output from the model, given the inputs
    output = gating_network.forward(torch.FloatTensor(input_))
    old_label  = torch.FloatTensor(label_)

    # get loss for the predicted output
    loss = nn.CrossEntropyLoss()(output, old_label.squeeze().long())

    # get gradients w.r.t to parameters
    loss.backward()
    # update parameters
    optimizer.step()
    scheduler.step(loss)

    print('epoch {}, loss {}'.format(epoch, loss.item()))

    if loss.item() < 0.01:
        print("########## Solved! ##########")
        torch.save(mod_network.state_dict(), './supervised_learning/run_{}.pth'.format(test))
        break

    # save every 500 episodes
    if epoch % 100 == 0:
        torch.save(gating_network.state_dict(), './run_{}.pth'.format(test))

标签: pytorchclassificationcross-entropy

解决方案


  • 您的代码在每个时期(在这种情况下也是每个批次)生成训练数据。这是非常多余的,但这并不意味着代码不起作用。然而,影响训练的一件事是类之间训练数据的不平衡。使用您的代码,大部分训练数据总是被标记2。如此直观地,您的网络将始终了解更多关于 class 的信息2。这就是为什么在非常小的 500 时期,网络将所有类别分类为2,因为这是降低损失的快速简便的方法。然而,当网络不能通过应用关于 label 的知识来降低损失时2,它也会学习1and 0。因此可以训练网络,尽管效率不高。
  • 继续上一期,使用ReduceLROnPlateau也效率不高,因为在网络开始学习标签01,学习率已经很小(直观地说)。并不意味着它是不可训练的,但它可能需要很多时间。
  • CrossEntropyLoss内部计算LogSoftmax,所以Sigmoid在网络末端意味着你有Softmax一层又Sigmoid一层,这可能不是你想要的。我认为网络不一定是“错误的”,但训练起来会困难得多。
  • 实际上 scale1.1被标记2是因为你有<1.1>1.1

TL;博士

摆脱sigmoidscheduler。我能够获得Solved!大约 15000 个 epoch(学习率和批量大小与您的代码相同)。


推荐阅读