Repository files navigation

Uwe Reichel, audEERING GmbH, Gilching, Germany

  • machine learning data splitting tool that allows for:
    • group-disjunct splits (e.g. different speakers in train, dev, and test partition)
    • stratification on multiple target and grouping variables (e.g. emotion, gender, language)

From PyPI

  • set up a virtual environment venv_splitutils, activate it, and install splitutils. For Linux this works e.g. as follows:
$ virtualenv --python="/usr/bin/python3" venv_splitutils
$ source venv_splitutils/bin/activate
(venv_splitutils) $ pip install splitutils

From GitHub

$ git clone git@github.com:reichelu/spliutils.git
$ cd splitutils/
$ virtualenv --python="/usr/bin/python3" venv_splitutils
$ source venv_splitutils/bin/activate
$ (venv_splitutils) $ pip install -r requirements.txt
defoptimize_traintest_split(X, y, split_on, stratify_on, weight=None,
test_size=.1, k=30, seed=42):
''' optimize group-disjunct split into training and test set which is guided by: - disjunct split of values in SPLIT_ON - stratification by all keys in STRATIFY_ON (targets and groupings) - test set proportion in X should be close to test_size (which is the test proportion in set(split_on)) Parameters: X: (np.array or pd.DataFrame) of features y: (np.array) of targets of length N if type(y[0]) in ["str", "int"]: y is assumed to be categorical, so that it is additionally tested that all partitions cover all classes. Else y is assumed to be numeric and no coverage test is done. split_on: (np.array) list of length N with grouping variable (e.g. speaker IDs), on which the group-disjunct split is to be performed. Must be categorical. stratify_on: (dict) Dict-keys are variable names (targets and/or further groupings) the split should be stratified on (groupings could e.g. be sex, age class, etc). Dict-Values are np.array-s of length N that contain the variable values. All variables must be categorical. weight: (dict) weight for each variable in stratify_on. Defines their amount of contribution to the optimization score. Uniform weighting by default. Additional key: "size_diff" defines how test size diff should be weighted. test_size: (float) test proportion in set(split_on), e.g. 10% of speakers to be held-out k: (int) number of different splits to be tried out seed: (int) random seed Returns: train_i: (np.array) train set indices in X test_i: (np.array) test set indices in X info: (dict) detail information about reference and achieved prob distributions "size_testset_in_spliton": intended test_size "size_testset_in_X": optimized test proportion in X "p_ref_{c}": reference class distribution calculated from stratify_on[c] "p_test_{c}": test set class distribution calculated from stratify_on[c][test_i] '''
defoptimize_traindevtest_split(X, y, split_on, stratify_on, weight=None,
dev_size=.1, test_size=.1, testset_not_smaller=False,
k=30, seed=42):
''' optimize group-disjunct split into training, dev, and test set, which is guided by: - disjunct split of values in SPLIT_ON - stratification by all keys in STRATIFY_ON (targets and groupings) - test set proportion in X should be close to test_size (which is the test proportion in set(split_on)) Parameters: X: (np.array or pd.DataFrame) of features y: (np.array) of targets of length N if type(y[0]) in ["str", "int"]: y is assumed to be categorical, so that it is additionally tested that all partitions cover all classes. Else y is assumed to be numeric and no coverage test is done. split_on: (np.array) list of length N with grouping variable (e.g. speaker IDs), on which the group-disjunct split is to be performed. Must be categorical. stratify_on: (dict) Dict-keys are variable names (targets and/or further groupings) the split should be stratified on (groupings could e.g. be sex, age class, etc). Dict-Values are np.array-s of length N that contain the variable values. All variables must be categorical. weight: (dict) weight for each variable in stratify_on. Defines their amount of contribution to the optimization score. Uniform weighting by default. Additional key: "size_diff" defines how the corresponding size differences should be weighted. dev_size: (float) proportion in set(split_on) for dev set, e.g. 10% of speakers to be held-out test_size: (float) test proportion in set(split_on) for test set testset_not_smaller (bool) if True, and if test_size >= dev_size, it is ensured, that the resulting test set is not smaller than the dev set k: (int) number of different splits to be tried out seed: (int) random seed Returns: train_i: (np.array) train set indices in X dev_i: (np.array) dev set indices in X test_i: (np.array) test set indices in X info: (dict) detail information about reference and achieved prob distributions "dev_size_in_spliton": intended grouping dev_size "dev_size_in_X": optimized dev proportion of observations in X "test_size_in_spliton": intended grouping test_size "test_size_in_X": optimized test proportion of observations in X "p_ref_{c}": reference class distribution calculated from stratify_on[c] "p_dev_{c}": dev set class distribution calculated from stratify_on[c][dev_i] "p_test_{c}": test set class distribution calculated from stratify_on[c][test_i] '''
defbinning(x, nbins=2, lower_boundaries=None, seed=42):
''' bins numeric data. If X is one-dimensional: binning is done either intrinsically into nbins classes based on an equidistant percentile split, or extrinsically by using the lower_boundaries values. If X is two-dimensional binning is done by kmeans clustering into nbins clusters Parameters: x: (list, np.array) with numeric data. nbins: (int) number of bins lower_boundaries: (list) of lower bin boundaries. If y is 1-dim and lower_boundaries is provided, nbins will be ignored and y is binned extrinsically. The first value of lower_boundaries is always corrected not to be higher than min(y). seed: (int) random seed for kmeans Returns: c: (np.array) integers as bin IDs '''

if you use this software for a publication please cite:

Reichel, U.: splitutils - machine learning data partitioning software, version 0.3.0. doi:10.5281/zenodo.10793086, 2024.

@Misc{splitutils,
author = {Reichel, U.},
title = {splitutils -- machine learning data partitioning software, version 0.3.0},
howpublished = {doi:10.5281/zenodo.10793086},
year = {2024}
}
  • see scripts/run_traintest_split.py
  • partitions are:
    • disjunct on categorical "split_var"
    • stratified on categorical "target", "strat_var1", "strat_var2"
    • each contain all levels of "target"
importnumpyasnpimportosimportsys# add this line if you have cloned the code from github to PROJECT_DIR# sys.path.append(PROJECT_DIR)fromsplitutilsimportoptimize_traindevtest_split# set seedseed=42np.random.seed(seed)
# DUMMY DATA# sizen=100# feature arraydata=np.random.rand(100, 20)
# target variabletarget=np.random.choice(["A", "B"], size=n, replace=True)
# array with variable on which to do a disjunct splitsplit_var=np.random.choice(["D", "E", "F", "G", "H", "I", "J", "K"],
size=n, replace=True)
# dict of variables to stratify on. Key names are arbitrary.stratif_vars= {
"target": target,
"strat_var1": np.random.choice(["L", "M"], size=n, replace=True),
"strat_var2": np.random.choice(["N", "O"], size=n, replace=True)
}
# ARGUMENTS# weight importance of all stratification variables in stratify_in# as well as of "size_diff", which punishes the deviation of intended# and received partition sizes.# Key names must match the names in stratif_vars.weights= {
"target": 2,
"strat_var1": 1,
"strat_var2": 1,
"size_diff": 1
}
# test partition proportion (from 0 to 1)test_size=.2# number of disjunct splits to be tried out in brute force optimizationk=30# FIND OPTIMAL SPLITtrain_i, test_i, info=optimize_traintest_split(
X=data,
y=target,
split_on=split_var,
stratify_on=stratif_vars,
weight=weights,
test_size=test_size,
k=k,
seed=seed
)
# SOME OUTPUTprint("test levels of split_var:", sorted(set(split_var[test_i])))
print("goodness of split:", info)
  • see scripts/run_traindevtest_split.py
  • Partitions are
    • disjunct on categorical "split_var"
    • stratified on categorical "target", "strat_var1", "strat_var2"
    • each contain all levels of "target"
importnumpyasnpimportosimportsys# add this line if you have cloned the code from github to PROJECT_DIR# sys.path.append(PROJECT_DIR)fromsplitutilsimportoptimize_traindevtest_split# set seedseed=42np.random.seed(seed)
# DUMMY DATA# sizen=100# feature arraydata=np.random.rand(100, 20)
# target variabletarget=np.random.choice(["A", "B"], size=n, replace=True)
# array with variable on which to do a disjunct splitsplit_var=np.random.choice(["D", "E", "F", "G", "H", "I", "J", "K"],
size=n, replace=True)
# dict of variables to stratify on. Key names are arbitrary.stratif_vars= {
"target": target,
"strat_var1": np.random.choice(["F", "G"], size=n, replace=True),
"strat_var2": np.random.choice(["H", "I"], size=n, replace=True)
}
# ARGUMENTS# weight importance of all stratification variables in stratify_in# as well as of "size_diff", which punishes the deviation of intended# and received partition sizes.# Key names must match the names in stratif_vars.weights= {
"target": 2,
"strat_var1": 1,
"strat_var2": 1,
"size_diff": 1
}
# dev and test partition proportion (from 0 to 1)dev_size=.1test_size=.1# number of disjunct splits to be tried out in brute force optimizationk=30# FIND OPTIMAL SPLITtrain_i, dev_i, test_i, info=optimize_traindevtest_split(
X=data,
y=target,
split_on=split_var,
stratify_on=stratif_vars,
weight=weights,
dev_size=dev_size,
test_size=test_size,
k=k,
seed=seed
)
# SOME OUTPUTprint("test levels of split_var:", sorted(set(split_var[test_i])))
print("goodness of split:", info)
  • see scripts/run_traindevtest_split_with_binning.py
  • Partitions are
    • disjunct on categorical "split_var"
    • stratified on numeric "target", and on 3 other numeric stratification variables
importnumpyasnpimportosimportsys# add this line if you have cloned the code from github to PROJECT_DIR# sys.path.append(PROJECT_DIR)fromsplitutilsimport (
binning,
optimize_traindevtest_split
)
"""example script how to split dummy data into training, development,and test partitions that are* disjunct on categorical "split_var"* stratified on numeric "target", and on 3 other numeric stratification variables"""# set seedseed=42np.random.seed(seed)
# DUMMY DATA# sizen=100# featuresdata=np.random.rand(n, 20)
# numeric target variablenum_target=np.random.rand(n)
# array with variable on which to do a disjunct splitsplit_var=np.random.choice(["D", "E", "F", "G", "H", "I", "J", "K"],
size=n, replace=True)
# further numeric variables to stratify onnum_strat_vars=np.random.rand(n, 3)
# intrinsically bin target into 3 bins by equidistant# percentile boundariesbinned_target=binning(num_target, nbins=3)
# ... alternatively, a variable can be extrinsically binned by# specifying lower boundaries:# binned_target = binning(num_target, lower_boundaries=[0, 0.33, 0.66])# bin other stratification variables into a single variable with 6 bins# (2-dim input is binned by StandardScaling and KMeans clustering)binned_strat_var=binning(num_strat_vars, nbins=6)
# ... alternatively, each stratification variable could be binned# individually - intrinsically or extrinsically the same way as num_target# strat_var1 = binning(num_strat_vars[:,0], nbins=...) etc.# now add the obtained categorical variable to stratification dictstratif_vars= {
"target": binned_target,
"strat_var": binned_strat_var
}
# ARGUMENTS# weight importance of all stratification variables in stratify_in# as well as of "size_diff", which punishes the deviation of intended# and received partition sizesweights= {
"target": 2,
"strat_var": 1,
"size_diff": 1
}
# dev and test partition proportion (from 0 to 1)dev_size=.1test_size=.1# number of disjunct splits to be tried out in brute force optimizationk=30# FIND OPTIMAL SPLITtrain_i, dev_i, test_i, info=optimize_traindevtest_split(
X=data,
y=num_target,
split_on=split_var,
stratify_on=stratif_vars,
weight=weights,
dev_size=dev_size,
test_size=test_size,
k=k,
seed=seed
)
# SOME OUTPUTprint("test levels of split_var:", sorted(set(split_var[test_i])))
print("goodness of split:", info)
  • find optimal train, dev, and test set split based on:
    • disjunct split of a categorical grouping variable G (e.g. speaker)
    • optimized joint stratification on an arbitrary amount of categorical target and grouping variables (e.g. emotion, gender, ...)
    • close match of partition proportions in G and underlying dataset X
  • brute-force optimization on k disjunct splits of G
  • score to be minimzed for train/test set split:
(sum_v[w(v) * irad(v)] + w(d) * d) / (sum_v[w(v)] + w(d))
v: variables to be stratified on
w(v): their weight
irad(v): information radius between reference and test set distribution of factor levels in v
d: absolute difference between test proportions of X and G, i.e. between the proportion of test
samples and the proportion of groups (e.g. speakers) that go into the test set
w(d): its weight
  • score to be minimzed for train / dev / test set split:
(sum_v[w(v) * max_irad(v)] + w(d) * max_d) / (sum_v[w(v)] + w(d))
v: variables to be stratified on
w(v): their weight
max_irad(v): maximum information radius of reference distribution of classes in v and
- dev set distribution,
- test set distribution
max_d: maximum of absolute difference between proportions of X and G (see above) calculated for
the dev and test set
w(d): its weight
  • let's look at Example 2 above. There info becomes:
{
'score': 0.030828359568603338,
'size_devset_in_spliton': 0.1,
'size_devset_in_X': 0.14,
'size_testset_in_spliton': 0.1,
'size_testset_in_X': 0.13,
'p_target_ref': {'B': 0.49, 'A': 0.51},
'p_target_dev': {'A': 0.5, 'B': 0.5},
'p_target_test': {'A': 0.5384615384615384, 'B': 0.46153846153846156},
'p_strat_var1_ref': {'G': 0.56, 'F': 0.44},
'p_strat_var1_dev': {'G': 0.5714285714285714, 'F': 0.42857142857142855},
'p_strat_var1_test': {'F': 0.5384615384615384, 'G': 0.46153846153846156},
'p_strat_var2_ref': {'I': 0.48, 'H': 0.52},
'p_strat_var2_dev': {'I': 0.5, 'H': 0.5},
'p_strat_var2_test': {'I': 0.46153846153846156, 'H': 0.5384615384615384}
}
  • Explanations
    • score: see above, score to be minimzed for train / dev / test set split:
    • size_devset_in_spliton: proportion of to-be-split-on variable levels in development set
    • size_devset_in_X: proportion of rows in X in development set
    • size_testset_in_spliton: proportion of to-be-split-on variable levels in test set
    • size_testset_in_X: proportion of rows in X in test set
    • p_target_ref: reference target class distribution over all data
    • p_target_dev: target class distribution in development set
    • p_target_test: target class distribution in test set
    • p_strat_var1_ref: first stratification variable's reference distribution over all data
    • p_strat_var1_dev: first stratification variable's class distribution in development set
    • p_strat_var1_test: first stratification variable's class distribution in test set
    • p_strat_var2_ref: second stratification variable's reference distribution over all data
    • p_strat_var2_dev: second stratification variable's class distribution in development set
    • p_strat_var2_test: second stratification variable's class distribution in test set
  • Remarks
    • for splitutils.optimize_traintest_split() no development set results are reported
    • all *_strat_var* keys: key names derived from key names in stratify_on argument

About

machine learning data partitioning tool that allows for group-disjunct splits and stratification on multiple target and grouping variables

Resources

Stars

1 star

Watchers

1 watching

Forks

Releases

Packages

