How can I split a continuous target into a train/test set such that the mean and standard deviation are the same?

I'm trying to do an 80-20 split on my target so that the distributions are the same. I've tried using cvpartition but I don't believe it can handle a continuous target. Suggestions to use N don't result in a split that maintains the distribution of my target
target = randn(100, 1);
cv = cvpartition(100, 'Holdout', 0.2);
train_idx = training(cv);
test_idx = test(cv);
figure;
hold on;
H_TRAIN = histogram(target(train_idx));
H_TEST = histogram(target(test_idx));
legend([H_TRAIN; H_TEST], {'Train', 'Test'});
hold off;
[h,p,ks2stat] = kstest2(target(train_idx), target(test_idx))
Running a two-sample KS-test returns that the null hypothesis that both samples came from the same continuous distribution can't be rejected, but is this the way to know for certain that my target is split correctly?

Answers (1)

The way to do it is to bin the target into bins depending on what makes sense for your target.
target = randn(100, 1);
binned_target = discretize(target, 5);
cv_new = cvpartition(binned_target, 'Holdout', 0.2, 'Stratify', true);
Warning: One or more of the unique class values in GROUP is not present in the training set. For classification problems, either remove this class from the data or use N instead of GROUP to obtain nonstratified partitions. For regression problems with continuous response, use N.
new_train_idx = training(cv_new);
new_test_idx = test(cv_new);
figure;
hold on;
H2_TRAIN = histogram(target(new_train_idx), 5);
H2_TEST = histogram(target(new_test_idx)), 5;
H2_TEST =
Histogram with properties: Data: [20×1 double] Values: [1 2 9 5 3] NumBins: 5 BinEdges: [-3 -2 -1 0 1 2] BinWidth: 1 BinLimits: [-3 2] Normalization: 'count' FaceColor: 'auto' EdgeColor: [0 0 0] Show all properties
legend([H2_TRAIN; H2_TEST], {'Binned Train', 'Binned Test'});
hold off;

Categories

Find more on MATLAB Coder in Help Center and File Exchange

Products

Release

R2022b

Asked:

on 12 Jun 2023

Answered:

on 13 Jun 2023

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!