I'm spliting some data in train and test set according to group values. How can I do this in order to have balanced data?
In order to solve a binary classification task I have 100 samples, each one with a unique ID a subject and a label(1 or 0).
In order to avoid to degenerate in a person recognition task, I need that the same subject cant be in both training and test set.
The number of subjects is less then the number of samples (57), some subject appears in only one sample other in many with same or different label.
I can simply do that using gropKfold from sklearn but I would like my data to be balanced (or at least close to be)
I tried with the following code:
n_shuffles = 2
group_k_fold = GroupKFold(n_splits=5)
for i in range(n_shuffles):
X_shuffled, y_shuffled, groups_shuffled = shuffle(idx, labels, subjects, random_state=i)
splits = group_k_fold.split(X_shuffled, y_shuffled, groups_shuffled)
for train_idx, val_idx in splits:
X = perezDataFrame.loc[perezDataFrame['ID'].isin(X_shuffled[train_idx]),AU_names].values
X = preprocessing.normalize(X, norm='l2')
y = perezDataFrame.loc[perezDataFrame['ID'].isin(X_shuffled[train_idx]),'label'].values
XTest = perezDataFrame.loc[perezDataFrame['ID'].isin(X_shuffled[val_idx]),AU_names].values
XTest = preprocessing.normalize(XTest, norm='l2')
yTest = perezDataFrame.loc[perezDataFrame['ID'].isin(X_shuffled[val_idx]),'label'].values
Where idx, subjects and labels are respectivlly a list of ID, subjects and labels.
But data were very unbalanced.
I also tried this:
for i in range(5):
GSP = GroupShuffleSplit(n_splits =10, test_size =0.20, train_size=0.80 ,random_state=i)
splits = GSP.split(idx, labels, subjects)
for train_idx, test_idx in splits:
.....
But this is not Kfold so I have no guarantee that same sample stay in just one fold.