Used by

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Add copy buttons to all
 blocks\n(function() {\n function addCopyButtons() {\n document.querySelectorAll('pre code').forEach(function(codeBlock) {\n if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;\n codeBlock.parentElement.setAttribute('data-copy-added', 'true');\n \n var btn = document.createElement('button');\n btn.textContent = 'Copy';\n btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';\n btn.onmouseover = function() { this.style.opacity = '1'; };\n btn.onmouseout = function() { this.style.opacity = '0.7'; };\n btn.onclick = function() {\n navigator.clipboard.writeText(codeBlock.textContent).then(function() {\n btn.textContent = 'Copied!';\n setTimeout(function() { btn.textContent = 'Copy'; }, 1500);\n });\n };\n codeBlock.parentElement.style.position = 'relative';\n codeBlock.parentElement.appendChild(btn);\n });\n }\n \n addCopyButtons();\n \n // Re-run on dynamic content\n var observer = new MutationObserver(addCopyButtons);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Add Copy Buttons to Code Blocks");
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
Skip to content

Repository files navigation

Uwe Reichel, audEERING GmbH, Gilching, Germany

  • machine learning data splitting tool that allows for:
    • group-disjunct splits (e.g. different speakers in train, dev, and test partition)
    • stratification on multiple target and grouping variables (e.g. emotion, gender, language)

From PyPI

  • set up a virtual environment venv_splitutils, activate it, and install splitutils. For Linux this works e.g. as follows:
$ virtualenv --python="/usr/bin/python3" venv_splitutils
$ source venv_splitutils/bin/activate
(venv_splitutils) $ pip install splitutils

From GitHub

$ git clone git@github.com:reichelu/spliutils.git
$ cd splitutils/
$ virtualenv --python="/usr/bin/python3" venv_splitutils
$ source venv_splitutils/bin/activate
$ (venv_splitutils) $ pip install -r requirements.txt
defoptimize_traintest_split(X, y, split_on, stratify_on, weight=None,
test_size=.1, k=30, seed=42):
''' optimize group-disjunct split into training and test set which is guided by: - disjunct split of values in SPLIT_ON - stratification by all keys in STRATIFY_ON (targets and groupings) - test set proportion in X should be close to test_size (which is the test proportion in set(split_on)) Parameters: X: (np.array or pd.DataFrame) of features y: (np.array) of targets of length N if type(y[0]) in ["str", "int"]: y is assumed to be categorical, so that it is additionally tested that all partitions cover all classes. Else y is assumed to be numeric and no coverage test is done. split_on: (np.array) list of length N with grouping variable (e.g. speaker IDs), on which the group-disjunct split is to be performed. Must be categorical. stratify_on: (dict) Dict-keys are variable names (targets and/or further groupings) the split should be stratified on (groupings could e.g. be sex, age class, etc). Dict-Values are np.array-s of length N that contain the variable values. All variables must be categorical. weight: (dict) weight for each variable in stratify_on. Defines their amount of contribution to the optimization score. Uniform weighting by default. Additional key: "size_diff" defines how test size diff should be weighted. test_size: (float) test proportion in set(split_on), e.g. 10% of speakers to be held-out k: (int) number of different splits to be tried out seed: (int) random seed Returns: train_i: (np.array) train set indices in X test_i: (np.array) test set indices in X info: (dict) detail information about reference and achieved prob distributions "size_testset_in_spliton": intended test_size "size_testset_in_X": optimized test proportion in X "p_ref_{c}": reference class distribution calculated from stratify_on[c] "p_test_{c}": test set class distribution calculated from stratify_on[c][test_i] '''
defoptimize_traindevtest_split(X, y, split_on, stratify_on, weight=None,
dev_size=.1, test_size=.1, testset_not_smaller=False,
k=30, seed=42):
''' optimize group-disjunct split into training, dev, and test set, which is guided by: - disjunct split of values in SPLIT_ON - stratification by all keys in STRATIFY_ON (targets and groupings) - test set proportion in X should be close to test_size (which is the test proportion in set(split_on)) Parameters: X: (np.array or pd.DataFrame) of features y: (np.array) of targets of length N if type(y[0]) in ["str", "int"]: y is assumed to be categorical, so that it is additionally tested that all partitions cover all classes. Else y is assumed to be numeric and no coverage test is done. split_on: (np.array) list of length N with grouping variable (e.g. speaker IDs), on which the group-disjunct split is to be performed. Must be categorical. stratify_on: (dict) Dict-keys are variable names (targets and/or further groupings) the split should be stratified on (groupings could e.g. be sex, age class, etc). Dict-Values are np.array-s of length N that contain the variable values. All variables must be categorical. weight: (dict) weight for each variable in stratify_on. Defines their amount of contribution to the optimization score. Uniform weighting by default. Additional key: "size_diff" defines how the corresponding size differences should be weighted. dev_size: (float) proportion in set(split_on) for dev set, e.g. 10% of speakers to be held-out test_size: (float) test proportion in set(split_on) for test set testset_not_smaller (bool) if True, and if test_size >= dev_size, it is ensured, that the resulting test set is not smaller than the dev set k: (int) number of different splits to be tried out seed: (int) random seed Returns: train_i: (np.array) train set indices in X dev_i: (np.array) dev set indices in X test_i: (np.array) test set indices in X info: (dict) detail information about reference and achieved prob distributions "dev_size_in_spliton": intended grouping dev_size "dev_size_in_X": optimized dev proportion of observations in X "test_size_in_spliton": intended grouping test_size "test_size_in_X": optimized test proportion of observations in X "p_ref_{c}": reference class distribution calculated from stratify_on[c] "p_dev_{c}": dev set class distribution calculated from stratify_on[c][dev_i] "p_test_{c}": test set class distribution calculated from stratify_on[c][test_i] '''
defbinning(x, nbins=2, lower_boundaries=None, seed=42):
''' bins numeric data. If X is one-dimensional: binning is done either intrinsically into nbins classes based on an equidistant percentile split, or extrinsically by using the lower_boundaries values. If X is two-dimensional binning is done by kmeans clustering into nbins clusters Parameters: x: (list, np.array) with numeric data. nbins: (int) number of bins lower_boundaries: (list) of lower bin boundaries. If y is 1-dim and lower_boundaries is provided, nbins will be ignored and y is binned extrinsically. The first value of lower_boundaries is always corrected not to be higher than min(y). seed: (int) random seed for kmeans Returns: c: (np.array) integers as bin IDs '''

if you use this software for a publication please cite:

Reichel, U.: splitutils - machine learning data partitioning software, version 0.3.0. doi:10.5281/zenodo.10793086, 2024.

@Misc{splitutils,
author = {Reichel, U.},
title = {splitutils -- machine learning data partitioning software, version 0.3.0},
howpublished = {doi:10.5281/zenodo.10793086},
year = {2024}
}
  • see scripts/run_traintest_split.py
  • partitions are:
    • disjunct on categorical "split_var"
    • stratified on categorical "target", "strat_var1", "strat_var2"
    • each contain all levels of "target"
importnumpyasnpimportosimportsys# add this line if you have cloned the code from github to PROJECT_DIR# sys.path.append(PROJECT_DIR)fromsplitutilsimportoptimize_traindevtest_split# set seedseed=42np.random.seed(seed)
# DUMMY DATA# sizen=100# feature arraydata=np.random.rand(100, 20)
# target variabletarget=np.random.choice(["A", "B"], size=n, replace=True)
# array with variable on which to do a disjunct splitsplit_var=np.random.choice(["D", "E", "F", "G", "H", "I", "J", "K"],
size=n, replace=True)
# dict of variables to stratify on. Key names are arbitrary.stratif_vars= {
"target": target,
"strat_var1": np.random.choice(["L", "M"], size=n, replace=True),
"strat_var2": np.random.choice(["N", "O"], size=n, replace=True)
}
# ARGUMENTS# weight importance of all stratification variables in stratify_in# as well as of "size_diff", which punishes the deviation of intended# and received partition sizes.# Key names must match the names in stratif_vars.weights= {
"target": 2,
"strat_var1": 1,
"strat_var2": 1,
"size_diff": 1
}
# test partition proportion (from 0 to 1)test_size=.2# number of disjunct splits to be tried out in brute force optimizationk=30# FIND OPTIMAL SPLITtrain_i, test_i, info=optimize_traintest_split(
X=data,
y=target,
split_on=split_var,
stratify_on=stratif_vars,
weight=weights,
test_size=test_size,
k=k,
seed=seed
)
# SOME OUTPUTprint("test levels of split_var:", sorted(set(split_var[test_i])))
print("goodness of split:", info)
  • see scripts/run_traindevtest_split.py
  • Partitions are
    • disjunct on categorical "split_var"
    • stratified on categorical "target", "strat_var1", "strat_var2"
    • each contain all levels of "target"
importnumpyasnpimportosimportsys# add this line if you have cloned the code from github to PROJECT_DIR# sys.path.append(PROJECT_DIR)fromsplitutilsimportoptimize_traindevtest_split# set seedseed=42np.random.seed(seed)
# DUMMY DATA# sizen=100# feature arraydata=np.random.rand(100, 20)
# target variabletarget=np.random.choice(["A", "B"], size=n, replace=True)
# array with variable on which to do a disjunct splitsplit_var=np.random.choice(["D", "E", "F", "G", "H", "I", "J", "K"],
size=n, replace=True)
# dict of variables to stratify on. Key names are arbitrary.stratif_vars= {
"target": target,
"strat_var1": np.random.choice(["F", "G"], size=n, replace=True),
"strat_var2": np.random.choice(["H", "I"], size=n, replace=True)
}
# ARGUMENTS# weight importance of all stratification variables in stratify_in# as well as of "size_diff", which punishes the deviation of intended# and received partition sizes.# Key names must match the names in stratif_vars.weights= {
"target": 2,
"strat_var1": 1,
"strat_var2": 1,
"size_diff": 1
}
# dev and test partition proportion (from 0 to 1)dev_size=.1test_size=.1# number of disjunct splits to be tried out in brute force optimizationk=30# FIND OPTIMAL SPLITtrain_i, dev_i, test_i, info=optimize_traindevtest_split(
X=data,
y=target,
split_on=split_var,
stratify_on=stratif_vars,
weight=weights,
dev_size=dev_size,
test_size=test_size,
k=k,
seed=seed
)
# SOME OUTPUTprint("test levels of split_var:", sorted(set(split_var[test_i])))
print("goodness of split:", info)
  • see scripts/run_traindevtest_split_with_binning.py
  • Partitions are
    • disjunct on categorical "split_var"
    • stratified on numeric "target", and on 3 other numeric stratification variables
importnumpyasnpimportosimportsys# add this line if you have cloned the code from github to PROJECT_DIR# sys.path.append(PROJECT_DIR)fromsplitutilsimport (
binning,
optimize_traindevtest_split
)
"""example script how to split dummy data into training, development,and test partitions that are* disjunct on categorical "split_var"* stratified on numeric "target", and on 3 other numeric stratification variables"""# set seedseed=42np.random.seed(seed)
# DUMMY DATA# sizen=100# featuresdata=np.random.rand(n, 20)
# numeric target variablenum_target=np.random.rand(n)
# array with variable on which to do a disjunct splitsplit_var=np.random.choice(["D", "E", "F", "G", "H", "I", "J", "K"],
size=n, replace=True)
# further numeric variables to stratify onnum_strat_vars=np.random.rand(n, 3)
# intrinsically bin target into 3 bins by equidistant# percentile boundariesbinned_target=binning(num_target, nbins=3)
# ... alternatively, a variable can be extrinsically binned by# specifying lower boundaries:# binned_target = binning(num_target, lower_boundaries=[0, 0.33, 0.66])# bin other stratification variables into a single variable with 6 bins# (2-dim input is binned by StandardScaling and KMeans clustering)binned_strat_var=binning(num_strat_vars, nbins=6)
# ... alternatively, each stratification variable could be binned# individually - intrinsically or extrinsically the same way as num_target# strat_var1 = binning(num_strat_vars[:,0], nbins=...) etc.# now add the obtained categorical variable to stratification dictstratif_vars= {
"target": binned_target,
"strat_var": binned_strat_var
}
# ARGUMENTS# weight importance of all stratification variables in stratify_in# as well as of "size_diff", which punishes the deviation of intended# and received partition sizesweights= {
"target": 2,
"strat_var": 1,
"size_diff": 1
}
# dev and test partition proportion (from 0 to 1)dev_size=.1test_size=.1# number of disjunct splits to be tried out in brute force optimizationk=30# FIND OPTIMAL SPLITtrain_i, dev_i, test_i, info=optimize_traindevtest_split(
X=data,
y=num_target,
split_on=split_var,
stratify_on=stratif_vars,
weight=weights,
dev_size=dev_size,
test_size=test_size,
k=k,
seed=seed
)
# SOME OUTPUTprint("test levels of split_var:", sorted(set(split_var[test_i])))
print("goodness of split:", info)
  • find optimal train, dev, and test set split based on:
    • disjunct split of a categorical grouping variable G (e.g. speaker)
    • optimized joint stratification on an arbitrary amount of categorical target and grouping variables (e.g. emotion, gender, ...)
    • close match of partition proportions in G and underlying dataset X
  • brute-force optimization on k disjunct splits of G
  • score to be minimzed for train/test set split:
(sum_v[w(v) * irad(v)] + w(d) * d) / (sum_v[w(v)] + w(d))
v: variables to be stratified on
w(v): their weight
irad(v): information radius between reference and test set distribution of factor levels in v
d: absolute difference between test proportions of X and G, i.e. between the proportion of test
samples and the proportion of groups (e.g. speakers) that go into the test set
w(d): its weight
  • score to be minimzed for train / dev / test set split:
(sum_v[w(v) * max_irad(v)] + w(d) * max_d) / (sum_v[w(v)] + w(d))
v: variables to be stratified on
w(v): their weight
max_irad(v): maximum information radius of reference distribution of classes in v and
- dev set distribution,
- test set distribution
max_d: maximum of absolute difference between proportions of X and G (see above) calculated for
the dev and test set
w(d): its weight
  • let's look at Example 2 above. There info becomes:
{
'score': 0.030828359568603338,
'size_devset_in_spliton': 0.1,
'size_devset_in_X': 0.14,
'size_testset_in_spliton': 0.1,
'size_testset_in_X': 0.13,
'p_target_ref': {'B': 0.49, 'A': 0.51},
'p_target_dev': {'A': 0.5, 'B': 0.5},
'p_target_test': {'A': 0.5384615384615384, 'B': 0.46153846153846156},
'p_strat_var1_ref': {'G': 0.56, 'F': 0.44},
'p_strat_var1_dev': {'G': 0.5714285714285714, 'F': 0.42857142857142855},
'p_strat_var1_test': {'F': 0.5384615384615384, 'G': 0.46153846153846156},
'p_strat_var2_ref': {'I': 0.48, 'H': 0.52},
'p_strat_var2_dev': {'I': 0.5, 'H': 0.5},
'p_strat_var2_test': {'I': 0.46153846153846156, 'H': 0.5384615384615384}
}
  • Explanations
    • score: see above, score to be minimzed for train / dev / test set split:
    • size_devset_in_spliton: proportion of to-be-split-on variable levels in development set
    • size_devset_in_X: proportion of rows in X in development set
    • size_testset_in_spliton: proportion of to-be-split-on variable levels in test set
    • size_testset_in_X: proportion of rows in X in test set
    • p_target_ref: reference target class distribution over all data
    • p_target_dev: target class distribution in development set
    • p_target_test: target class distribution in test set
    • p_strat_var1_ref: first stratification variable's reference distribution over all data
    • p_strat_var1_dev: first stratification variable's class distribution in development set
    • p_strat_var1_test: first stratification variable's class distribution in test set
    • p_strat_var2_ref: second stratification variable's reference distribution over all data
    • p_strat_var2_dev: second stratification variable's class distribution in development set
    • p_strat_var2_test: second stratification variable's class distribution in test set
  • Remarks
    • for splitutils.optimize_traintest_split() no development set results are reported
    • all *_strat_var* keys: key names derived from key names in stratify_on argument

About

machine learning data partitioning tool that allows for group-disjunct splits and stratification on multiple target and grouping variables

Resources

Stars

1 star

Watchers

1 watching

Forks

Releases

Packages

Used by

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Force GitHub README to respect dark mode\n(function() {\n var style = document.createElement('style');\n style.textContent = '\n .markdown-body {\n color-scheme: dark light;\n }\n .markdown-body pre { background: #161b22 !important; }\n .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; }\n .markdown-body table th, .markdown-body table td { border-color: #30363d !important; }\n .markdown-body img { background: #0d1117; }\n .markdown-body blockquote { border-left-color: #8b949e; }\n .markdown-body hr { border-color: #30363d; }\n ';\n document.head.appendChild(style);\n})();", "GitHub Dark Mode README Fix"); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Repository files navigation

Uwe Reichel, audEERING GmbH, Gilching, Germany

  • machine learning data splitting tool that allows for:
    • group-disjunct splits (e.g. different speakers in train, dev, and test partition)
    • stratification on multiple target and grouping variables (e.g. emotion, gender, language)

From PyPI

  • set up a virtual environment venv_splitutils, activate it, and install splitutils. For Linux this works e.g. as follows:
