Pytorch 使用Dataloader 遇到stack expects each tensor to be equal size 和Trying to resize storage that is not resizable 问题
出现这两个问题的关键都在__getitem()函数中,获取后拼接batch出现张量维度不相等。
我的源代码
return {'pc': pc,
'intensity': intensity,
'sn': sn,
'P': P,
'img': img,
'K': K,
'pc_mask': torch.from_numpy(pc_mask).float(),
'img_mask': torch.from_numpy(img_mask).float(), # (40,128)
'pc_kpt_idx': torch.from_numpy(pc_kpt_idx), # 512
'pc_outline_idx': torch.from_numpy(pc_outline_idx), # 512
'img_kpt_idx': torch.from_numpy(img_kpt_index).long(), # 512
'img_outline_index': torch.from_numpy(img_outline_index).long(),
'node_a': torch.from_numpy(node_a_np).float(),
'node_b': torch.from_numpy(node_b_np).float()
}
在出现这个问题后,将Dataloader的batch_size设为1,num_worker设为0并且将输出的tensor尺寸打印出来,寻找异常值。
if ((pc_outline_idx.shape[0] < self.opt.num_kpt) | (img_kpt_index.shape[0] < self.opt.num_kpt) | (img_outline_index.shape[0] < self.opt.num_kpt)):
#异常值条件
print('pc_outline_idx.shape[0]: ',pc_outline_idx.shape[0]
,'img_kpt_index.shape[0]: ',img_kpt_index.shape[0]
,'img_outline_index.shape[0]: ',img_outline_index.shape[0])
#记录异常值信息
with open('data_clean_train.txt', 'a') as file:
file.write(os.path.join(self.root, traversal, lidar_name, '%d.npy' % pc_timestamp) + ',' + os.path.join(camera_folder, "%d.jpg" % camera_timestamp) + '\n')
return {'pc': pc,
'intensity': intensity,
'sn': sn,
'P': P,
'img': img,
'K': K,
'pc_mask': torch.from_numpy(pc_mask).float(),
'img_mask': torch.from_numpy(img_mask).float(), # (40,128)
'pc_kpt_idx': torch.from_numpy(pc_kpt_idx), # 512
'pc_outline_idx': torch.from_numpy(pc_outline_idx), # 512
'img_kpt_idx': torch.from_numpy(img_kpt_index).long(), # 512
'img_outline_index': torch.from_numpy(img_outline_index).long(),
'node_a': torch.from_numpy(node_a_np).float(),
'node_b': torch.from_numpy(node_b_np).float()
}
其实就是一个数据清洗的过程。也可以进行强制补0之类的操作,但后续处理起来相对麻烦,还是建议数据清洗方式。