如何为具有多个标签的数据集使用Pytorch DataLoader



我想知道如何在Pytorch中创建一个支持多种类型标签的DataLoader。我该怎么做呢?

您可以返回数据集中每个项目的标签的dict, DataLoader足够聪明地为您整理它们。例如,如果您为每个项目提供一个dict, DataLoader将返回一个dict,其中键是标签类型。访问该标签类型的键将返回该标签类型的排序张量。

见下文:

import torch
from torch.utils.data import Dataset, DataLoader
import numpy as np
class M(Dataset):
def __init__(self):
super().__init__()
self.data = np.random.randn(20, 2)
print(self.data)
def __getitem__(self, i):
return self.data[i], {'label_1':self.data[i], 'label_2':self.data[i]}
def __len__(self):
return len(self.data)
ds = M()
dl = DataLoader(ds, batch_size=6)
for x, y in dl:
print(x, 'n', y)
print(type(x), type(y))
[[-0.33029911  0.36632142]
[-0.25303721 -0.11872778]
[-0.35955625 -1.41633132]
[ 1.28814629  0.38238357]
[ 0.72908184 -0.09222787]
[-0.01777293 -1.81824167]
[-0.85346074 -1.0319562 ]
[-0.4144832   0.12125039]
[-1.29546792 -1.56314292]
[ 1.22566887 -0.71523568]]
tensor([[-0.3303,  0.3663],
[-0.2530, -0.1187],
[-0.3596, -1.4163]], dtype=torch.float64) 
{'item_1': tensor([[-0.3303,  0.3663],
[-0.2530, -0.1187],
[-0.3596, -1.4163]], dtype=torch.float64), 'item_2': tensor([[-0.3303,  0.3663],
[-0.2530, -0.1187],
[-0.3596, -1.4163]], dtype=torch.float64)}
<class 'torch.Tensor'> <class 'dict'>
...

最新更新