$ virtualenv --python="/usr/bin/python3" venv_splitutils
$ source venv_splitutils/bin/activate
(venv_splitutils) $ pip install splitutils

From GitHub

$ git clone git@github.com:reichelu/spliutils.git
$ cd splitutils/
$ virtualenv --python="/usr/bin/python3" venv_splitutils
$ source venv_splitutils/bin/activate
$ (venv_splitutils) $ pip install -r requirements.txt
defoptimize_traintest_split(X, y, split_on, stratify_on, weight=None,
test_size=.1, k=30, seed=42):
''' optimize group-disjunct split into training and test set which is guided by: - disjunct split of values in SPLIT_ON - stratification by all keys in STRATIFY_ON (targets and groupings) - test set proportion in X should be close to test_size (which is the test proportion in set(split_on)) Parameters: X: (np.array or pd.DataFrame) of features y: (np.array) of targets of length N if type(y[0]) in ["str", "int"]: y is assumed to be categorical, so that it is additionally tested that all partitions cover all classes. Else y is assumed to be numeric and no coverage test is done. split_on: (np.array) list of length N with grouping variable (e.g. speaker IDs), on which the group-disjunct split is to be performed. Must be categorical. stratify_on: (dict) Dict-keys are variable names (targets and/or further groupings) the split should be stratified on (groupings could e.g. be sex, age class, etc). Dict-Values are np.array-s of length N that contain the variable values. All variables must be categorical. weight: (dict) weight for each variable in stratify_on. Defines their amount of contribution to the optimization score. Uniform weighting by default. Additional key: "size_diff" defines how test size diff should be weighted. test_size: (float) test proportion in set(split_on), e.g. 10% of speakers to be held-out k: (int) number of different splits to be tried out seed: (int) random seed Returns: train_i: (np.array) train set indices in X test_i: (np.array) test set indices in X info: (dict) detail information about reference and achieved prob distributions "size_testset_in_spliton": intended test_size "size_testset_in_X": optimized test proportion in X "p_ref_{c}": reference class distribution calculated from stratify_on[c] "p_test_{c}": test set class distribution calculated from stratify_on[c][test_i] '''
defoptimize_traindevtest_split(X, y, split_on, stratify_on, weight=None,
dev_size=.1, test_size=.1, testset_not_smaller=False,
k=30, seed=42):
''' optimize group-disjunct split into training, dev, and test set, which is guided by: - disjunct split of values in SPLIT_ON - stratification by all keys in STRATIFY_ON (targets and groupings) - test set proportion in X should be close to test_size (which is the test proportion in set(split_on)) Parameters: X: (np.array or pd.DataFrame) of features y: (np.array) of targets of length N if type(y[0]) in ["str", "int"]: y is assumed to be categorical, so that it is additionally tested that all partitions cover all classes. Else y is assumed to be numeric and no coverage test is done. split_on: (np.array) list of length N with grouping variable (e.g. speaker IDs), on which the group-disjunct split is to be performed. Must be categorical. stratify_on: (dict) Dict-keys are variable names (targets and/or further groupings) the split should be stratified on (groupings could e.g. be sex, age class, etc). Dict-Values are np.array-s of length N that contain the variable values. All variables must be categorical. weight: (dict) weight for each variable in stratify_on. Defines their amount of contribution to the optimization score. Uniform weighting by default. Additional key: "size_diff" defines how the corresponding size differences should be weighted. dev_size: (float) proportion in set(split_on) for dev set, e.g. 10% of speakers to be held-out test_size: (float) test proportion in set(split_on) for test set testset_not_smaller (bool) if True, and if test_size >= dev_size, it is ensured, that the resulting test set is not smaller than the dev set k: (int) number of different splits to be tried out seed: (int) random seed Returns: train_i: (np.array) train set indices in X dev_i: (np.array) dev set indices in X test_i: (np.array) test set indices in X info: (dict) detail information about reference and achieved prob distributions "dev_size_in_spliton": intended grouping dev_size "dev_size_in_X": optimized dev proportion of observations in X "test_size_in_spliton": intended grouping test_size "test_size_in_X": optimized test proportion of observations in X "p_ref_{c}": reference class distribution calculated from stratify_on[c] "p_dev_{c}": dev set class distribution calculated from stratify_on[c][dev_i] "p_test_{c}": test set class distribution calculated from stratify_on[c][test_i] '''
defbinning(x, nbins=2, lower_boundaries=None, seed=42):
''' bins numeric data. If X is one-dimensional: binning is done either intrinsically into nbins classes based on an equidistant percentile split, or extrinsically by using the lower_boundaries values. If X is two-dimensional binning is done by kmeans clustering into nbins clusters Parameters: x: (list, np.array) with numeric data. nbins: (int) number of bins lower_boundaries: (list) of lower bin boundaries. If y is 1-dim and lower_boundaries is provided, nbins will be ignored and y is binned extrinsically. The first value of lower_boundaries is always corrected not to be higher than min(y). seed: (int) random seed for kmeans Returns: c: (np.array) integers as bin IDs '''

if you use this software for a publication please cite:

Reichel, U.: splitutils - machine learning data partitioning software, version 0.3.0. doi:10.5281/zenodo.10793086, 2024.

@Misc{splitutils,
author = {Reichel, U.},
title = {splitutils -- machine learning data partitioning software, version 0.3.0},
howpublished = {doi:10.5281/zenodo.10793086},
year = {2024}
}
  • see scripts/run_traintest_split.py
  • partitions are:
    • disjunct on categorical "split_var"
    • stratified on categorical "target", "strat_var1", "strat_var2"
    • each contain all levels of "target"
importnumpyasnpimportosimportsys# add this line if you have cloned the code from github to PROJECT_DIR# sys.path.append(PROJECT_DIR)fromsplitutilsimportoptimize_traindevtest_split# set seedseed=42np.random.seed(seed)
# DUMMY DATA# sizen=100# feature arraydata=np.random.rand(100, 20)
# target variabletarget=np.random.choice(["A", "B"], size=n, replace=True)
# array with variable on which to do a disjunct splitsplit_var=np.random.choice(["D", "E", "F", "G", "H", "I", "J", "K"],
size=n, replace=True)
# dict of variables to stratify on. Key names are arbitrary.stratif_vars= {
"target": target,
"strat_var1": np.random.choice(["L", "M"], size=n, replace=True),
"strat_var2": np.random.choice(["N", "O"], size=n, replace=True)
}
# ARGUMENTS# weight importance of all stratification variables in stratify_in# as well as of "size_diff", which punishes the deviation of intended# and received partition sizes.# Key names must match the names in stratif_vars.weights= {
"target": 2,
"strat_var1": 1,
"strat_var2": 1,
"size_diff": 1
}
# test partition proportion (from 0 to 1)test_size=.2# number of disjunct splits to be tried out in brute force optimizationk=30# FIND OPTIMAL SPLITtrain_i, test_i, info=optimize_traintest_split(
X=data,
y=target,
split_on=split_var,
stratify_on=stratif_vars,
weight=weights,
test_size=test_size,
k=k,
seed=seed
)
# SOME OUTPUTprint("test levels of split_var:", sorted(set(split_var[test_i])))
print("goodness of split:", info)
  • see scripts/run_traindevtest_split.py
  • Partitions are
    • disjunct on categorical "split_var"
    • stratified on categorical "target", "strat_var1", "strat_var2"
    • each contain all levels of "target"
importnumpyasnpimportosimportsys# add this line if you have cloned the code from github to PROJECT_DIR# sys.path.append(PROJECT_DIR)fromsplitutilsimportoptimize_traindevtest_split# set seedseed=42np.random.seed(seed)
# DUMMY DATA# sizen=100# feature arraydata=np.random.rand(100, 20)
# target variabletarget=np.random.choice(["A", "B"], size=n, replace=True)
# array with variable on which to do a disjunct splitsplit_var=np.random.choice(["D", "E", "F", "G", "H", "I", "J", "K"],
size=n, replace=True)
# dict of variables to stratify on. Key names are arbitrary.stratif_vars= {
"target": target,
"strat_var1": np.random.choice(["F", "G"], size=n, replace=True),
"strat_var2": np.random.choice(["H", "I"], size=n, replace=True)
}
# ARGUMENTS# weight importance of all stratification variables in stratify_in# as well as of "size_diff", which punishes the deviation of intended# and received partition sizes.# Key names must match the names in stratif_vars.weights= {
"target": 2,
"strat_var1": 1,
"strat_var2": 1,
"size_diff": 1
}
# dev and test partition proportion (from 0 to 1)dev_size=.1test_size=.1# number of disjunct splits to be tried out in brute force optimizationk=30# FIND OPTIMAL SPLITtrain_i, dev_i, test_i, info=optimize_traindevtest_split(
X=data,
y=target,
split_on=split_var,
stratify_on=stratif_vars,
weight=weights,
dev_size=dev_size,
test_size=test_size,
k=k,
seed=seed
)
# SOME OUTPUTprint("test levels of split_var:", sorted(set(split_var[test_i])))
print("goodness of split:", info)
  • see scripts/run_traindevtest_split_with_binning.py
  • Partitions are
    • disjunct on categorical "split_var"
    • stratified on numeric "target", and on 3 other numeric stratification variables
importnumpyasnpimportosimportsys# add this line if you have cloned the code from github to PROJECT_DIR# sys.path.append(PROJECT_DIR)fromsplitutilsimport (
binning,
optimize_traindevtest_split
)
"""example script how to split dummy data into training, development,and test partitions that are* disjunct on categorical "split_var"* stratified on numeric "target", and on 3 other numeric stratification variables"""# set seedseed=42np.random.seed(seed)
# DUMMY DATA# sizen=100# featuresdata=np.random.rand(n, 20)
# numeric target variablenum_target=np.random.rand(n)
# array with variable on which to do a disjunct splitsplit_var=np.random.choice(["D", "E", "F", "G", "H", "I", "J", "K"],
size=n, replace=True)
# further numeric variables to stratify onnum_strat_vars=np.random.rand(n, 3)
# intrinsically bin target into 3 bins by equidistant# percentile boundariesbinned_target=binning(num_target, nbins=3)
# ... alternatively, a variable can be extrinsically binned by# specifying lower boundaries:# binned_target = binning(num_target, lower_boundaries=[0, 0.33, 0.66])# bin other stratification variables into a single variable with 6 bins# (2-dim input is binned by StandardScaling and KMeans clustering)binned_strat_var=binning(num_strat_vars, nbins=6)
# ... alternatively, each stratification variable could be binned# individually - intrinsically or extrinsically the same way as num_target# strat_var1 = binning(num_strat_vars[:,0], nbins=...) etc.# now add the obtained categorical variable to stratification dictstratif_vars= {
"target": binned_target,
"strat_var": binned_strat_var
}
# ARGUMENTS# weight importance of all stratification variables in stratify_in# as well as of "size_diff", which punishes the deviation of intended# and received partition sizesweights= {
"target": 2,
"strat_var": 1,
"size_diff": 1
}
# dev and test partition proportion (from 0 to 1)dev_size=.1test_size=.1# number of disjunct splits to be tried out in brute force optimizationk=30# FIND OPTIMAL SPLITtrain_i, dev_i, test_i, info=optimize_traindevtest_split(
X=data,
y=num_target,
split_on=split_var,
stratify_on=stratif_vars,
weight=weights,
dev_size=dev_size,
test_size=test_size,
k=k,
seed=seed
)
# SOME OUTPUTprint("test levels of split_var:", sorted(set(split_var[test_i])))
print("goodness of split:", info)
  • find optimal train, dev, and test set split based on:
    • disjunct split of a categorical grouping variable G (e.g. speaker)
    • optimized joint stratification on an arbitrary amount of categorical target and grouping variables (e.g. emotion, gender, ...)
    • close match of partition proportions in G and underlying dataset X
  • brute-force optimization on k disjunct splits of G
  • score to be minimzed for train/test set split:
(sum_v[w(v) * irad(v)] + w(d) * d) / (sum_v[w(v)] + w(d))
v: variables to be stratified on
w(v): their weight
irad(v): information radius between reference and test set distribution of factor levels in v
d: absolute difference between test proportions of X and G, i.e. between the proportion of test
samples and the proportion of groups (e.g. speakers) that go into the test set
w(d): its weight
  • score to be minimzed for train / dev / test set split:
(sum_v[w(v) * max_irad(v)] + w(d) * max_d) / (sum_v[w(v)] + w(d))
v: variables to be stratified on
w(v): their weight
max_irad(v): maximum information radius of reference distribution of classes in v and
- dev set distribution,
- test set distribution
max_d: maximum of absolute difference between proportions of X and G (see above) calculated for
the dev and test set
w(d): its weight
  • let's look at Example 2 above. There info becomes:
{
'score': 0.030828359568603338,
'size_devset_in_spliton': 0.1,
'size_devset_in_X': 0.14,
'size_testset_in_spliton': 0.1,
'size_testset_in_X': 0.13,
'p_target_ref': {'B': 0.49, 'A': 0.51},
'p_target_dev': {'A': 0.5, 'B': 0.5},
'p_target_test': {'A': 0.5384615384615384, 'B': 0.46153846153846156},
'p_strat_var1_ref': {'G': 0.56, 'F': 0.44},
'p_strat_var1_dev': {'G': 0.5714285714285714, 'F': 0.42857142857142855},
'p_strat_var1_test': {'F': 0.5384615384615384, 'G': 0.46153846153846156},
'p_strat_var2_ref': {'I': 0.48, 'H': 0.52},
'p_strat_var2_dev': {'I': 0.5, 'H': 0.5},
'p_strat_var2_test': {'I': 0.46153846153846156, 'H': 0.5384615384615384}
}
  • Explanations
    • score: see above, score to be minimzed for train / dev / test set split:
    • size_devset_in_spliton: proportion of to-be-split-on variable levels in development set
    • size_devset_in_X: proportion of rows in X in development set
    • size_testset_in_spliton: proportion of to-be-split-on variable levels in test set
    • size_testset_in_X: proportion of rows in X in test set
    • p_target_ref: reference target class distribution over all data
    • p_target_dev: target class distribution in development set
    • p_target_test: target class distribution in test set
    • p_strat_var1_ref: first stratification variable's reference distribution over all data
    • p_strat_var1_dev: first stratification variable's class distribution in development set
    • p_strat_var1_test: first stratification variable's class distribution in test set
    • p_strat_var2_ref: second stratification variable's reference distribution over all data
    • p_strat_var2_dev: second stratification variable's class distribution in development set
    • p_strat_var2_test: second stratification variable's class distribution in test set
  • Remarks
    • for splitutils.optimize_traintest_split() no development set results are reported
    • all *_strat_var* keys: key names derived from key names in stratify_on argument

About

machine learning data partitioning tool that allows for group-disjunct splits and stratification on multiple target and grouping variables

Resources

Stars

1 star

Watchers

1 watching

Forks

Releases

Packages

Used by

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Highlight search terms from Google/DuckDuckGo/Bing referrer\n(function() {\n var ref = document.referrer;\n var terms = [];\n \n if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) {\n var url = new URL(ref);\n var q = url.searchParams.get('q') || url.searchParams.get('p');\n if (q) {\n terms = q.split(/\\s+/).filter(function(t) { return t.length > 2; });\n }\n }\n \n if (terms.length === 0) return;\n \n var style = document.createElement('style');\n style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }';\n document.head.appendChild(style);\n \n function highlight(node) {\n if (node.nodeType === 3) { // text node\n var text = node.textContent;\n var found = false;\n terms.forEach(function(term) {\n var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\') + ')', 'gi');\n if (regex.test(text)) {\n found = true;\n var frag = document.createDocumentFragment();\n var parts = text.split(regex);\n parts.forEach(function(part, i) {\n if (i % 2 === 0) {\n frag.appendChild(document.createTextNode(part));\n } else {\n var span = document.createElement('span');\n span.className = 'userscript-highlight';\n span.textContent = part;\n frag.appendChild(span);\n }\n });\n node.parentNode.replaceChild(frag, node);\n }\n });\n } else if (node.nodeType === 1 && node.childNodes) { // element\n var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT'];\n if (!skipTags.includes(node.tagName)) {\n Array.from(node.childNodes).forEach(highlight);\n }\n }\n }\n \n highlight(document.body);\n \n // Re-highlight on dynamic content\n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1 || node.nodeType === 3) highlight(node);\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Highlight Search Terms"); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Repository files navigation

