【问题标题】:PyTorch infinite loop in the training and validation step训练和验证步骤中的 PyTorch 无限循环
【发布时间】:2026-01-28 16:25:02
【问题描述】:

Dataset 和 DataLoader 的部分没问题,我从我构建的另一个代码中回收,但在我的代码中该部分出现了无限循环:

def train(train_loader, MLP, epoch, criterion, optimizer):

 MLP.train()
 epoch_loss = []

 for batch in train_loader:

    optimizer.zero_grad()
    sample, label = batch

    #Forward
    pred = MLP(sample)
    loss = criterion(pred, label)
    epoch_loss.append(loss.data)

    #Backward
    loss.backward()
    optimizer.step()

 epoch_loss = np.asarray(epoch_loss)

 print('Epoch: {}, Loss: {:.4f} +/- {:.4f}'.format(epoch+1, 
 epoch_loss.mean(), epoch_loss.std()))



def test(test_loader, MLP, epoch, criterion):

 MLP.eval()
 with torch.no_grad():
    epoch_loss = []

    for batch in train_loader:

        sample, label = batch

        #Forward
        pred = MLP(sample)
        loss = criterion(pred, label)
        epoch_loss.append(loss.data)

    epoch_loss = np.asarray(epoch_loss)

    print('Epoch: {}, Loss: {:.4f} +/- {:.4f}'.format(epoch+1, 
    epoch_loss.mean(), epoch_loss.std()))

然后,我把它放在迭代的时代:

for epoch in range(args['num_epochs']):
    train(train_loader, MLP, epoch, criterion, optimizer)
    test(test_loader, MLP, epoch, criterion)
    print('-----------------------')

由于它连第一个损失数据都没有打印,我认为逻辑错误在训练函数中,但我不知道它在哪里。

编辑:这是我的 MLP 课程,问题也可能在这里:

class BikeRegressor(nn.Module):

 def __init__(self, input_size, hidden_size, out_size):
    super(BikeRegressor, self).__init__()
    
    self.features = nn.Sequential(nn.Linear(input_size, hidden_size),
                                  nn.ReLU(),
                                  nn.Linear(hidden_size, hidden_size),
                                  nn.ReLU())
    
    self.out = nn.Sequential(nn.Linear(hidden_size, out_size),
                             nn.ReLU())
    
 def forward(self, X):
    
    hidden = self.features(X)
    output = self.out(hidden)
    
    return output

编辑 2:数据集和数据加载器:

class Bikes(Dataset):
 def __init__(self, data): #data is a Dataframe from Pandas
    self.datas = data.to_numpy()
    
 def __getitem__(self, idx): 
    sample = self.datas[idx][2:14] 
    label = self.datas[idx][-1:] 
    
    
    sample = torch.from_numpy(sample.astype(np.float32))
    label = torch.from_numpy(label.astype(np.float32))
    
    return sample, label

 def __len__(self):
    return len(self.datas)



train_set = Bikes(ds_train)
test_set = Bikes(ds_test)



train_loader = DataLoader(train_set, batch_size=args['batch_size'], shuffle=True, num_workers=args['num_workers'])
test_loader = DataLoader(test_set, batch_size=args['batch_size'], shuffle=True, num_workers=args['num_workers'])

【问题讨论】:

  • 我觉得你需要试试 loss.backward()
  • @GaussianPrior 是的,哈哈,我真的忘记了(),但问题仍然存在..
  • 你的函数结构有问题,你应该正确地设计火车的主体并正确测试函数。
  • 你的代码是否完成了第一个训练周期?另外,你的批量有多大?是否有可能您的计算机实际上正在计算东西,但您看不到它,因为它没有使用 GPU,而且它太大了?
  • @aaossa 它没有,因此我认为存在逻辑问题或类似问题。我不认为缺少 GPU 是问题,因为我遇到了 MNIST 问题(60000 张图像 28x28),并且当前数据集的形状为 (17379, 12),并没有那么大。批量大小为 20

标签: neural-network pytorch regression mlp


【解决方案1】:

我遇到了同样的问题,问题是 jupyter notebook 可能无法正常使用多处理,如 here 所述:

注意此包中的功能需要 __ main __ 模块可由孩子们导入。这在编程中有所介绍 指南但是值得在这里指出。 This means that some examples, such as the Pool examples will not work in the interactive interpreter.

您可以通过三个选项来解决您的问题:

  • train_loadertest_loader 中设置num_worker = 0。 (最简单的)
  • 将您的代码移至 google colab。它适用于num_worker = 6,但我认为这取决于您的程序将使用多少内存。因此,请尝试逐渐增加 num_worker,直到您的程序兑现并告诉您您的程序内存不足。
  • 在 jupyter 中调整您的程序以支持多处理,这些资源 12 可以提供帮助。

【讨论】:

  • 哦,第一个真的很有帮助,谢谢!这种问题很烂哈哈,最后不是逻辑错误(取一些代码错误)