Get target list from Dataset

Hi, Can I get target list from Dataset object?
like [0, 1, 0, 3, 5, …]
I am getting it by loop code like the last 3 rows of the code below, but it’s not only time consuming, but also looks not good.
Thank you for any advice.

    train_dataset = ImageFolder(os.path.join(data_dir), train_transform)

    # Temporary dataset and dataloader to create train/val split
    trainval_dataset = ImageFolder(os.path.join(data_dir), transform=transforms.ToTensor()) 
    trainval_loader = DataLoader(trainval_dataset, batch_size=train_batch_size,
                                 shuffle=False, drop_last=False,
                                 num_workers=num_workers, pin_memory=False)

    train_indices, val_indices = get_train_val_indices(trainval_loader, fold_index=fold_index, n_splits=5)

    train_dataset = Subset(train_dataset, train_indices)
    targetlst = []
    for i in range(len(train_dataset)):
        image, target = train_dataset[i]

Since train_dataset is an instance of ImageFolder which is really just an instance of DatasetFolder, you can access it directly e.g.,

targetlst = list(train_dataset.targets)

If you don’t mutate targetlst you can likely get away with using train_dataset.targets directly.

Relevant code in torchvision:

1 Like

Thank you!
It seems Subset object has no “targets” attribute, but I could make it with ImageFolder, as you said.