Reputation: 161
I have a custom data set of images and its target. I have created a training data set in PyTorch. I want to split it into 3 parts: training, validation and test. How do I do it?
Upvotes: 2
Views: 10369
Reputation: 47003
Given parameter train_frac=0.8
, this function will split the dataset
into 80%, 10%, 10%:
import torch, itertools
from torch.utils.data import TensorDataset
def dataset_split(dataset, train_frac):
'''
param dataset: Dataset object to be split
param train_frac: Ratio of train set to whole dataset
Randomly split dataset into a dictionary with keys, based on these ratios:
'train': train_frac
'valid': (1-split_frac) / 2
'test': (1-split_frac) / 2
'''
assert split_frac >= 0 and split_frac <= 1, "Invalid training set fraction"
length = len(dataset)
# Use int to get the floor to favour allocation to the smaller valid and test sets
train_length = int(length * train_frac)
valid_length = int((length - train_length) / 2)
test_length = length - train_length - valid_length
dataset = random_split(dataset, (train_length, valid_length, test_length))
dataset = {name: set for name, set in zip(('train', 'valid', 'test'), sets)}
return dataset
Upvotes: 1
Reputation: 114936
Once you have the "master" dataset you can use data.Subset
to split it.
Here's an example for random split
import torch
from torch.utils import data
import random
master = data.Dataset( ... ) # your "master" dataset
n = len(master) # how many total elements you have
n_test = int( n * .05 ) # number of test/val elements
n_train = n - 2 * n_test
idx = list(range(n)) # indices to all elements
random.shuffle(idx) # in-place shuffle the indices to facilitate random splitting
train_idx = idx[:n_train]
val_idx = idx[n_train:(n_train + n_test)]
test_idx = idx[(n_train + n_test):]
train_set = data.Subset(master, train_idx)
val_set = data.Subset(master, val_idx)
test_set = data.Subset(master, test_idx)
This can also be achieved using data.random_split
:
train_set, val_set, test_set = data.random_split(master, (n_train, n_val, n_test))
Upvotes: 12