Uwe Reichel, audEERING GmbH, Gilching, Germany

  • machine learning data splitting tool that allows for:
    • group-disjunct splits (e.g. different speakers in train, dev, and test partition)
    • stratification on multiple target and grouping variables (e.g. emotion, gender, language)

From PyPI

  • set up a virtual environment venv_splitutils, activate it, and install splitutils. For Linux this works e.g. as follows:
$ virtualenv --python="/usr/bin/python3" venv_splitutils
$ source venv_splitutils/bin/activate
(venv_splitutils) $ pip install splitutils

From GitHub

$ git clone git@github.com:reichelu/spliutils.git
$ cd splitutils/
$ virtualenv --python="/usr/bin/python3" venv_splitutils
$ source venv_splitutils/bin/activate
$ (venv_splitutils) $ pip install -r requirements.txt
defoptimize_traintest_split(X, y, split_on, stratify_on, weight=None,
test_size=.1, k=30, seed=42):
''' optimize group-disjunct split into training and test set which is guided by: - disjunct split of values in SPLIT_ON - stratification by all keys in STRATIFY_ON (targets and groupings) - test set proportion in X should be close to test_size (which is the test proportion in set(split_on)) Parameters: X: (np.array or pd.DataFrame) of features y: (np.array) of targets of length N if type(y[0]) in ["str", "int"]: y is assumed to be categorical, so that it is additionally tested that all partitions cover all classes. Else y is assumed to be numeric and no coverage test is done. split_on: (np.array) list of length N with grouping variable (e.g. speaker IDs), on which the group-disjunct split is to be performed. Must be categorical. stratify_on: (dict) Dict-keys are variable names (targets and/or further groupings) the split should be stratified on (groupings could e.g. be sex, age class, etc). Dict-Values are np.array-s of length N that contain the variable values. All variables must be categorical. weight: (dict) weight for each variable in stratify_on. Defines their amount of contribution to the optimization score. Uniform weighting by default. Additional key: "size_diff" defines how test size diff should be weighted. test_size: (float) test proportion in set(split_on), e.g. 10% of speakers to be held-out k: (int) number of different splits to be tried out seed: (int) random seed Returns: train_i: (np.array) train set indices in X test_i: (np.array) test set indices in X info: (dict) detail information about reference and achieved prob distributions "size_testset_in_spliton": intended test_size "size_testset_in_X": optimized test proportion in X "p_ref_{c}": reference class distribution calculated from stratify_on[c] "p_test_{c}": test set class distribution calculated from stratify_on[c][test_i] '''
defoptimize_traindevtest_split(X, y, split_on, stratify_on, weight=None,
dev_size=.1, test_size=.1, testset_not_smaller=False,
k=30, seed=42):
''' optimize group-disjunct split into training, dev, and test set, which is guided by: - disjunct split of values in SPLIT_ON - stratification by all keys in STRATIFY_ON (targets and groupings) - test set proportion in X should be close to test_size (which is the test proportion in set(split_on)) Parameters: X: (np.array or pd.DataFrame) of features y: (np.array) of targets of length N if type(y[0]) in ["str", "int"]: y is assumed to be categorical, so that it is additionally tested that all partitions cover all classes. Else y is assumed to be numeric and no coverage test is done. split_on: (np.array) list of length N with grouping variable (e.g. speaker IDs), on which the group-disjunct split is to be performed. Must be categorical. stratify_on: (dict) Dict-keys are variable names (targets and/or further groupings) the split should be stratified on (groupings could e.g. be sex, age class, etc). Dict-Values are np.array-s of length N that contain the variable values. All variables must be categorical. weight: (dict) weight for each variable in stratify_on. Defines their amount of contribution to the optimization score. Uniform weighting by default. Additional key: "size_diff" defines how the corresponding size differences should be weighted. dev_size: (float) proportion in set(split_on) for dev set, e.g. 10% of speakers to be held-out test_size: (float) test proportion in set(split_on) for test set testset_not_smaller (bool) if True, and if test_size >= dev_size, it is ensured, that the resulting test set is not smaller than the dev set k: (int) number of different splits to be tried out seed: (int) random seed Returns: train_i: (np.array) train set indices in X dev_i: (np.array) dev set indices in X test_i: (np.array) test set indices in X info: (dict) detail information about reference and achieved prob distributions "dev_size_in_spliton": intended grouping dev_size "dev_size_in_X": optimized dev proportion of observations in X "test_size_in_spliton": intended grouping test_size "test_size_in_X": optimized test proportion of observations in X "p_ref_{c}": reference class distribution calculated from stratify_on[c] "p_dev_{c}": dev set class distribution calculated from stratify_on[c][dev_i] "p_test_{c}": test set class distribution calculated from stratify_on[c][test_i] '''
defbinning(x, nbins=2, lower_boundaries=None, seed=42):
''' bins numeric data. If X is one-dimensional: binning is done either intrinsically into nbins classes based on an equidistant percentile split, or extrinsically by using the lower_boundaries values. If X is two-dimensional binning is done by kmeans clustering into nbins clusters Parameters: x: (list, np.array) with numeric data. nbins: (int) number of bins lower_boundaries: (list) of lower bin boundaries. If y is 1-dim and lower_boundaries is provided, nbins will be ignored and y is binned extrinsically. The first value of lower_boundaries is always corrected not to be higher than min(y). seed: (int) random seed for kmeans Returns: c: (np.array) integers as bin IDs '''

if you use this software for a publication please cite:

Reichel, U.: splitutils - machine learning data partitioning software, version 0.3.0. doi:10.5281/zenodo.10793086, 2024.

@Misc{splitutils,
author = {Reichel, U.},
title = {splitutils -- machine learning data partitioning software, version 0.3.0},
howpublished = {doi:10.5281/zenodo.10793086},
year = {2024}
}
  • see scripts/run_traintest_split.py
  • partitions are:
    • disjunct on categorical "split_var"
    • stratified on categorical "target", "strat_var1", "strat_var2"
    • each contain all levels of "target"
importnumpyasnpimportosimportsys# add this line if you have cloned the code from github to PROJECT_DIR# sys.path.append(PROJECT_DIR)fromsplitutilsimportoptimize_traindevtest_split# set seedseed=42np.random.seed(seed)
# DUMMY DATA# sizen=100# feature arraydata=np.random.rand(100, 20)
# target variabletarget=np.random.choice(["A", "B"], size=n, replace=True)
# array with variable on which to do a disjunct splitsplit_var=np.random.choice(["D", "E", "F", "G", "H", "I", "J", "K"],
size=n, replace=True)
# dict of variables to stratify on. Key names are arbitrary.stratif_vars= {
"target": target,
"strat_var1": np.random.choice(["L", "M"], size=n, replace=True),
"strat_var2": np.random.choice(["N", "O"], size=n, replace=True)
}
# ARGUMENTS# weight importance of all stratification variables in stratify_in# as well as of "size_diff", which punishes the deviation of intended# and received partition sizes.# Key names must match the names in stratif_vars.weights= {
"target": 2,
"strat_var1": 1,
"strat_var2": 1,
"size_diff": 1
}
# test partition proportion (from 0 to 1)test_size=.2# number of disjunct splits to be tried out in brute force optimizationk=30# FIND OPTIMAL SPLITtrain_i, test_i, info=optimize_traintest_split(
X=data,
y=target,
split_on=split_var,
stratify_on=stratif_vars,
weight=weights,
test_size=test_size,
k=k,
seed=seed
)
# SOME OUTPUTprint("test levels of split_var:", sorted(set(split_var[test_i])))
print("goodness of split:", info)
  • see scripts/run_traindevtest_split.py
  • Partitions are
    • disjunct on categorical "split_var"
    • stratified on categorical "target", "strat_var1", "strat_var2"
    • each contain all levels of "target"
importnumpyasnpimportosimportsys# add this line if you have cloned the code from github to PROJECT_DIR# sys.path.append(PROJECT_DIR)fromsplitutilsimportoptimize_traindevtest_split# set seedseed=42np.random.seed(seed)
# DUMMY DATA# sizen=100# feature arraydata=np.random.rand(100, 20)
# target variabletarget=np.random.choice(["A", "B"], size=n, replace=True)
# array with variable on which to do a disjunct splitsplit_var=np.random.choice(["D", "E", "F", "G", "H", "I", "J", "K"],
size=n, replace=True)
# dict of variables to stratify on. Key names are arbitrary.stratif_vars= {
"target": target,
"strat_var1": np.random.choice(["F", "G"], size=n, replace=True),
"strat_var2": np.random.choice(["H", "I"], size=n, replace=True)
}
# ARGUMENTS# weight importance of all stratification variables in stratify_in# as well as of "size_diff", which punishes the deviation of intended# and received partition sizes.# Key names must match the names in stratif_vars.weights= {
"target": 2,
"strat_var1": 1,
"strat_var2": 1,
"size_diff": 1
}
# dev and test partition proportion (from 0 to 1)dev_size=.1test_size=.1# number of disjunct splits to be tried out in brute force optimizationk=30# FIND OPTIMAL SPLITtrain_i, dev_i, test_i, info=optimize_traindevtest_split(
X=data,
y=target,
split_on=split_var,
stratify_on=stratif_vars,
weight=weights,
dev_size=dev_size,
test_size=test_size,
k=k,
seed=seed
)
# SOME OUTPUTprint("test levels of split_var:", sorted(set(split_var[test_i])))
print("goodness of split:", info)
  • see scripts/run_traindevtest_split_with_binning.py
  • Partitions are
    • disjunct on categorical "split_var"
    • stratified on numeric "target", and on 3 other numeric stratification variables
importnumpyasnpimportosimportsys# add this line if you have cloned the code from github to PROJECT_DIR# sys.path.append(PROJECT_DIR)fromsplitutilsimport (
binning,
optimize_traindevtest_split
)
"""example script how to split dummy data into training, development,and test partitions that are* disjunct on categorical "split_var"* stratified on numeric "target", and on 3 other numeric stratification variables"""# set seedseed=42np.random.seed(seed)
# DUMMY DATA# sizen=100# featuresdata=np.random.rand(n, 20)
# numeric target variablenum_target=np.random.rand(n)
# array with variable on which to do a disjunct splitsplit_var=np.random.choice(["D", "E", "F", "G", "H", "I", "J", "K"],
size=n, replace=True)
# further numeric variables to stratify onnum_strat_vars=np.random.rand(n, 3)
# intrinsically bin target into 3 bins by equidistant# percentile boundariesbinned_target=binning(num_target, nbins=3)
# ... alternatively, a variable can be extrinsically binned by# specifying lower boundaries:# binned_target = binning(num_target, lower_boundaries=[0, 0.33, 0.66])# bin other stratification variables into a single variable with 6 bins# (2-dim input is binned by StandardScaling and KMeans clustering)binned_strat_var=binning(num_strat_vars, nbins=6)
# ... alternatively, each stratification variable could be binned# individually - intrinsically or extrinsically the same way as num_target# strat_var1 = binning(num_strat_vars[:,0], nbins=...) etc.# now add the obtained categorical variable to stratification dictstratif_vars= {
"target": binned_target,
"strat_var": binned_strat_var
}
# ARGUMENTS# weight importance of all stratification variables in stratify_in# as well as of "size_diff", which punishes the deviation of intended# and received partition sizesweights= {
"target": 2,
"strat_var": 1,
"size_diff": 1
}
# dev and test partition proportion (from 0 to 1)dev_size=.1test_size=.1# number of disjunct splits to be tried out in brute force optimizationk=30# FIND OPTIMAL SPLITtrain_i, dev_i, test_i, info=optimize_traindevtest_split(
X=data,
y=num_target,
split_on=split_var,
stratify_on=stratif_vars,
weight=weights,
dev_size=dev_size,
test_size=test_size,
k=k,
seed=seed
)
# SOME OUTPUTprint("test levels of split_var:", sorted(set(split_var[test_i])))
print("goodness of split:", info)
  • find optimal train, dev, and test set split based on:
    • disjunct split of a categorical grouping variable G (e.g. speaker)
    • optimized joint stratification on an arbitrary amount of categorical target and grouping variables (e.g. emotion, gender, ...)
    • close match of partition proportions in G and underlying dataset X
  • brute-force optimization on k disjunct splits of G
  • score to be minimzed for train/test set split:
(sum_v[w(v) * irad(v)] + w(d) * d) / (sum_v[w(v)] + w(d))
v: variables to be stratified on
w(v): their weight
irad(v): information radius between reference and test set distribution of factor levels in v
d: absolute difference between test proportions of X and G, i.e. between the proportion of test
samples and the proportion of groups (e.g. speakers) that go into the test set
w(d): its weight
  • score to be minimzed for train / dev / test set split:
(sum_v[w(v) * max_irad(v)] + w(d) * max_d) / (sum_v[w(v)] + w(d))
v: variables to be stratified on
w(v): their weight
max_irad(v): maximum information radius of reference distribution of classes in v and
- dev set distribution,
- test set distribution
max_d: maximum of absolute difference between proportions of X and G (see above) calculated for
the dev and test set
w(d): its weight
  • let's look at Example 2 above. There info becomes:
{
'score': 0.030828359568603338,
'size_devset_in_spliton': 0.1,
'size_devset_in_X': 0.14,
'size_testset_in_spliton': 0.1,
'size_testset_in_X': 0.13,
'p_target_ref': {'B': 0.49, 'A': 0.51},
'p_target_dev': {'A': 0.5, 'B': 0.5},
'p_target_test': {'A': 0.5384615384615384, 'B': 0.46153846153846156},
'p_strat_var1_ref': {'G': 0.56, 'F': 0.44},
'p_strat_var1_dev': {'G': 0.5714285714285714, 'F': 0.42857142857142855},
'p_strat_var1_test': {'F': 0.5384615384615384, 'G': 0.46153846153846156},
'p_strat_var2_ref': {'I': 0.48, 'H': 0.52},
'p_strat_var2_dev': {'I': 0.5, 'H': 0.5},
'p_strat_var2_test': {'I': 0.46153846153846156, 'H': 0.5384615384615384}
}
  • Explanations
    • score: see above, score to be minimzed for train / dev / test set split:
    • size_devset_in_spliton: proportion of to-be-split-on variable levels in development set
    • size_devset_in_X: proportion of rows in X in development set
    • size_testset_in_spliton: proportion of to-be-split-on variable levels in test set
    • size_testset_in_X: proportion of rows in X in test set
    • p_target_ref: reference target class distribution over all data
    • p_target_dev: target class distribution in development set
    • p_target_test: target class distribution in test set
    • p_strat_var1_ref: first stratification variable's reference distribution over all data
    • p_strat_var1_dev: first stratification variable's class distribution in development set
    • p_strat_var1_test: first stratification variable's class distribution in test set
    • p_strat_var2_ref: second stratification variable's reference distribution over all data
    • p_strat_var2_dev: second stratification variable's class distribution in development set
    • p_strat_var2_test: second stratification variable's class distribution in test set
  • Remarks
    • for splitutils.optimize_traintest_split() no development set results are reported
    • all *_strat_var* keys: key names derived from key names in stratify_on argument

About

machine learning data partitioning tool that allows for group-disjunct splits and stratification on multiple target and grouping variables

Resources

Stars

1 star

Watchers

1 watching

Forks

Releases

Packages

