训练和验证步骤中的PyTorch无限循环 [英] PyTorch infinite loop in the training and validation step

查看:0
本文介绍了训练和验证步骤中的PyTorch无限循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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'])

推荐答案

我遇到了同样的问题,问题是Jupyter笔记本可能无法正常运行文档中所述的多处理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可以提供帮助。

这篇关于训练和验证步骤中的PyTorch无限循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