You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Add missing values and categorical features when generating datasets #28952
I am often using random datasets (typically with make_classification). However I often find myself having to add more realistic features to the dataset:
missing data, sometime just to test the pipeline (missing at random would be fine), or sometimes to look for more complex phenomenons (missingnes not at random, possibly depending on the target)
categorical: categoricals variables often need to be handled specifically. I usually introduce categoricals with binning a continuous value, then transforming to strings.
It would be nice to have both of those in datasets generation.
Describe your proposed solution
Introduce parameters to allow for generation of missing data (proportion of missingness, type of missingness - at random, not at random).
Introduce parameters to allow for generation of categorical features (number of features, type of repartition in categories - even - uneven - pareto.
Describe alternatives you've considered, if relevant
I usually handle this by hand.
Additional context
Could be used to illustrate imputing techniques, encoding techniques.
@lcrmorin This would be great for testing! I would also suggest adding infinities as possible values, bcs they also break stuff quite often. Also, if randomly generated, making sure to always include at least one NaN and inf value
@lcrmorin I suggest adding a noise function or something similar which can generate structured randomness so as to make some sense in data and not pseudo-randomness. Perhaps something like Perlin Noise?
Regarding the missing values I recall the following issues/PRs: #6284 / #7084. It seems that the consensus was to have something similar to the ampute R package.
I almost a similar discussion for categorical features but I could not find. For sure, it would be handy to have those two parameters even though we could limit the complexity (e.g. only have a single missingness pattern)
I might be interested in taking it this week. I have a bit of time on my hand. I'll start with a generic ampute function, possibly with different strategies, then I'll see how we can add it to data generating functions.
Keep in mind this is a proposal, flagging the open questions inline and at the end.
Public API (proposed)
defmake_missing_values(X, y=None, *, mcar_rate=0.0, mar_rate=0.05, mnar_rate=0.05,
n_informative=None, weights=None, missing_values=np.nan,
random_state=None):
rng=check_random_state(random_state)
n_samples, n_features=X.shapemask=np.zeros_like(X, dtype=bool)
# --- MCAR: uniform random cells, independent of X ---ifmcar_rate>0:
mask|=rng.random(X.shape) <mcar_rate# --- MAR: PROBABILITY of missingness depends on other observed features ---ifmar_rate>0:
ifweightsisnotNone:
mar_weights=weights# user-supplied, deterministicelse:
mar_weights=_random_sparse_weights( # random, like make_classificationn_features, n_informative, rng)
score=X @ mar_weights# raw weighted-sum score per rowshift=_calibrate_shift(score, target_rate=mar_rate) # binary search on the SHIFT,# s.t. mean(expit(score + shift)) == mar_rateprob=expit(score+shift) # per-row probability, not a cutoffmask|=rng.random(n_samples) <prob# stochastic Bernoulli draw# --- MNAR: same idea, but the score comes from the feature's own value ---ifmnar_rate>0:
forjinrange(n_features):
score_j=_standardize(X[:, j])
shift_j=_calibrate_shift(score_j, target_rate=mnar_rate)
prob_j=expit(score_j+shift_j)
mask[:, j] |=rng.random(n_samples) <prob_jX_missing=X.copy()
X_missing[mask] =missing_valuesreturnX_missing
One rate per mechanism instead of a single mechanism= switch:
MAR fraction: score each cell from a combination of other, observed features, threshold to hit mar_rate — same shape as generating y from n_informative features.
MNAR fraction: same mechanism, but the score comes from the feature's own (about-to-be-missing) value.
MCAR fraction: cells chosen uniformly at random, independent of X — the missingness equivalent of flip_y's label noise.
The main topic of discussion here would be:
difference between continuous and categorical variable
missing values for y ?
to check wether they properly compose. e.g. if setting 5% for both MAR and MNAR should give 10% overall... it would be a tradeoff between simplicity and expected value...
use user-defined weights if possible
Module location
sklearn/datasets/_missing_values.py, re-exported from sklearn/datasets/__init__.py as make_missing_values. Not sklearn.impute (opposite direction: removes values rather than filling them); kept out of _samples_generator.py to keep the diff isolated.
Handling missingness in its full generality is hard unless it's MCAR, because MAR and MNAR can have different functional relationships that result in the missingness, but I think a simple approach can be sufficient to start. We should just make it clear in the docstring how the missingness is generated.
@adam2392 I’ve made progress on a local implementation of make_missing_values in a separate datasets module, with MCAR, MAR, and MNAR mechanisms, documentation, and examples.
The current draft uses additive expected rates: 10% MCAR + 20% MAR + 10% MNAR gives 40% missing entries on average among eligible columns. Each cell can be removed by only one mechanism, and the rates must sum to at most 1.
The main design question is MAR. The draft requires explicit observed_features, which remain observed under every mechanism and drive MAR probabilities through a weighted score. Rates exclude those protected columns, meaning, in the exemple above that we have 20% MAR on non observed features... but not on observed features. So we have the correct 40% total on some feature but not 'observed' ones. Supporting missingness in every column while retaining MAR would require a more flexible pattern-based design... Would this simpler approach be an acceptable starting point?
The updated implementation also add 85 focused tests (which all pass) and 14 documentation examples. Most of these were AI generated.
Since I already have an open PR, I cannot make a new one for this issue. What would be best course of action to proceed ?
Also I am wondering if it would make sense to add some option to have other stuff added than nan (e.g. +/- infinity).
Activity
oasidorshin commentedon May 6, 2024
@lcrmorin This would be great for testing! I would also suggest adding infinities as possible values, bcs they also break stuff quite often. Also, if randomly generated, making sure to always include at least one NaN and inf value
AK3847 commentedon May 6, 2024
@lcrmorin I suggest adding a noise function or something similar which can generate structured randomness so as to make some sense in data and not pseudo-randomness. Perhaps something like Perlin Noise?
glemaitre commentedon May 14, 2024
Regarding the missing values I recall the following issues/PRs: #6284 / #7084. It seems that the consensus was to have something similar to the
amputeR package.I almost a similar discussion for categorical features but I could not find. For sure, it would be handy to have those two parameters even though we could limit the complexity (e.g. only have a single missingness pattern)
glemaitre commentedon May 16, 2024
Regarding the categorical features, we have the following related issue: #12433
[-]Improve random datasets [/-][+]Add missing values and categorical features when generating datasets[/+]IppotisTheKing commentedon Oct 24, 2024
I will take a look on it and try to implement this feature in my side by exploring different possibilities to incorporate NaN and inf values.
kaekkr commentedon Apr 10, 2025
I will try to work on it!
lcrmorin commentedon Aug 24, 2026
I might be interested in taking it this week. I have a bit of time on my hand. I'll start with a generic ampute function, possibly with different strategies, then I'll see how we can add it to data generating functions.
lcrmorin commentedon Aug 24, 2026
After a bit of thinking (and looking at proposed architecture in previous issues) I am sketching a simple architecture. In a sense it quite match the
[make_classification](https://github.com/scikit-learn/scikit-learn/blob/main/sklearn/datasets/_samples_generator.py)design as we are trying to classify wether a value is missing. The approach would be simpler than the algorithm proposed by Schoutten in previous discussions. Also worth a mention is the package pyampute, that I haven't checked yet, but I feel like we want to have something proper in scikit learn.Keep in mind this is a proposal, flagging the open questions inline and at the end.
Public API (proposed)
One rate per mechanism instead of a single
mechanism=switch:mar_rate— same shape as generatingyfromn_informativefeatures.X— the missingness equivalent offlip_y's label noise.The main topic of discussion here would be:
Module location
sklearn/datasets/_missing_values.py, re-exported fromsklearn/datasets/__init__.pyasmake_missing_values. Notsklearn.impute(opposite direction: removes values rather than filling them); kept out of_samples_generator.pyto keep the diff isolated.Tests (
sklearn/datasets/tests/test_missing_values.py)mcar_rate/mar_rate/mnar_ratewithin toleranceweightsrandom_statereproducibilityn_informativelarger thanX.shape[1], sparse-input rejectionDocs
doc/datasets.rst, drawing themake_classificationparallel explicitlydoc/modules/impute.rstexamples/impute/plot_ampute_missing_values.py: vary the three rates andweights, compareSimpleImputervsIterativeImputerreconstruction error ?doc/whats_new/upcoming_changes/sklearn.datasets/?References
[pyampute](https://github.com/RianneSchouten/pyampute)— Rianne Schouten's existing standalone package implementingMultivariateAmputation; worth deciding explicitly whether this PR ports/wraps that code or reimplements independentlyBenlite777 commentedon Aug 27, 2026
/take
Benlite777 commentedon Aug 27, 2026
Apologies, I didn't notice that @lcrmorin is already actively working on this with a detailed design proposal. /untake
adam2392 commentedon Sep 1, 2026
I'm excited to review this!
Handling missingness in its full generality is hard unless it's MCAR, because MAR and MNAR can have different functional relationships that result in the missingness, but I think a simple approach can be sufficient to start. We should just make it clear in the docstring how the missingness is generated.
lcrmorin commentedon Sep 20, 2026
@adam2392 I’ve made progress on a local implementation of
make_missing_valuesin a separate datasets module, with MCAR, MAR, and MNAR mechanisms, documentation, and examples.The current draft uses additive expected rates: 10% MCAR + 20% MAR + 10% MNAR gives 40% missing entries on average among eligible columns. Each cell can be removed by only one mechanism, and the rates must sum to at most 1.
The main design question is MAR. The draft requires explicit
observed_features, which remain observed under every mechanism and drive MAR probabilities through a weighted score. Rates exclude those protected columns, meaning, in the exemple above that we have 20% MAR on non observed features... but not on observed features. So we have the correct 40% total on some feature but not 'observed' ones. Supporting missingness in every column while retaining MAR would require a more flexible pattern-based design... Would this simpler approach be an acceptable starting point?The updated implementation also add 85 focused tests (which all pass) and 14 documentation examples. Most of these were AI generated.
Since I already have an open PR, I cannot make a new one for this issue. What would be best course of action to proceed ?
Also I am wondering if it would make sense to add some option to have other stuff added than nan (e.g. +/- infinity).