Used by

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Strip utm_, fbclid, gclid, etc. from all links on page\n(function() {\n var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content',\n 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid',\n 'ref', 'ref_src', 'source', 'medium', 'campaign'];\n \n function cleanUrl(url) {\n try {\n var u = new URL(url, window.location.origin);\n var changed = false;\n trackingParams.forEach(function(p) {\n if (u.searchParams.has(p)) {\n u.searchParams.delete(p);\n changed = true;\n }\n });\n return changed ? u.toString() : url;\n } catch (e) {\n return url;\n }\n }\n \n function cleanLinks() {\n document.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n \n cleanLinks();\n \n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1) {\n if (node.tagName === 'A') cleanLinks();\n node.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Remove Tracking Parameters from Links"); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + '
Skip to content

Repository files navigation

Uwe Reichel, audEERING GmbH, Gilching, Germany

  • machine learning data splitting tool that allows for:
    • group-disjunct splits (e.g. different speakers in train, dev, and test partition)
    • stratification on multiple target and grouping variables (e.g. emotion, gender, language)

From PyPI

  • set up a virtual environment venv_splitutils, activate it, and install splitutils. For Linux this works e.g. as follows:
$ virtualenv --python="/usr/bin/python3" venv_splitutils
$ source venv_splitutils/bin/activate
(venv_splitutils) $ pip install splitutils

From GitHub

$ git clone git@github.com:reichelu/spliutils.git
$ cd splitutils/
$ virtualenv --python="/usr/bin/python3" venv_splitutils
$ source venv_splitutils/bin/activate
$ (venv_splitutils) $ pip install -r requirements.txt
defoptimize_traintest_split(X, y, split_on, stratify_on, weight=None,
test_size=.1, k=30, seed=42):
''' optimize group-disjunct split into training and test set which is guided by: - disjunct split of values in SPLIT_ON - stratification by all keys in STRATIFY_ON (targets and groupings) - test set proportion in X should be close to test_size (which is the test proportion in set(split_on)) Parameters: X: (np.array or pd.DataFrame) of features y: (np.array) of targets of length N if type(y[0]) in ["str", "int"]: y is assumed to be categorical, so that it is additionally tested that all partitions cover all classes. Else y is assumed to be numeric and no coverage test is done. split_on: (np.array) list of length N with grouping variable (e.g. speaker IDs), on which the group-disjunct split is to be performed. Must be categorical. stratify_on: (dict) Dict-keys are variable names (targets and/or further groupings) the split should be stratified on (groupings could e.g. be sex, age class, etc). Dict-Values are np.array-s of length N that contain the variable values. All variables must be categorical. weight: (dict) weight for each variable in stratify_on. Defines their amount of contribution to the optimization score. Uniform weighting by default. Additional key: "size_diff" defines how test size diff should be weighted. test_size: (float) test proportion in set(split_on), e.g. 10% of speakers to be held-out k: (int) number of different splits to be tried out seed: (int) random seed Returns: train_i: (np.array) train set indices in X test_i: (np.array) test set indices in X info: (dict) detail information about reference and achieved prob distributions "size_testset_in_spliton": intended test_size "size_testset_in_X": optimized test proportion in X "p_ref_{c}": reference class distribution calculated from stratify_on[c] "p_test_{c}": test set class distribution calculated from stratify_on[c][test_i] '''
defoptimize_traindevtest_split(X, y, split_on, stratify_on, weight=None,
dev_size=.1, test_size=.1, testset_not_smaller=False,
k=30, seed=42):
''' optimize group-disjunct split into training, dev, and test set, which is guided by: - disjunct split of values in SPLIT_ON - stratification by all keys in STRATIFY_ON (targets and groupings) - test set proportion in X should be close to test_size (which is the test proportion in set(split_on)) Parameters: X: (np.array or pd.DataFrame) of features y: (np.array) of targets of length N if type(y[0]) in ["str", "int"]: y is assumed to be categorical, so that it is additionally tested that all partitions cover all classes. Else y is assumed to be numeric and no coverage test is done. split_on: (np.array) list of length N with grouping variable (e.g. speaker IDs), on which the group-disjunct split is to be performed. Must be categorical. stratify_on: (dict) Dict-keys are variable names (targets and/or further groupings) the split should be stratified on (groupings could e.g. be sex, age class, etc). Dict-Values are np.array-s of length N that contain the variable values. All variables must be categorical. weight: (dict) weight for each variable in stratify_on. Defines their amount of contribution to the optimization score. Uniform weighting by default. Additional key: "size_diff" defines how the corresponding size differences should be weighted. dev_size: (float) proportion in set(split_on) for dev set, e.g. 10% of speakers to be held-out test_size: (float) test proportion in set(split_on) for test set testset_not_smaller (bool) if True, and if test_size >= dev_size, it is ensured, that the resulting test set is not smaller than the dev set k: (int) number of different splits to be tried out seed: (int) random seed Returns: train_i: (np.array) train set indices in X dev_i: (np.array) dev set indices in X test_i: (np.array) test set indices in X info: (dict) detail information about reference and achieved prob distributions "dev_size_in_spliton": intended grouping dev_size "dev_size_in_X": optimized dev proportion of observations in X "test_size_in_spliton": intended grouping test_size "test_size_in_X": optimized test proportion of observations in X "p_ref_{c}": reference class distribution calculated from stratify_on[c] "p_dev_{c}": dev set class distribution calculated from stratify_on[c][dev_i] "p_test_{c}": test set class distribution calculated from stratify_on[c][test_i] '''
defbinning(x, nbins=2, lower_boundaries=None, seed=42):
''' bins numeric data. If X is one-dimensional: binning is done either intrinsically into nbins classes based on an equidistant percentile split, or extrinsically by using the lower_boundaries values. If X is two-dimensional binning is done by kmeans clustering into nbins clusters Parameters: x: (list, np.array) with numeric data. nbins: (int) number of bins lower_boundaries: (list) of lower bin boundaries. If y is 1-dim and lower_boundaries is provided, nbins will be ignored and y is binned extrinsically. The first value of lower_boundaries is always corrected not to be higher than min(y). seed: (int) random seed for kmeans Returns: c: (np.array) integers as bin IDs '''

if you use this software for a publication please cite:

Reichel, U.: splitutils - machine learning data partitioning software, version 0.3.0. doi:10.5281/zenodo.10793086, 2024.

@Misc{splitutils,
author = {Reichel, U.},
title = {splitutils -- machine learning data partitioning software, version 0.3.0},
howpublished = {doi:10.5281/zenodo.10793086},
year = {2024}
}
  • see scripts/run_traintest_split.py
  • partitions are:
    • disjunct on categorical "split_var"
    • stratified on categorical "target", "strat_var1", "strat_var2"
    • each contain all levels of "target"
importnumpyasnpimportosimportsys# add this line if you have cloned the code from github to PROJECT_DIR# sys.path.append(PROJECT_DIR)fromsplitutilsimportoptimize_traindevtest_split# set seedseed=42np.random.seed(seed)
# DUMMY DATA# sizen=100# feature arraydata=np.random.rand(100, 20)
# target variabletarget=np.random.choice(["A", "B"], size=n, replace=True)
# array with variable on which to do a disjunct splitsplit_var=np.random.choice(["D", "E", "F", "G", "H", "I", "J", "K"],
size=n, replace=True)
# dict of variables to stratify on. Key names are arbitrary.stratif_vars= {
"target": target,
"strat_var1": np.random.choice(["L", "M"], size=n, replace=True),
"strat_var2": np.random.choice(["N", "O"], size=n, replace=True)
}
# ARGUMENTS# weight importance of all stratification variables in stratify_in# as well as of "size_diff", which punishes the deviation of intended# and received partition sizes.# Key names must match the names in stratif_vars.weights= {
"target": 2,
"strat_var1": 1,
"strat_var2": 1,
"size_diff": 1
}
# test partition proportion (from 0 to 1)test_size=.2# number of disjunct splits to be tried out in brute force optimizationk=30# FIND OPTIMAL SPLITtrain_i, test_i, info=optimize_traintest_split(
X=data,
y=target,
split_on=split_var,
stratify_on=stratif_vars,
weight=weights,
test_size=test_size,
k=k,
seed=seed
)
# SOME OUTPUTprint("test levels of split_var:", sorted(set(split_var[test_i])))
print("goodness of split:", info)
  • see scripts/run_traindevtest_split.py
  • Partitions are
    • disjunct on categorical "split_var"
    • stratified on categorical "target", "strat_var1", "strat_var2"
    • each contain all levels of "target"
importnumpyasnpimportosimportsys# add this line if you have cloned the code from github to PROJECT_DIR# sys.path.append(PROJECT_DIR)fromsplitutilsimportoptimize_traindevtest_split# set seedseed=42np.random.seed(seed)
# DUMMY DATA# sizen=100# feature arraydata=np.random.rand(100, 20)
# target variabletarget=np.random.choice(["A", "B"], size=n, replace=True)
# array with variable on which to do a disjunct splitsplit_var=np.random.choice(["D", "E", "F", "G", "H", "I", "J", "K"],
size=n, replace=True)
# dict of variables to stratify on. Key names are arbitrary.stratif_vars= {
"target": target,
"strat_var1": np.random.choice(["F", "G"], size=n, replace=True),
"strat_var2": np.random.choice(["H", "I"], size=n, replace=True)
}
# ARGUMENTS# weight importance of all stratification variables in stratify_in# as well as of "size_diff", which punishes the deviation of intended# and received partition sizes.# Key names must match the names in stratif_vars.weights= {
"target": 2,
"strat_var1": 1,
"strat_var2": 1,
"size_diff": 1
}
# dev and test partition proportion (from 0 to 1)dev_size=.1test_size=.1# number of disjunct splits to be tried out in brute force optimizationk=30# FIND OPTIMAL SPLITtrain_i, dev_i, test_i, info=optimize_traindevtest_split(
X=data,
y=target,
split_on=split_var,
stratify_on=stratif_vars,
weight=weights,
dev_size=dev_size,
test_size=test_size,
k=k,
seed=seed
)
# SOME OUTPUTprint("test levels of split_var:", sorted(set(split_var[test_i])))
print("goodness of split:", info)
  • see scripts/run_traindevtest_split_with_binning.py
  • Partitions are
    • disjunct on categorical "split_var"
    • stratified on numeric "target", and on 3 other numeric stratification variables
importnumpyasnpimportosimportsys# add this line if you have cloned the code from github to PROJECT_DIR# sys.path.append(PROJECT_DIR)fromsplitutilsimport (
binning,
optimize_traindevtest_split
)
"""example script how to split dummy data into training, development,and test partitions that are* disjunct on categorical "split_var"* stratified on numeric "target", and on 3 other numeric stratification variables"""# set seedseed=42np.random.seed(seed)
# DUMMY DATA# sizen=100# featuresdata=np.random.rand(n, 20)
# numeric target variablenum_target=np.random.rand(n)
# array with variable on which to do a disjunct splitsplit_var=np.random.choice(["D", "E", "F", "G", "H", "I", "J", "K"],
size=n, replace=True)
# further numeric variables to stratify onnum_strat_vars=np.random.rand(n, 3)
# intrinsically bin target into 3 bins by equidistant# percentile boundariesbinned_target=binning(num_target, nbins=3)
# ... alternatively, a variable can be extrinsically binned by# specifying lower boundaries:# binned_target = binning(num_target, lower_boundaries=[0, 0.33, 0.66])# bin other stratification variables into a single variable with 6 bins# (2-dim input is binned by StandardScaling and KMeans clustering)binned_strat_var=binning(num_strat_vars, nbins=6)
# ... alternatively, each stratification variable could be binned# individually - intrinsically or extrinsically the same way as num_target# strat_var1 = binning(num_strat_vars[:,0], nbins=...) etc.# now add the obtained categorical variable to stratification dictstratif_vars= {
"target": binned_target,
"strat_var": binned_strat_var
}
# ARGUMENTS# weight importance of all stratification variables in stratify_in# as well as of "size_diff", which punishes the deviation of intended# and received partition sizesweights= {
"target": 2,
"strat_var": 1,
"size_diff": 1
}
# dev and test partition proportion (from 0 to 1)dev_size=.1test_size=.1# number of disjunct splits to be tried out in brute force optimizationk=30# FIND OPTIMAL SPLITtrain_i, dev_i, test_i, info=optimize_traindevtest_split(
X=data,
y=num_target,
split_on=split_var,
stratify_on=stratif_vars,
weight=weights,
dev_size=dev_size,
test_size=test_size,
k=k,
seed=seed
)
# SOME OUTPUTprint("test levels of split_var:", sorted(set(split_var[test_i])))
print("goodness of split:", info)
  • find optimal train, dev, and test set split based on:
    • disjunct split of a categorical grouping variable G (e.g. speaker)
    • optimized joint stratification on an arbitrary amount of categorical target and grouping variables (e.g. emotion, gender, ...)
    • close match of partition proportions in G and underlying dataset X
  • brute-force optimization on k disjunct splits of G
  • score to be minimzed for train/test set split:
(sum_v[w(v) * irad(v)] + w(d) * d) / (sum_v[w(v)] + w(d))
v: variables to be stratified on
w(v): their weight
irad(v): information radius between reference and test set distribution of factor levels in v
d: absolute difference between test proportions of X and G, i.e. between the proportion of test
samples and the proportion of groups (e.g. speakers) that go into the test set
w(d): its weight
  • score to be minimzed for train / dev / test set split:
(sum_v[w(v) * max_irad(v)] + w(d) * max_d) / (sum_v[w(v)] + w(d))
v: variables to be stratified on
w(v): their weight
max_irad(v): maximum information radius of reference distribution of classes in v and
- dev set distribution,
- test set distribution
max_d: maximum of absolute difference between proportions of X and G (see above) calculated for
the dev and test set
w(d): its weight
  • let's look at Example 2 above. There info becomes:
{
'score': 0.030828359568603338,
'size_devset_in_spliton': 0.1,
'size_devset_in_X': 0.14,
'size_testset_in_spliton': 0.1,
'size_testset_in_X': 0.13,
'p_target_ref': {'B': 0.49, 'A': 0.51},
'p_target_dev': {'A': 0.5, 'B': 0.5},
'p_target_test': {'A': 0.5384615384615384, 'B': 0.46153846153846156},
'p_strat_var1_ref': {'G': 0.56, 'F': 0.44},
'p_strat_var1_dev': {'G': 0.5714285714285714, 'F': 0.42857142857142855},
'p_strat_var1_test': {'F': 0.5384615384615384, 'G': 0.46153846153846156},
'p_strat_var2_ref': {'I': 0.48, 'H': 0.52},
'p_strat_var2_dev': {'I': 0.5, 'H': 0.5},
'p_strat_var2_test': {'I': 0.46153846153846156, 'H': 0.5384615384615384}
}
  • Explanations
    • score: see above, score to be minimzed for train / dev / test set split:
    • size_devset_in_spliton: proportion of to-be-split-on variable levels in development set
    • size_devset_in_X: proportion of rows in X in development set
    • size_testset_in_spliton: proportion of to-be-split-on variable levels in test set
    • size_testset_in_X: proportion of rows in X in test set
    • p_target_ref: reference target class distribution over all data
    • p_target_dev: target class distribution in development set
    • p_target_test: target class distribution in test set
    • p_strat_var1_ref: first stratification variable's reference distribution over all data
    • p_strat_var1_dev: first stratification variable's class distribution in development set
    • p_strat_var1_test: first stratification variable's class distribution in test set
    • p_strat_var2_ref: second stratification variable's reference distribution over all data
    • p_strat_var2_dev: second stratification variable's class distribution in development set
    • p_strat_var2_test: second stratification variable's class distribution in test set
  • Remarks
    • for splitutils.optimize_traintest_split() no development set results are reported
    • all *_strat_var* keys: key names derived from key names in stratify_on argument

About

machine learning data partitioning tool that allows for group-disjunct splits and stratification on multiple target and grouping variables

Resources

Stars

1 star

Watchers

1 watching

Forks

Releases

Packages

