Skip to content

Add missing values and categorical features when generating datasets #28952

Open

Description

@lcrmorin

Describe the workflow you want to enable

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.

Activity

  1. oasidorshin commented on May 6, 2024

    @oasidorshin

    @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

  2. AK3847 commented on May 6, 2024

    @AK3847

    @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?

  3. glemaitre commented on May 14, 2024

    @glemaitre
    Member

    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)

  4. removed
    Needs Triage
    on May 14, 2024
  5. glemaitre commented on May 16, 2024

    @glemaitre
    Member

    Regarding the categorical features, we have the following related issue: #12433

  6. changed the title [-]Improve random datasets [/-] [+]Add missing values and categorical features when generating datasets[/+] on May 16, 2024
  7. IppotisTheKing commented on Oct 24, 2024

    @IppotisTheKing

    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.

  8. kaekkr commented on Apr 10, 2025

    @kaekkr

    I will try to work on it!

  9. added
    Moderate
    on Apr 18, 2025
  10. lcrmorin commented on Aug 24, 2026

    @lcrmorin
    Author

    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.

  11. lcrmorin commented on Aug 24, 2026

    @lcrmorin
    Author

    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)

    def make_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.shape
        mask = np.zeros_like(X, dtype=bool)
    
        # --- MCAR: uniform random cells, independent of X ---
        if mcar_rate > 0:
            mask |= rng.random(X.shape) < mcar_rate
    
        # --- MAR: PROBABILITY of missingness depends on other observed features ---
        if mar_rate > 0:
            if weights is not None:
                mar_weights = weights                      # user-supplied, deterministic
            else:
                mar_weights = _random_sparse_weights(       # random, like make_classification
                    n_features, n_informative, rng)
            score = X @ mar_weights                         # raw weighted-sum score per row
            shift = _calibrate_shift(score, target_rate=mar_rate)  # binary search on the SHIFT,
                                                              # s.t. mean(expit(score + shift)) == mar_rate
            prob = expit(score + shift)                      # per-row probability, not a cutoff
            mask |= rng.random(n_samples) < prob             # stochastic Bernoulli draw
    
        # --- MNAR: same idea, but the score comes from the feature's own value ---
        if mnar_rate > 0:
            for j in range(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_j
    
        X_missing = X.copy()
        X_missing[mask] = missing_values
        return X_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.

    Tests (sklearn/datasets/tests/test_missing_values.py)

    • data format
    • realized MCAR/MAR/MNAR fractions match mcar_rate/mar_rate/mnar_rate within tolerance
    • MAR/MNAR missingness actually correlates with the informative features / own value respectively, both for random and user-supplied weights
    • random_state reproducibility
    • edge cases: all-zero rates, rates summing to 1, n_informative larger than X.shape[1], sparse-input rejection

    Docs

    • "Generating missing values" subsection in doc/datasets.rst, drawing the make_classification parallel explicitly
    • cross-reference from doc/modules/impute.rst
    • examples/impute/plot_ampute_missing_values.py: vary the three rates and weights, compare SimpleImputer vs IterativeImputer reconstruction error ?
    • changelog fragment under doc/whats_new/upcoming_changes/sklearn.datasets/ ?

    References

  12. Benlite777 commented on Aug 27, 2026

    @Benlite777

    /take

  13. Benlite777 commented on Aug 27, 2026

    @Benlite777

    Apologies, I didn't notice that @lcrmorin is already actively working on this with a detailed design proposal. /untake

  14. adam2392 commented on Sep 1, 2026

    @adam2392
    Member

    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.

  15. lcrmorin commented on Sep 20, 2026

    @lcrmorin
    Author

    @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).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    ModerateNew Feature

    Type

    No type

    Projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions