3

我已将我的 GitHub 存储库克隆到 google colab 并尝试使用 PyTorch 的 DataLoader 加载数据。

global gpu, device
if torch.cuda.is_available():
    gpu = True
    device = 'cuda:0'
    torch.set_default_tensor_type('torch.cuda.FloatTensor')
    print("Using GPU")
else:
    gpu = False
    device = 'cpu'
    print("Using CPU")

data_transforms = transforms.Compose([
    #transforms.Resize(224),
    transforms.ToTensor(),
    transforms.Normalize([0.3112, 0.2636, 0.2047], [0.2419, 0.1972, 0.1554])
    ])
train_path = '/content/convLSTM/code/data/train/'
val_path = '/content/convLSTM/code/data/val/'
test_path = '/content/convLSTM/code/data/test/'

train_data = datasets.ImageFolder(root=train_path, transform=data_transforms)
val_data = datasets.ImageFolder(root=val_path, transform=data_transforms)
test_data = datasets.ImageFolder(root=test_path, transform=data_transforms)

train_loader = torch.utils.data.DataLoader(
    train_data,
    batch_size=18,
    num_workers=4,
    shuffle=False,
    pin_memory=True
    )

val_loader = torch.utils.data.DataLoader(
    val_data,
    batch_size=18,
    shuffle=False,
    num_workers=4,
    pin_memory=True
    )

test_loader = torch.utils.data.DataLoader(
    test_data,
    batch_size=18,
    shuffle=False,
    num_workers=4,
    pin_memory=True
    )
for batch_idx, (data, target) in enumerate(train_loader):
  print(batch_idx)
  if batch_idx==3:
    break

运行最后一个 for 循环时出现以下错误:

RuntimeError: Cannot re-initialize CUDA in forked subprocess. To use CUDA with multiprocessing, you must use the 'spawn' start method

我尝试num_workers = 1了,4但错误仍然存​​在。我没有使用任何多处理。

我也试过不设置torch.set_default_tensor_type('torch.cuda.FloatTensor'),但错误仍然存​​在。

蟒蛇:3.6.8 | 火炬:1.3.1

似乎是什么问题?

4

2 回答 2

6

不确定您是否已经修复它,但以防万一其他人阅读此内容,使用 n 件作品激活 pytorch 多处理。要禁用它,您需要拥有默认的工作人员数量,即 0,而不是 1。

尝试将 num_workers 设置为 0 或使用Torch Multiprocessing 子模块

于 2020-01-25T18:28:25.693 回答
1

试着把num_workers=0

dataloader = DataLoader(dataset, batch_size=batch_size, shuffle=True, num_workers=0)

这解决了 Kaggle notebook 的问题

于 2021-12-15T07:15:15.520 回答