Used by

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Auto-enable theater mode on YouTube\n(function() {\n function tryTheater() {\n var btn = document.querySelector('button[aria-label=\"Theater mode\"], ytd-player #player button[title=\"Theater mode\"]');\n if (btn && !btn.classList.contains('activated')) {\n btn.click();\n }\n }\n \n // Try immediately\n tryTheater();\n \n // Try after navigation (SPA)\n var lastUrl = location.href;\n setInterval(function() {\n if (location.href !== lastUrl) {\n lastUrl = location.href;\n setTimeout(tryTheater, 500);\n }\n }, 1000);\n \n // Also try on player load\n var observer = new MutationObserver(tryTheater);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "YouTube Theater Mode Default"); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Repository files navigation

Uwe Reichel, audEERING GmbH, Gilching, Germany

  • machine learning data splitting tool that allows for:
    • group-disjunct splits (e.g. different speakers in train, dev, and test partition)
    • stratification on multiple target and grouping variables (e.g. emotion, gender, language)

From PyPI

  • set up a virtual environment venv_splitutils, activate it, and install splitutils. For Linux this works e.g. as follows:
$ virtualenv --python="/usr/bin/python3" venv_splitutils
$ source venv_splitutils/bin/activate
(venv_splitutils) $ pip install splitutils

From GitHub

$ git clone git@github.com:reichelu/spliutils.git
$ cd splitutils/
$ virtualenv --python="/usr/bin/python3" venv_splitutils
$ source venv_splitutils/bin/activate
$ (venv_splitutils) $ pip install -r requirements.txt
defoptimize_traintest_split(X, y, split_on, stratify_on, weight=None,
test_size=.1, k=30, seed=42):
''' optimize group-disjunct split into training and test set which is guided by: - disjunct split of values in SPLIT_ON - stratification by all keys in STRATIFY_ON (targets and groupings) - test set proportion in X should be close to test_size (which is the test proportion in set(split_on)) Parameters: X: (np.array or pd.DataFrame) of features y: (np.array) of targets of length N if type(y[0]) in ["str", "int"]: y is assumed to be categorical, so that it is additionally tested that all partitions cover all classes. Else y is assumed to be numeric and no coverage test is done. split_on: (np.array) list of length N with grouping variable (e.g. speaker IDs), on which the group-disjunct split is to be performed. Must be categorical. stratify_on: (dict) Dict-keys are variable names (targets and/or further groupings) the split should be stratified on (groupings could e.g. be sex, age class, etc). Dict-Values are np.array-s of length N that contain the variable values. All variables must be categorical. weight: (dict) weight for each variable in stratify_on. Defines their amount of contribution to the optimization score. Uniform weighting by default. Additional key: "size_diff" defines how test size diff should be weighted. test_size: (float) test proportion in set(split_on), e.g. 10% of speakers to be held-out k: (int) number of different splits to be tried out seed: (int) random seed Returns: train_i: (np.array) train set indices in X test_i: (np.array) test set indices in X info: (dict) detail information about reference and achieved prob distributions "size_testset_in_spliton": intended test_size "size_testset_in_X": optimized test proportion in X "p_ref_{c}": reference class distribution calculated from stratify_on[c] "p_test_{c}": test set class distribution calculated from stratify_on[c][test_i] '''
defoptimize_traindevtest_split(X, y, split_on, stratify_on, weight=None,
dev_size=.1, test_size=.1, testset_not_smaller=False,
k=30, seed=42):
''' optimize group-disjunct split into training, dev, and test set, which is guided by: - disjunct split of values in SPLIT_ON - stratification by all keys in STRATIFY_ON (targets and groupings) - test set proportion in X should be close to test_size (which is the test proportion in set(split_on)) Parameters: X: (np.array or pd.DataFrame) of features y: (np.array) of targets of length N if type(y[0]) in ["str", "int"]: y is assumed to be categorical, so that it is additionally tested that all partitions cover all classes. Else y is assumed to be numeric and no coverage test is done. split_on: (np.array) list of length N with grouping variable (e.g. speaker IDs), on which the group-disjunct split is to be performed. Must be categorical. stratify_on: (dict) Dict-keys are variable names (targets and/or further groupings) the split should be stratified on (groupings could e.g. be sex, age class, etc). Dict-Values are np.array-s of length N that contain the variable values. All variables must be categorical. weight: (dict) weight for each variable in stratify_on. Defines their amount of contribution to the optimization score. Uniform weighting by default. Additional key: "size_diff" defines how the corresponding size differences should be weighted. dev_size: (float) proportion in set(split_on) for dev set, e.g. 10% of speakers to be held-out test_size: (float) test proportion in set(split_on) for test set testset_not_smaller (bool) if True, and if test_size >= dev_size, it is ensured, that the resulting test set is not smaller than the dev set k: (int) number of different splits to be tried out seed: (int) random seed Returns: train_i: (np.array) train set indices in X dev_i: (np.array) dev set indices in X test_i: (np.array) test set indices in X info: (dict) detail information about reference and achieved prob distributions "dev_size_in_spliton": intended grouping dev_size "dev_size_in_X": optimized dev proportion of observations in X "test_size_in_spliton": intended grouping test_size "test_size_in_X": optimized test proportion of observations in X "p_ref_{c}": reference class distribution calculated from stratify_on[c] "p_dev_{c}": dev set class distribution calculated from stratify_on[c][dev_i] "p_test_{c}": test set class distribution calculated from stratify_on[c][test_i] '''
defbinning(x, nbins=2, lower_boundaries=None, seed=42):
''' bins numeric data. If X is one-dimensional: binning is done either intrinsically into nbins classes based on an equidistant percentile split, or extrinsically by using the lower_boundaries values. If X is two-dimensional binning is done by kmeans clustering into nbins clusters Parameters: x: (list, np.array) with numeric data. nbins: (int) number of bins lower_boundaries: (list) of lower bin boundaries. If y is 1-dim and lower_boundaries is provided, nbins will be ignored and y is binned extrinsically. The first value of lower_boundaries is always corrected not to be higher than min(y). seed: (int) random seed for kmeans Returns: c: (np.array) integers as bin IDs '''

if you use this software for a publication please cite:

Reichel, U.: splitutils - machine learning data partitioning software, version 0.3.0. doi:10.5281/zenodo.10793086, 2024.

@Misc{splitutils,
author = {Reichel, U.},
title = {splitutils -- machine learning data partitioning software, version 0.3.0},
howpublished = {doi:10.5281/zenodo.10793086},
year = {2024}
}
  • see scripts/run_traintest_split.py
  • partitions are:
    • disjunct on categorical "split_var"
    • stratified on categorical "target", "strat_var1", "strat_var2"
    • each contain all levels of "target"
importnumpyasnpimportosimportsys# add this line if you have cloned the code from github to PROJECT_DIR# sys.path.append(PROJECT_DIR)fromsplitutilsimportoptimize_traindevtest_split# set seedseed=42np.random.seed(seed)
# DUMMY DATA# sizen=100# feature arraydata=np.random.rand(100, 20)
# target variabletarget=np.random.choice(["A", "B"], size=n, replace=True)
# array with variable on which to do a disjunct splitsplit_var=np.random.choice(["D", "E", "F", "G", "H", "I", "J", "K"],
size=n, replace=True)
# dict of variables to stratify on. Key names are arbitrary.stratif_vars= {
"target": target,
"strat_var1": np.random.choice(["L", "M"], size=n, replace=True),
"strat_var2": np.random.choice(["N", "O"], size=n, replace=True)
}
# ARGUMENTS# weight importance of all stratification variables in stratify_in# as well as of "size_diff", which punishes the deviation of intended# and received partition sizes.# Key names must match the names in stratif_vars.weights= {
"target": 2,
"strat_var1": 1,
"strat_var2": 1,
"size_diff": 1
}
# test partition proportion (from 0 to 1)test_size=.2# number of disjunct splits to be tried out in brute force optimizationk=30# FIND OPTIMAL SPLITtrain_i, test_i, info=optimize_traintest_split(
X=data,
y=target,
split_on=split_var,
stratify_on=stratif_vars,
weight=weights,
test_size=test_size,
k=k,
seed=seed
)
# SOME OUTPUTprint("test levels of split_var:", sorted(set(split_var[test_i])))
print("goodness of split:", info)
  • see scripts/run_traindevtest_split.py
  • Partitions are
    • disjunct on categorical "split_var"
    • stratified on categorical "target", "strat_var1", "strat_var2"
    • each contain all levels of "target"
importnumpyasnpimportosimportsys# add this line if you have cloned the code from github to PROJECT_DIR# sys.path.append(PROJECT_DIR)fromsplitutilsimportoptimize_traindevtest_split# set seedseed=42np.random.seed(seed)
# DUMMY DATA# sizen=100# feature arraydata=np.random.rand(100, 20)
# target variabletarget=np.random.choice(["A", "B"], size=n, replace=True)
# array with variable on which to do a disjunct splitsplit_var=np.random.choice(["D", "E", "F", "G", "H", "I", "J", "K"],
size=n, replace=True)
# dict of variables to stratify on. Key names are arbitrary.stratif_vars= {
"target": target,
"strat_var1": np.random.choice(["F", "G"], size=n, replace=True),
"strat_var2": np.random.choice(["H", "I"], size=n, replace=True)
}
# ARGUMENTS# weight importance of all stratification variables in stratify_in# as well as of "size_diff", which punishes the deviation of intended# and received partition sizes.# Key names must match the names in stratif_vars.weights= {
"target": 2,
"strat_var1": 1,
"strat_var2": 1,
"size_diff": 1
}
# dev and test partition proportion (from 0 to 1)dev_size=.1test_size=.1# number of disjunct splits to be tried out in brute force optimizationk=30# FIND OPTIMAL SPLITtrain_i, dev_i, test_i, info=optimize_traindevtest_split(
X=data,
y=target,
split_on=split_var,
stratify_on=stratif_vars,
weight=weights,
dev_size=dev_size,
test_size=test_size,
k=k,
seed=seed
)
# SOME OUTPUTprint("test levels of split_var:", sorted(set(split_var[test_i])))
print("goodness of split:", info)
  • see scripts/run_traindevtest_split_with_binning.py
  • Partitions are
    • disjunct on categorical "split_var"
    • stratified on numeric "target", and on 3 other numeric stratification variables
importnumpyasnpimportosimportsys# add this line if you have cloned the code from github to PROJECT_DIR# sys.path.append(PROJECT_DIR)fromsplitutilsimport (
binning,
optimize_traindevtest_split
)
"""example script how to split dummy data into training, development,and test partitions that are* disjunct on categorical "split_var"* stratified on numeric "target", and on 3 other numeric stratification variables"""# set seedseed=42np.random.seed(seed)
# DUMMY DATA# sizen=100# featuresdata=np.random.rand(n, 20)
# numeric target variablenum_target=np.random.rand(n)
# array with variable on which to do a disjunct splitsplit_var=np.random.choice(["D", "E", "F", "G", "H", "I", "J", "K"],
size=n, replace=True)
# further numeric variables to stratify onnum_strat_vars=np.random.rand(n, 3)
# intrinsically bin target into 3 bins by equidistant# percentile boundariesbinned_target=binning(num_target, nbins=3)
# ... alternatively, a variable can be extrinsically binned by# specifying lower boundaries:# binned_target = binning(num_target, lower_boundaries=[0, 0.33, 0.66])# bin other stratification variables into a single variable with 6 bins# (2-dim input is binned by StandardScaling and KMeans clustering)binned_strat_var=binning(num_strat_vars, nbins=6)
# ... alternatively, each stratification variable could be binned# individually - intrinsically or extrinsically the same way as num_target# strat_var1 = binning(num_strat_vars[:,0], nbins=...) etc.# now add the obtained categorical variable to stratification dictstratif_vars= {
"target": binned_target,
"strat_var": binned_strat_var
}
# ARGUMENTS# weight importance of all stratification variables in stratify_in# as well as of "size_diff", which punishes the deviation of intended# and received partition sizesweights= {
"target": 2,
"strat_var": 1,
"size_diff": 1
}
# dev and test partition proportion (from 0 to 1)dev_size=.1test_size=.1# number of disjunct splits to be tried out in brute force optimizationk=30# FIND OPTIMAL SPLITtrain_i, dev_i, test_i, info=optimize_traindevtest_split(
X=data,
y=num_target,
split_on=split_var,
stratify_on=stratif_vars,
weight=weights,
dev_size=dev_size,
test_size=test_size,
k=k,
seed=seed
)
# SOME OUTPUTprint("test levels of split_var:", sorted(set(split_var[test_i])))
print("goodness of split:", info)
  • find optimal train, dev, and test set split based on:
    • disjunct split of a categorical grouping variable G (e.g. speaker)
    • optimized joint stratification on an arbitrary amount of categorical target and grouping variables (e.g. emotion, gender, ...)
    • close match of partition proportions in G and underlying dataset X
  • brute-force optimization on k disjunct splits of G
  • score to be minimzed for train/test set split:
(sum_v[w(v) * irad(v)] + w(d) * d) / (sum_v[w(v)] + w(d))
v: variables to be stratified on
w(v): their weight
irad(v): information radius between reference and test set distribution of factor levels in v
d: absolute difference between test proportions of X and G, i.e. between the proportion of test
samples and the proportion of groups (e.g. speakers) that go into the test set
w(d): its weight
  • score to be minimzed for train / dev / test set split:
(sum_v[w(v) * max_irad(v)] + w(d) * max_d) / (sum_v[w(v)] + w(d))
v: variables to be stratified on
w(v): their weight
max_irad(v): maximum information radius of reference distribution of classes in v and
- dev set distribution,
- test set distribution
max_d: maximum of absolute difference between proportions of X and G (see above) calculated for
the dev and test set
w(d): its weight
  • let's look at Example 2 above. There info becomes:
{
'score': 0.030828359568603338,
'size_devset_in_spliton': 0.1,
'size_devset_in_X': 0.14,
'size_testset_in_spliton': 0.1,
'size_testset_in_X': 0.13,
'p_target_ref': {'B': 0.49, 'A': 0.51},
'p_target_dev': {'A': 0.5, 'B': 0.5},
'p_target_test': {'A': 0.5384615384615384, 'B': 0.46153846153846156},
'p_strat_var1_ref': {'G': 0.56, 'F': 0.44},
'p_strat_var1_dev': {'G': 0.5714285714285714, 'F': 0.42857142857142855},
'p_strat_var1_test': {'F': 0.5384615384615384, 'G': 0.46153846153846156},
'p_strat_var2_ref': {'I': 0.48, 'H': 0.52},
'p_strat_var2_dev': {'I': 0.5, 'H': 0.5},
'p_strat_var2_test': {'I': 0.46153846153846156, 'H': 0.5384615384615384}
}
  • Explanations
    • score: see above, score to be minimzed for train / dev / test set split:
    • size_devset_in_spliton: proportion of to-be-split-on variable levels in development set
    • size_devset_in_X: proportion of rows in X in development set
    • size_testset_in_spliton: proportion of to-be-split-on variable levels in test set
    • size_testset_in_X: proportion of rows in X in test set
    • p_target_ref: reference target class distribution over all data
    • p_target_dev: target class distribution in development set
    • p_target_test: target class distribution in test set
    • p_strat_var1_ref: first stratification variable's reference distribution over all data
    • p_strat_var1_dev: first stratification variable's class distribution in development set
    • p_strat_var1_test: first stratification variable's class distribution in test set
    • p_strat_var2_ref: second stratification variable's reference distribution over all data
    • p_strat_var2_dev: second stratification variable's class distribution in development set
    • p_strat_var2_test: second stratification variable's class distribution in test set
  • Remarks
    • for splitutils.optimize_traintest_split() no development set results are reported
    • all *_strat_var* keys: key names derived from key names in stratify_on argument

About

machine learning data partitioning tool that allows for group-disjunct splits and stratification on multiple target and grouping variables

Resources

Stars

1 star

Watchers

1 watching

Forks

Releases

Packages

