【问题标题】:Loading a huge dataset batch-wise to train pytorch批量加载庞大的数据集以训练 pytorch
【发布时间】:2019-12-29 20:25:13
【问题描述】:

我正在训练 LSTM,以便将时间序列数据分为 2 类(0 和 1)。我在 0 类和 1 类数据所在的驱动器上有大量数据集在不同的文件夹中。我试图通过创建一个 Dataset 类并将 DataLoader 包装在它周围来批量训练 LSTM。我必须进行预处理,例如重塑。这是我的代码

`

class LoadingDataset(Dataset):
  def __init__(self,data_root1,data_root2,file_name):
    self.data_root1=data_root1#Has the path for class1 data
    self.data_root2=data_root2#Has the path for class0 data
    self.fileap1= pd.DataFrame()#Stores class 1 data
    self.fileap0 = pd.DataFrame()#Stores class 0 data
    self.file_name=file_name#List of all the files at data_root1 and data_root2
    self.labs1=None #Will store the class 1 labels
    self.labs0=None #Will store the class 0 labels

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

  def __getitem__(self, index):        
    self.fileap1 = pd.read_csv(self.data_root1+self.file_name[index],header=None)#read the csv file for class 1
    self.fileap1=self.fileap1.iloc[1:,1:].values.reshape(-1,WINDOW+1,1)#reshape the file for lstm
    self.fileap0 = pd.read_csv(self.data_root2+self.file_name[index],header=None)#read the csv file for class 0
    self.fileap0=self.fileap0.iloc[1:,1:].values.reshape(-1,WINDOW+1,1)#reshape the file for lstm
    self.labs1=np.array([1]*len(self.fileap1)).reshape(-1,1)#create the labels 1 for the csv file
    self.labs0=np.array([0]*len(self.fileap0)).reshape(-1,1)#create the labels 0 for the csv file
    # print(self.fileap1.shape,' ',self.fileap0.shape)
    # print(self.labs1.shape,' ',self.labs0.shape)
    self.fileap1=np.append(self.fileap1,self.fileap0,axis=0)#combine the class 0 and class one data
    self.fileap1 = torch.from_numpy(self.fileap1).float()
    self.labs1=np.append(self.labs1,self.labs0,axis=0)#combine the label0 and label 1 data
    self.labs1 = torch.from_numpy(self.labs1).int()
    # print(self.fileap1.shape,' ',self.fileap0.shape)
    # print(self.labs1.shape,' ',self.labs0.shape)

    return self.fileap1,self.labs1

data_root1 = '/content/gdrive/My Drive/Data/Processed_Data/Folder1/One_'#location of class 1 data
data_root2 = '/content/gdrive/My Drive/Data/Processed_Data/Folder0/Zero_'#location of class 0 data
training_set=LoadingDataset(data_root1,data_root2,train_ind)#train_ind is a list of file names that have to be read from data_root1 and data_root2
training_generator = DataLoader(training_set,batch_size =2,num_workers=4)

for epoch in range(num_epochs):
  model.train()#Setting the model to train mode after eval mode to train for next epoch once the testing for that epoch is finished
  for i, (inputs, targets) in enumerate(train_loader):
    .
    .
    .
    .

` 运行此代码时出现此错误

RuntimeError: Traceback(最近一次调用最后一次): _worker_loop 中的文件“/usr/local/lib/python3.6/dist-packages/torch/utils/data/_utils/worker.py”,第 99 行 samples = collat​​e_fn([dataset[i] for i in batch_indices]) 文件“/usr/local/lib/python3.6/dist-packages/torch/utils/data/_utils/collat​​e.py”,第 68 行,在 default_collat​​e return [default_collat​​e(samples) for samples in transposed] 文件“/usr/local/lib/python3.6/dist-packages/torch/utils/data/_utils/collat​​e.py”,第 68 行,在 return [default_collat​​e(samples) for samples in transposed] 文件“/usr/local/lib/python3.6/dist-packages/torch/utils/data/_utils/collat​​e.py”,第 43 行,在 default_collat​​e 返回 torch.stack(batch, 0, out=out) RuntimeError:无效参数 0:张量的大小必须匹配,但维度 0 除外。在 /pytorch/aten/src/TH/generic/THTensor.cpp:711 的维度 1 中获得 96596 和 25060

我的问题是 1.我是否正确地实现了这一点,你是这样预处理然后批量训练数据集的吗?

2.DataLoader的batch_size和LSTM的batch_size不同,因为DataLoader的batch_size是指编号。文件的数量,而 LSTM 模型的 batch_size 是指编号。的实例,所以我会在这里得到另一个错误吗?

3.我不知道如何缩放这个数据集,因为 MinMaxScaler 必须应用于整个数据集。

感谢您的回复。如果我必须为每个问题创建单独的帖子,请告诉我。

谢谢。

【问题讨论】:

    标签: python machine-learning dataset artificial-intelligence pytorch


    【解决方案1】:

    这里总结一下pytorch是如何做事的:

    • 您有一个dataset,它是一个具有__len__ 方法和__getitem__ 方法的对象。
    • 您从datasetcollate_fn 创建一个dataloader
    • 您遍历dataloader 并将一批数据传递给您的模型。

    所以基本上你的训练循环看起来像

    for x, y in dataloader:
        output = model(x)
    ...
    

    for x, y in dataloader:
            output = model(*x)
        ...
    

    如果您的模型 forward 方法采用多个参数。

    那么这是如何工作的呢? 基本上你有一个批处理索引生成器batch_sampler,这就是你的数据加载器内部循环的行为。

    for indices in batch_sampler:
        yield collate_fn([dataset[i] for i in indices])
    

    因此,如果您希望一切正常,您必须查看模型的forward 方法并查看它需要多少个参数(根据我的经验,LSTM 的前向方法可以有多个参数),并确保您使用collate_fn 正确传递这些。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-02-20
      • 1970-01-01
      • 2020-05-27
      • 2021-08-25
      • 2019-08-06
      • 1970-01-01
      • 2021-04-05
      • 2018-09-22
      相关资源
      最近更新 更多