Used by

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Remove or un-stick sticky/fixed headers that block content\n(function() {\n function unstick() {\n document.querySelectorAll('header, nav, [role=\"banner\"], .header, .navbar, .sticky, .fixed-top, [style*=\"position: fixed\"], [style*=\"position:sticky\"]').forEach(function(el) {\n if (el.style.position === 'fixed' || el.style.position === 'sticky' || \n getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') {\n el.style.position = 'static';\n el.style.top = 'auto';\n el.style.zIndex = 'auto';\n }\n });\n }\n \n unstick();\n \n var observer = new MutationObserver(unstick);\n observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] });\n})();", "Kill Sticky Headers"); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Repository files navigation

Uwe Reichel, audEERING GmbH, Gilching, Germany

  • machine learning data splitting tool that allows for:
    • group-disjunct splits (e.g. different speakers in train, dev, and test partition)
    • stratification on multiple target and grouping variables (e.g. emotion, gender, language)

From PyPI

  • set up a virtual environment venv_splitutils, activate it, and install splitutils. For Linux this works e.g. as follows:
$ virtualenv --python="/usr/bin/python3" venv_splitutils
$ source venv_splitutils/bin/activate
(venv_splitutils) $ pip install splitutils

From GitHub

$ git clone git@github.com:reichelu/spliutils.git
$ cd splitutils/
$ virtualenv --python="/usr/bin/python3" venv_splitutils
$ source venv_splitutils/bin/activate
$ (venv_splitutils) $ pip install -r requirements.txt
defoptimize_traintest_split(X, y, split_on, stratify_on, weight=None,
test_size=.1, k=30, seed=42):
''' optimize group-disjunct split into training and test set which is guided by: - disjunct split of values in SPLIT_ON - stratification by all keys in STRATIFY_ON (targets and groupings) - test set proportion in X should be close to test_size (which is the test proportion in set(split_on)) Parameters: X: (np.array or pd.DataFrame) of features y: (np.array) of targets of length N if type(y[0]) in ["str", "int"]: y is assumed to be categorical, so that it is additionally tested that all partitions cover all classes. Else y is assumed to be numeric and no coverage test is done. split_on: (np.array) list of length N with grouping variable (e.g. speaker IDs), on which the group-disjunct split is to be performed. Must be categorical. stratify_on: (dict) Dict-keys are variable names (targets and/or further groupings) the split should be stratified on (groupings could e.g. be sex, age class, etc). Dict-Values are np.array-s of length N that contain the variable values. All variables must be categorical. weight: (dict) weight for each variable in stratify_on. Defines their amount of contribution to the optimization score. Uniform weighting by default. Additional key: "size_diff" defines how test size diff should be weighted. test_size: (float) test proportion in set(split_on), e.g. 10% of speakers to be held-out k: (int) number of different splits to be tried out seed: (int) random seed Returns: train_i: (np.array) train set indices in X test_i: (np.array) test set indices in X info: (dict) detail information about reference and achieved prob distributions "size_testset_in_spliton": intended test_size "size_testset_in_X": optimized test proportion in X "p_ref_{c}": reference class distribution calculated from stratify_on[c] "p_test_{c}": test set class distribution calculated from stratify_on[c][test_i] '''
defoptimize_traindevtest_split(X, y, split_on, stratify_on, weight=None,
dev_size=.1, test_size=.1, testset_not_smaller=False,
k=30, seed=42):
''' optimize group-disjunct split into training, dev, and test set, which is guided by: - disjunct split of values in SPLIT_ON - stratification by all keys in STRATIFY_ON (targets and groupings) - test set proportion in X should be close to test_size (which is the test proportion in set(split_on)) Parameters: X: (np.array or pd.DataFrame) of features y: (np.array) of targets of length N if type(y[0]) in ["str", "int"]: y is assumed to be categorical, so that it is additionally tested that all partitions cover all classes. Else y is assumed to be numeric and no coverage test is done. split_on: (np.array) list of length N with grouping variable (e.g. speaker IDs), on which the group-disjunct split is to be performed. Must be categorical. stratify_on: (dict) Dict-keys are variable names (targets and/or further groupings) the split should be stratified on (groupings could e.g. be sex, age class, etc). Dict-Values are np.array-s of length N that contain the variable values. All variables must be categorical. weight: (dict) weight for each variable in stratify_on. Defines their amount of contribution to the optimization score. Uniform weighting by default. Additional key: "size_diff" defines how the corresponding size differences should be weighted. dev_size: (float) proportion in set(split_on) for dev set, e.g. 10% of speakers to be held-out test_size: (float) test proportion in set(split_on) for test set testset_not_smaller (bool) if True, and if test_size >= dev_size, it is ensured, that the resulting test set is not smaller than the dev set k: (int) number of different splits to be tried out seed: (int) random seed Returns: train_i: (np.array) train set indices in X dev_i: (np.array) dev set indices in X test_i: (np.array) test set indices in X info: (dict) detail information about reference and achieved prob distributions "dev_size_in_spliton": intended grouping dev_size "dev_size_in_X": optimized dev proportion of observations in X "test_size_in_spliton": intended grouping test_size "test_size_in_X": optimized test proportion of observations in X "p_ref_{c}": reference class distribution calculated from stratify_on[c] "p_dev_{c}": dev set class distribution calculated from stratify_on[c][dev_i] "p_test_{c}": test set class distribution calculated from stratify_on[c][test_i] '''
defbinning(x, nbins=2, lower_boundaries=None, seed=42):
''' bins numeric data. If X is one-dimensional: binning is done either intrinsically into nbins classes based on an equidistant percentile split, or extrinsically by using the lower_boundaries values. If X is two-dimensional binning is done by kmeans clustering into nbins clusters Parameters: x: (list, np.array) with numeric data. nbins: (int) number of bins lower_boundaries: (list) of lower bin boundaries. If y is 1-dim and lower_boundaries is provided, nbins will be ignored and y is binned extrinsically. The first value of lower_boundaries is always corrected not to be higher than min(y). seed: (int) random seed for kmeans Returns: c: (np.array) integers as bin IDs '''

if you use this software for a publication please cite:

Reichel, U.: splitutils - machine learning data partitioning software, version 0.3.0. doi:10.5281/zenodo.10793086, 2024.

@Misc{splitutils,
author = {Reichel, U.},
title = {splitutils -- machine learning data partitioning software, version 0.3.0},
howpublished = {doi:10.5281/zenodo.10793086},
year = {2024}
}
  • see scripts/run_traintest_split.py
  • partitions are:
    • disjunct on categorical "split_var"
    • stratified on categorical "target", "strat_var1", "strat_var2"
    • each contain all levels of "target"
importnumpyasnpimportosimportsys# add this line if you have cloned the code from github to PROJECT_DIR# sys.path.append(PROJECT_DIR)fromsplitutilsimportoptimize_traindevtest_split# set seedseed=42np.random.seed(seed)
# DUMMY DATA# sizen=100# feature arraydata=np.random.rand(100, 20)
# target variabletarget=np.random.choice(["A", "B"], size=n, replace=True)
# array with variable on which to do a disjunct splitsplit_var=np.random.choice(["D", "E", "F", "G", "H", "I", "J", "K"],
size=n, replace=True)
# dict of variables to stratify on. Key names are arbitrary.stratif_vars= {
"target": target,
"strat_var1": np.random.choice(["L", "M"], size=n, replace=True),
"strat_var2": np.random.choice(["N", "O"], size=n, replace=True)
}
# ARGUMENTS# weight importance of all stratification variables in stratify_in# as well as of "size_diff", which punishes the deviation of intended# and received partition sizes.# Key names must match the names in stratif_vars.weights= {
"target": 2,
"strat_var1": 1,
"strat_var2": 1,
"size_diff": 1
}
# test partition proportion (from 0 to 1)test_size=.2# number of disjunct splits to be tried out in brute force optimizationk=30# FIND OPTIMAL SPLITtrain_i, test_i, info=optimize_traintest_split(
X=data,
y=target,
split_on=split_var,
stratify_on=stratif_vars,
weight=weights,
test_size=test_size,
k=k,
seed=seed
)
# SOME OUTPUTprint("test levels of split_var:", sorted(set(split_var[test_i])))
print("goodness of split:", info)
  • see scripts/run_traindevtest_split.py
  • Partitions are
    • disjunct on categorical "split_var"
    • stratified on categorical "target", "strat_var1", "strat_var2"
    • each contain all levels of "target"
importnumpyasnpimportosimportsys# add this line if you have cloned the code from github to PROJECT_DIR# sys.path.append(PROJECT_DIR)fromsplitutilsimportoptimize_traindevtest_split# set seedseed=42np.random.seed(seed)
# DUMMY DATA# sizen=100# feature arraydata=np.random.rand(100, 20)
# target variabletarget=np.random.choice(["A", "B"], size=n, replace=True)
# array with variable on which to do a disjunct splitsplit_var=np.random.choice(["D", "E", "F", "G", "H", "I", "J", "K"],
size=n, replace=True)
# dict of variables to stratify on. Key names are arbitrary.stratif_vars= {
"target": target,
"strat_var1": np.random.choice(["F", "G"], size=n, replace=True),
"strat_var2": np.random.choice(["H", "I"], size=n, replace=True)
}
# ARGUMENTS# weight importance of all stratification variables in stratify_in# as well as of "size_diff", which punishes the deviation of intended# and received partition sizes.# Key names must match the names in stratif_vars.weights= {
"target": 2,
"strat_var1": 1,
"strat_var2": 1,
"size_diff": 1
}
# dev and test partition proportion (from 0 to 1)dev_size=.1test_size=.1# number of disjunct splits to be tried out in brute force optimizationk=30# FIND OPTIMAL SPLITtrain_i, dev_i, test_i, info=optimize_traindevtest_split(
X=data,
y=target,
split_on=split_var,
stratify_on=stratif_vars,
weight=weights,
dev_size=dev_size,
test_size=test_size,
k=k,
seed=seed
)
# SOME OUTPUTprint("test levels of split_var:", sorted(set(split_var[test_i])))
print("goodness of split:", info)
  • see scripts/run_traindevtest_split_with_binning.py
  • Partitions are
    • disjunct on categorical "split_var"
    • stratified on numeric "target", and on 3 other numeric stratification variables
importnumpyasnpimportosimportsys# add this line if you have cloned the code from github to PROJECT_DIR# sys.path.append(PROJECT_DIR)fromsplitutilsimport (
binning,
optimize_traindevtest_split
)
"""example script how to split dummy data into training, development,and test partitions that are* disjunct on categorical "split_var"* stratified on numeric "target", and on 3 other numeric stratification variables"""# set seedseed=42np.random.seed(seed)
# DUMMY DATA# sizen=100# featuresdata=np.random.rand(n, 20)
# numeric target variablenum_target=np.random.rand(n)
# array with variable on which to do a disjunct splitsplit_var=np.random.choice(["D", "E", "F", "G", "H", "I", "J", "K"],
size=n, replace=True)
# further numeric variables to stratify onnum_strat_vars=np.random.rand(n, 3)
# intrinsically bin target into 3 bins by equidistant# percentile boundariesbinned_target=binning(num_target, nbins=3)
# ... alternatively, a variable can be extrinsically binned by# specifying lower boundaries:# binned_target = binning(num_target, lower_boundaries=[0, 0.33, 0.66])# bin other stratification variables into a single variable with 6 bins# (2-dim input is binned by StandardScaling and KMeans clustering)binned_strat_var=binning(num_strat_vars, nbins=6)
# ... alternatively, each stratification variable could be binned# individually - intrinsically or extrinsically the same way as num_target# strat_var1 = binning(num_strat_vars[:,0], nbins=...) etc.# now add the obtained categorical variable to stratification dictstratif_vars= {
"target": binned_target,
"strat_var": binned_strat_var
}
# ARGUMENTS# weight importance of all stratification variables in stratify_in# as well as of "size_diff", which punishes the deviation of intended# and received partition sizesweights= {
"target": 2,
"strat_var": 1,
"size_diff": 1
}
# dev and test partition proportion (from 0 to 1)dev_size=.1test_size=.1# number of disjunct splits to be tried out in brute force optimizationk=30# FIND OPTIMAL SPLITtrain_i, dev_i, test_i, info=optimize_traindevtest_split(
X=data,
y=num_target,
split_on=split_var,
stratify_on=stratif_vars,
weight=weights,
dev_size=dev_size,
test_size=test_size,
k=k,
seed=seed
)
# SOME OUTPUTprint("test levels of split_var:", sorted(set(split_var[test_i])))
print("goodness of split:", info)
  • find optimal train, dev, and test set split based on:
    • disjunct split of a categorical grouping variable G (e.g. speaker)
    • optimized joint stratification on an arbitrary amount of categorical target and grouping variables (e.g. emotion, gender, ...)
    • close match of partition proportions in G and underlying dataset X
  • brute-force optimization on k disjunct splits of G
  • score to be minimzed for train/test set split:
(sum_v[w(v) * irad(v)] + w(d) * d) / (sum_v[w(v)] + w(d))
v: variables to be stratified on
w(v): their weight
irad(v): information radius between reference and test set distribution of factor levels in v
d: absolute difference between test proportions of X and G, i.e. between the proportion of test
samples and the proportion of groups (e.g. speakers) that go into the test set
w(d): its weight
  • score to be minimzed for train / dev / test set split:
(sum_v[w(v) * max_irad(v)] + w(d) * max_d) / (sum_v[w(v)] + w(d))
v: variables to be stratified on
w(v): their weight
max_irad(v): maximum information radius of reference distribution of classes in v and
- dev set distribution,
- test set distribution
max_d: maximum of absolute difference between proportions of X and G (see above) calculated for
the dev and test set
w(d): its weight
  • let's look at Example 2 above. There info becomes:
{
'score': 0.030828359568603338,
'size_devset_in_spliton': 0.1,
'size_devset_in_X': 0.14,
'size_testset_in_spliton': 0.1,
'size_testset_in_X': 0.13,
'p_target_ref': {'B': 0.49, 'A': 0.51},
'p_target_dev': {'A': 0.5, 'B': 0.5},
'p_target_test': {'A': 0.5384615384615384, 'B': 0.46153846153846156},
'p_strat_var1_ref': {'G': 0.56, 'F': 0.44},
'p_strat_var1_dev': {'G': 0.5714285714285714, 'F': 0.42857142857142855},
'p_strat_var1_test': {'F': 0.5384615384615384, 'G': 0.46153846153846156},
'p_strat_var2_ref': {'I': 0.48, 'H': 0.52},
'p_strat_var2_dev': {'I': 0.5, 'H': 0.5},
'p_strat_var2_test': {'I': 0.46153846153846156, 'H': 0.5384615384615384}
}
  • Explanations
    • score: see above, score to be minimzed for train / dev / test set split:
    • size_devset_in_spliton: proportion of to-be-split-on variable levels in development set
    • size_devset_in_X: proportion of rows in X in development set
    • size_testset_in_spliton: proportion of to-be-split-on variable levels in test set
    • size_testset_in_X: proportion of rows in X in test set
    • p_target_ref: reference target class distribution over all data
    • p_target_dev: target class distribution in development set
    • p_target_test: target class distribution in test set
    • p_strat_var1_ref: first stratification variable's reference distribution over all data
    • p_strat_var1_dev: first stratification variable's class distribution in development set
    • p_strat_var1_test: first stratification variable's class distribution in test set
    • p_strat_var2_ref: second stratification variable's reference distribution over all data
    • p_strat_var2_dev: second stratification variable's class distribution in development set
    • p_strat_var2_test: second stratification variable's class distribution in test set
  • Remarks
    • for splitutils.optimize_traintest_split() no development set results are reported
    • all *_strat_var* keys: key names derived from key names in stratify_on argument

About

machine learning data partitioning tool that allows for group-disjunct splits and stratification on multiple target and grouping variables

Resources

Stars

1 star

Watchers

1 watching

Forks

Releases

Packages

Used by

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Universal Dark Mode - works on any site\n(function() {\n var enabled = true;\n \n function applyDarkMode() {\n if (!enabled) return;\n \n // Create style element if it doesn't exist\n var style = document.getElementById('universal-dark-mode-style');\n if (!style) {\n style = document.createElement('style');\n style.id = 'universal-dark-mode-style';\n document.head.appendChild(style);\n }\n \n // Dark mode CSS - inverts colors but preserves images/video\n style.textContent = '\n /* Invert everything except media */\n html {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #1a1a2e !important;\n }\n \n /* Restore images, videos, iframes, canvas */\n img, video, iframe, canvas, svg, picture, [style*=\"background-image\"] {\n filter: invert(1) hue-rotate(180deg) !important;\n }\n \n /* Preserve specific elements that should not be inverted */\n .no-dark-mode, .no-dark-mode *,\n [data-theme=\"light\"], [data-theme=\"light\"],\n .ace_editor, .ace_editor *,\n .CodeMirror, .CodeMirror *,\n .monaco-editor, .monaco-editor *,\n .markdown-body pre, .markdown-body pre *,\n .highlight, .highlight *,\n pre code, pre code * {\n filter: none !important;\n }\n \n /* Fix common UI elements */\n .modal, .popup, .dropdown-menu, .tooltip, .popover {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #2d2d44 !important;\n border-color: #444 !important;\n }\n \n /* Scrollbars */\n ::-webkit-scrollbar { background: #1a1a2e !important; }\n ::-webkit-scrollbar-thumb { background: #444 !important; }\n ::-webkit-scrollbar-thumb:hover { background: #555 !important; }\n \n /* Selection */\n ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ';\n }\n \n function removeDarkMode() {\n var style = document.getElementById('universal-dark-mode-style');\n if (style) style.remove();\n }\n \n // Toggle with Alt+Shift+D\n document.addEventListener('keydown', function(e) {\n if (e.altKey && e.shiftKey && e.key === 'D') {\n e.preventDefault();\n enabled = !enabled;\n if (enabled) {\n applyDarkMode();\n console.log('[Universal Dark Mode] Enabled');\n } else {\n removeDarkMode();\n console.log('[Universal Dark Mode] Disabled');\n }\n }\n });\n \n // Apply on load\n applyDarkMode();\n \n // Re-apply on dynamic content\n var observer = new MutationObserver(function(mutations) {\n if (enabled && !document.getElementById('universal-dark-mode-style')) {\n applyDarkMode();\n }\n });\n observer.observe(document.head, { childList: true });\n \n console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle');\n})();", "Universal Dark Mode"); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })();
Skip to content

Repository files navigation

Uwe Reichel, audEERING GmbH, Gilching, Germany

  • machine learning data splitting tool that allows for:
    • group-disjunct splits (e.g. different speakers in train, dev, and test partition)
    • stratification on multiple target and grouping variables (e.g. emotion, gender, language)

From PyPI

  • set up a virtual environment venv_splitutils, activate it, and install splitutils. For Linux this works e.g. as follows:
$ virtualenv --python="/usr/bin/python3" venv_splitutils
$ source venv_splitutils/bin/activate
(venv_splitutils) $ pip install splitutils

From GitHub

$ git clone git@github.com:reichelu/spliutils.git
$ cd splitutils/
$ virtualenv --python="/usr/bin/python3" venv_splitutils
$ source venv_splitutils/bin/activate
$ (venv_splitutils) $ pip install -r requirements.txt
defoptimize_traintest_split(X, y, split_on, stratify_on, weight=None,
test_size=.1, k=30, seed=42):
''' optimize group-disjunct split into training and test set which is guided by: - disjunct split of values in SPLIT_ON - stratification by all keys in STRATIFY_ON (targets and groupings) - test set proportion in X should be close to test_size (which is the test proportion in set(split_on)) Parameters: X: (np.array or pd.DataFrame) of features y: (np.array) of targets of length N if type(y[0]) in ["str", "int"]: y is assumed to be categorical, so that it is additionally tested that all partitions cover all classes. Else y is assumed to be numeric and no coverage test is done. split_on: (np.array) list of length N with grouping variable (e.g. speaker IDs), on which the group-disjunct split is to be performed. Must be categorical. stratify_on: (dict) Dict-keys are variable names (targets and/or further groupings) the split should be stratified on (groupings could e.g. be sex, age class, etc). Dict-Values are np.array-s of length N that contain the variable values. All variables must be categorical. weight: (dict) weight for each variable in stratify_on. Defines their amount of contribution to the optimization score. Uniform weighting by default. Additional key: "size_diff" defines how test size diff should be weighted. test_size: (float) test proportion in set(split_on), e.g. 10% of speakers to be held-out k: (int) number of different splits to be tried out seed: (int) random seed Returns: train_i: (np.array) train set indices in X test_i: (np.array) test set indices in X info: (dict) detail information about reference and achieved prob distributions "size_testset_in_spliton": intended test_size "size_testset_in_X": optimized test proportion in X "p_ref_{c}": reference class distribution calculated from stratify_on[c] "p_test_{c}": test set class distribution calculated from stratify_on[c][test_i] '''
defoptimize_traindevtest_split(X, y, split_on, stratify_on, weight=None,
dev_size=.1, test_size=.1, testset_not_smaller=False,
k=30, seed=42):
''' optimize group-disjunct split into training, dev, and test set, which is guided by: - disjunct split of values in SPLIT_ON - stratification by all keys in STRATIFY_ON (targets and groupings) - test set proportion in X should be close to test_size (which is the test proportion in set(split_on)) Parameters: X: (np.array or pd.DataFrame) of features y: (np.array) of targets of length N if type(y[0]) in ["str", "int"]: y is assumed to be categorical, so that it is additionally tested that all partitions cover all classes. Else y is assumed to be numeric and no coverage test is done. split_on: (np.array) list of length N with grouping variable (e.g. speaker IDs), on which the group-disjunct split is to be performed. Must be categorical. stratify_on: (dict) Dict-keys are variable names (targets and/or further groupings) the split should be stratified on (groupings could e.g. be sex, age class, etc). Dict-Values are np.array-s of length N that contain the variable values. All variables must be categorical. weight: (dict) weight for each variable in stratify_on. Defines their amount of contribution to the optimization score. Uniform weighting by default. Additional key: "size_diff" defines how the corresponding size differences should be weighted. dev_size: (float) proportion in set(split_on) for dev set, e.g. 10% of speakers to be held-out test_size: (float) test proportion in set(split_on) for test set testset_not_smaller (bool) if True, and if test_size >= dev_size, it is ensured, that the resulting test set is not smaller than the dev set k: (int) number of different splits to be tried out seed: (int) random seed Returns: train_i: (np.array) train set indices in X dev_i: (np.array) dev set indices in X test_i: (np.array) test set indices in X info: (dict) detail information about reference and achieved prob distributions "dev_size_in_spliton": intended grouping dev_size "dev_size_in_X": optimized dev proportion of observations in X "test_size_in_spliton": intended grouping test_size "test_size_in_X": optimized test proportion of observations in X "p_ref_{c}": reference class distribution calculated from stratify_on[c] "p_dev_{c}": dev set class distribution calculated from stratify_on[c][dev_i] "p_test_{c}": test set class distribution calculated from stratify_on[c][test_i] '''
defbinning(x, nbins=2, lower_boundaries=None, seed=42):
''' bins numeric data. If X is one-dimensional: binning is done either intrinsically into nbins classes based on an equidistant percentile split, or extrinsically by using the lower_boundaries values. If X is two-dimensional binning is done by kmeans clustering into nbins clusters Parameters: x: (list, np.array) with numeric data. nbins: (int) number of bins lower_boundaries: (list) of lower bin boundaries. If y is 1-dim and lower_boundaries is provided, nbins will be ignored and y is binned extrinsically. The first value of lower_boundaries is always corrected not to be higher than min(y). seed: (int) random seed for kmeans Returns: c: (np.array) integers as bin IDs '''

if you use this software for a publication please cite:

Reichel, U.: splitutils - machine learning data partitioning software, version 0.3.0. doi:10.5281/zenodo.10793086, 2024.

@Misc{splitutils,
author = {Reichel, U.},
title = {splitutils -- machine learning data partitioning software, version 0.3.0},
howpublished = {doi:10.5281/zenodo.10793086},
year = {2024}
}
  • see scripts/run_traintest_split.py
  • partitions are:
    • disjunct on categorical "split_var"
    • stratified on categorical "target", "strat_var1", "strat_var2"
    • each contain all levels of "target"
importnumpyasnpimportosimportsys# add this line if you have cloned the code from github to PROJECT_DIR# sys.path.append(PROJECT_DIR)fromsplitutilsimportoptimize_traindevtest_split# set seedseed=42np.random.seed(seed)
# DUMMY DATA# sizen=100# feature arraydata=np.random.rand(100, 20)
# target variabletarget=np.random.choice(["A", "B"], size=n, replace=True)
# array with variable on which to do a disjunct splitsplit_var=np.random.choice(["D", "E", "F", "G", "H", "I", "J", "K"],
size=n, replace=True)
# dict of variables to stratify on. Key names are arbitrary.stratif_vars= {
"target": target,
"strat_var1": np.random.choice(["L", "M"], size=n, replace=True),
"strat_var2": np.random.choice(["N", "O"], size=n, replace=True)
}
# ARGUMENTS# weight importance of all stratification variables in stratify_in# as well as of "size_diff", which punishes the deviation of intended# and received partition sizes.# Key names must match the names in stratif_vars.weights= {
"target": 2,
"strat_var1": 1,
"strat_var2": 1,
"size_diff": 1
}
# test partition proportion (from 0 to 1)test_size=.2# number of disjunct splits to be tried out in brute force optimizationk=30# FIND OPTIMAL SPLITtrain_i, test_i, info=optimize_traintest_split(
X=data,
y=target,
split_on=split_var,
stratify_on=stratif_vars,
weight=weights,
test_size=test_size,
k=k,
seed=seed
)
# SOME OUTPUTprint("test levels of split_var:", sorted(set(split_var[test_i])))
print("goodness of split:", info)
  • see scripts/run_traindevtest_split.py
  • Partitions are
    • disjunct on categorical "split_var"
    • stratified on categorical "target", "strat_var1", "strat_var2"
    • each contain all levels of "target"
importnumpyasnpimportosimportsys# add this line if you have cloned the code from github to PROJECT_DIR# sys.path.append(PROJECT_DIR)fromsplitutilsimportoptimize_traindevtest_split# set seedseed=42np.random.seed(seed)
# DUMMY DATA# sizen=100# feature arraydata=np.random.rand(100, 20)
# target variabletarget=np.random.choice(["A", "B"], size=n, replace=True)
# array with variable on which to do a disjunct splitsplit_var=np.random.choice(["D", "E", "F", "G", "H", "I", "J", "K"],
size=n, replace=True)
# dict of variables to stratify on. Key names are arbitrary.stratif_vars= {
"target": target,
"strat_var1": np.random.choice(["F", "G"], size=n, replace=True),
"strat_var2": np.random.choice(["H", "I"], size=n, replace=True)
}
# ARGUMENTS# weight importance of all stratification variables in stratify_in# as well as of "size_diff", which punishes the deviation of intended# and received partition sizes.# Key names must match the names in stratif_vars.weights= {
"target": 2,
"strat_var1": 1,
"strat_var2": 1,
"size_diff": 1
}
# dev and test partition proportion (from 0 to 1)dev_size=.1test_size=.1# number of disjunct splits to be tried out in brute force optimizationk=30# FIND OPTIMAL SPLITtrain_i, dev_i, test_i, info=optimize_traindevtest_split(
X=data,
y=target,
split_on=split_var,
stratify_on=stratif_vars,
weight=weights,
dev_size=dev_size,
test_size=test_size,
k=k,
seed=seed
)
# SOME OUTPUTprint("test levels of split_var:", sorted(set(split_var[test_i])))
print("goodness of split:", info)
  • see scripts/run_traindevtest_split_with_binning.py
  • Partitions are
    • disjunct on categorical "split_var"
    • stratified on numeric "target", and on 3 other numeric stratification variables
importnumpyasnpimportosimportsys# add this line if you have cloned the code from github to PROJECT_DIR# sys.path.append(PROJECT_DIR)fromsplitutilsimport (
binning,
optimize_traindevtest_split
)
"""example script how to split dummy data into training, development,and test partitions that are* disjunct on categorical "split_var"* stratified on numeric "target", and on 3 other numeric stratification variables"""# set seedseed=42np.random.seed(seed)
# DUMMY DATA# sizen=100# featuresdata=np.random.rand(n, 20)
# numeric target variablenum_target=np.random.rand(n)
# array with variable on which to do a disjunct splitsplit_var=np.random.choice(["D", "E", "F", "G", "H", "I", "J", "K"],
size=n, replace=True)
# further numeric variables to stratify onnum_strat_vars=np.random.rand(n, 3)
# intrinsically bin target into 3 bins by equidistant# percentile boundariesbinned_target=binning(num_target, nbins=3)
# ... alternatively, a variable can be extrinsically binned by# specifying lower boundaries:# binned_target = binning(num_target, lower_boundaries=[0, 0.33, 0.66])# bin other stratification variables into a single variable with 6 bins# (2-dim input is binned by StandardScaling and KMeans clustering)binned_strat_var=binning(num_strat_vars, nbins=6)
# ... alternatively, each stratification variable could be binned# individually - intrinsically or extrinsically the same way as num_target# strat_var1 = binning(num_strat_vars[:,0], nbins=...) etc.# now add the obtained categorical variable to stratification dictstratif_vars= {
"target": binned_target,
"strat_var": binned_strat_var
}
# ARGUMENTS# weight importance of all stratification variables in stratify_in# as well as of "size_diff", which punishes the deviation of intended# and received partition sizesweights= {
"target": 2,
"strat_var": 1,
"size_diff": 1
}
# dev and test partition proportion (from 0 to 1)dev_size=.1test_size=.1# number of disjunct splits to be tried out in brute force optimizationk=30# FIND OPTIMAL SPLITtrain_i, dev_i, test_i, info=optimize_traindevtest_split(
X=data,
y=num_target,
split_on=split_var,
stratify_on=stratif_vars,
weight=weights,
dev_size=dev_size,
test_size=test_size,
k=k,
seed=seed
)
# SOME OUTPUTprint("test levels of split_var:", sorted(set(split_var[test_i])))
print("goodness of split:", info)
  • find optimal train, dev, and test set split based on:
    • disjunct split of a categorical grouping variable G (e.g. speaker)
    • optimized joint stratification on an arbitrary amount of categorical target and grouping variables (e.g. emotion, gender, ...)
    • close match of partition proportions in G and underlying dataset X
  • brute-force optimization on k disjunct splits of G
  • score to be minimzed for train/test set split:
(sum_v[w(v) * irad(v)] + w(d) * d) / (sum_v[w(v)] + w(d))
v: variables to be stratified on
w(v): their weight
irad(v): information radius between reference and test set distribution of factor levels in v
d: absolute difference between test proportions of X and G, i.e. between the proportion of test
samples and the proportion of groups (e.g. speakers) that go into the test set
w(d): its weight
  • score to be minimzed for train / dev / test set split:
(sum_v[w(v) * max_irad(v)] + w(d) * max_d) / (sum_v[w(v)] + w(d))
v: variables to be stratified on
w(v): their weight
max_irad(v): maximum information radius of reference distribution of classes in v and
- dev set distribution,
- test set distribution
max_d: maximum of absolute difference between proportions of X and G (see above) calculated for
the dev and test set
w(d): its weight
  • let's look at Example 2 above. There info becomes:
{
'score': 0.030828359568603338,
'size_devset_in_spliton': 0.1,
'size_devset_in_X': 0.14,
'size_testset_in_spliton': 0.1,
'size_testset_in_X': 0.13,
'p_target_ref': {'B': 0.49, 'A': 0.51},
'p_target_dev': {'A': 0.5, 'B': 0.5},
'p_target_test': {'A': 0.5384615384615384, 'B': 0.46153846153846156},
'p_strat_var1_ref': {'G': 0.56, 'F': 0.44},
'p_strat_var1_dev': {'G': 0.5714285714285714, 'F': 0.42857142857142855},
'p_strat_var1_test': {'F': 0.5384615384615384, 'G': 0.46153846153846156},
'p_strat_var2_ref': {'I': 0.48, 'H': 0.52},
'p_strat_var2_dev': {'I': 0.5, 'H': 0.5},
'p_strat_var2_test': {'I': 0.46153846153846156, 'H': 0.5384615384615384}
}
  • Explanations
    • score: see above, score to be minimzed for train / dev / test set split:
    • size_devset_in_spliton: proportion of to-be-split-on variable levels in development set
    • size_devset_in_X: proportion of rows in X in development set
    • size_testset_in_spliton: proportion of to-be-split-on variable levels in test set
    • size_testset_in_X: proportion of rows in X in test set
    • p_target_ref: reference target class distribution over all data
    • p_target_dev: target class distribution in development set
    • p_target_test: target class distribution in test set
    • p_strat_var1_ref: first stratification variable's reference distribution over all data
    • p_strat_var1_dev: first stratification variable's class distribution in development set
    • p_strat_var1_test: first stratification variable's class distribution in test set
    • p_strat_var2_ref: second stratification variable's reference distribution over all data
    • p_strat_var2_dev: second stratification variable's class distribution in development set
    • p_strat_var2_test: second stratification variable's class distribution in test set
  • Remarks
    • for splitutils.optimize_traintest_split() no development set results are reported
    • all *_strat_var* keys: key names derived from key names in stratify_on argument

About

machine learning data partitioning tool that allows for group-disjunct splits and stratification on multiple target and grouping variables

Resources

Stars

1 star

Watchers

1 watching

Forks

Releases

Packages

Used by

Contributors

Languages