Skip to content

Unclear rules and behaviors for dtypes in estimators with partial_fit #35532

Backlog

Description

@david-cortes-intel

Warning

This issue is not yet ready for a PR. If you are interested in contributing to scikit-learn, please have a look at our contributing guidelines, and in particular the sections for new contributors and the "Needs triage" label.

Introduce yourself

No response

Describe the bug and give evidence about its user-facing impact

There do not appear to be rules about how things work when the dtypes (e.g. float32/float64) passed to estimators with methods like partial_fit or argument warm_start are supposed to work, and different estimators show different behavior.

For instance:

  • SGDRegressor will error out if the dtypes of attributes do not match with the dtype of the new 'X':
import numpy as np
rng = np.random.default_rng(seed=123)
X = rng.standard_normal(size=(20,3))
y = rng.standard_normal(size=X.shape[0])

from sklearn.linear_model import SGDRegressor
model = SGDRegressor().fit(X[:10].astype(np.float32), y[:10].astype(np.float32))
model.partial_fit(X[10:], y[10:])
TypeError: Argument 'dataset' has incorrect type (expected sklearn.utils._seq_dataset.SequentialDataset32, got sklearn.utils._seq_dataset.ArrayDataset64)
  • LogisticRegression(warm_start=True) will keep the dtype of the last 'X' passed to .fit() (I think this one is an unambiguously correct behavior regardless of the rest).

  • IncrementalPCA will upcast the dtype whenever it sees a float64:

import numpy as np
rng = np.random.default_rng(seed=123)
X = rng.standard_normal(size=(20,3))

from sklearn.decomposition import IncrementalPCA
model1 = IncrementalPCA().fit(X[:10].astype(np.float32))
model1.partial_fit(X[10:])
print(model1.singular_values_.dtype)

model2 = IncrementalPCA().fit(X[:10])
model2.partial_fit(X[10:].astype(np.float32))
print(model2.singular_values_.dtype)
float64
float64
  • Most estimators will upcast dtypes when the 'X' passed to methods like .predict() or .transform() differs from the attributes, but MaxAbsScaler follows the dtype of the input instead:
import numpy as np
rng = np.random.default_rng(seed=123)
X = rng.standard_normal(size=(20,3))

from sklearn.preprocessing import MaxAbsScaler
scaler = MaxAbsScaler().fit(X)
print(scaler.scale_.dtype)
print(scaler.transform(X[:5].astype(np.float32)).dtype)
float64
float32
  • In the same line, LogisticRegression follows this upcast-on-predict behavior with NumPy namespaces, but under array API, it errors out if the dtypes do not match, and will follow a different logic after Store all fitted attributes as Numpy arrays #35053 where the dtype of the prediction will follow 'X' under array API but will still upcast under NumPy.

  • IncrementalPCA will use float64 for some methods regardless of the dtype the attributes have:

import numpy as np
rng = np.random.default_rng(seed=123)
X = rng.standard_normal(size=(20,3))

from sklearn.decomposition import IncrementalPCA
model = IncrementalPCA().fit(X[:10].astype(np.float32))
print(model.singular_values_.dtype)
print(model.get_covariance().dtype)
float32
float64

Steps/Code to Reproduce

Examples given above.

Expected Results

Code examples given above should be consistent across estimators.

Actual Results

There's differences across estimators.

Versions

Not relevant.

Interest in fixing the bug

No.

Activity

  1. Kaynup commented on Nov 27, 2026

    @Kaynup
    Contributor

    Hello @david-cortes-intel

    I ran an empirical audit with antigravity across all 24 non-meta estimators with partial_fit, the 5 meta-estimators with partial_fit, sparse CSR paths, and all 33 estimators with warm_start=True in main to map out their behaviours.


    i. partial_fit across all 24 non-meta estimators (float32 to float64)

    Behavior Estimators Details
    Crashes with dtype error SGDClassifier, SGDRegressor, SGDOneClassSVM, PassiveAggressiveClassifier, PassiveAggressiveRegressor, Perceptron, MiniBatchKMeans SGD/PA/Perceptron raise TypeError (SequentialDataset32 vs ArrayDataset64). MiniBatchKMeans raises ValueError: Buffer dtype mismatch in _mini_batch_step (both dense & sparse CSR).
    Keeps 1st batch's dtype Birch, LatentDirichletAllocation, MiniBatchDictionaryLearning, MiniBatchNMF, MLPClassifier, MLPRegressor Fitted attributes (subcluster_centers_, components_, coefs_) stay float32 on f32 -> f64 and float64 on f64 -> f32. (In MLPRegressor, best_loss_ stays float32 while loss_ switches to float64.)
    Upcasts whenever float64 is seen IncrementalPCA, MinMaxScaler, MaxAbsScaler Attributes stay float32 on f32 only, promote to float64 on f32 -> f64, and remain float64 on f64 -> f32.
    Mixed attribute dtypes (partial overwrite) GaussianNB theta_, var_, class_count_, class_prior_ keep the 1st call's dtype, but epsilon_ flips to match the latest batch (self.var_smoothing * xp.max(xp.var(X, axis=0))).
    Always stores float64 internally StandardScaler, BernoulliNB, MultinomialNB, ComplementNB, CategoricalNB, BernoulliRBM All float fitted attributes are float64 even when fitted solely on float32 (under NumPy).

    (Meta-estimators OneVsRestClassifier, OneVsOneClassifier, MultiOutputClassifier, MultiOutputRegressor, and SelectFromModel inherit whatever their wrapped estimator does, e.g. all crash when wrapping SGD* on f32 -> f64, while OneVsRestClassifier(GaussianNB) succeeds. HashingVectorizer is stateless with no float attributes.)


    ii. warm_start=True across all 33 estimators (fit(f32) $\to$ fit(f64) and vice versa)

    Even within warm_start=True (which you noted LogisticRegression handles cleanly), estimators diverge sharply:

    • Follows latest fit() dtype cleanly: LogisticRegression, Lasso, ElasticNet, TweedieRegressor, PoissonRegressor, GammaRegressor, and SGDClassifier / PassiveAggressiveClassifier / Perceptron / SGDOneClassSVM (though the latter four keep intercept_/offset_ in float64).
    • Crashes with dtype mismatch:
      • SGDRegressor(warm_start=True) & PassiveAggressiveRegressor(warm_start=True): raise TypeError (SequentialDataset32 vs ArrayDataset64) on f32 -> f64, unlike SGDClassifier(warm_start=True) which succeeds!
      • MultiTaskLasso(warm_start=True) & MultiTaskElasticNet(warm_start=True): raise ValueError: Buffer dtype mismatch on both f32 -> f64 and f64 -> f32, unlike single-task Lasso / ElasticNet!
    • Keeps 1st fit() dtype: MLPClassifier, MLPRegressor (coefs_/intercepts_ stay in 1st dtype).
    • Mixed / split attribute dtypes after fit(f64) $\to$ fit(f32):
      • GaussianMixture(warm_start=True): weights_, means_, lower_bound_ stay float64, while covariances_, precisions_cholesky_, precisions_ flip to float32.
      • BayesianGaussianMixture(warm_start=True): mean_prior_ flips to float32 while means_, covariances_, etc. stay float64.

    ii. Reproducers for a few Edge Cases

    1. MiniBatchKMeans crashes both on partial_fit AND on predict with mixed dtypes (while transform silently upcasts):

      import numpy as np
      from sklearn.cluster import MiniBatchKMeans
      
      rng = np.random.default_rng(123)
      X = rng.standard_normal((20, 3))
      
      km = MiniBatchKMeans(n_clusters=2, n_init=1, random_state=0).partial_fit(X[:10].astype(np.float32))
      km.partial_fit(X[10:])  # ValueError: Buffer dtype mismatch, expected 'const float' but got 'double'
      km.predict(X[10:])      # ValueError: Buffer dtype mismatch, expected 'const float' but got 'double'
    2. GaussianNB splits theta_/var_ and epsilon_ across dtypes; GaussianMixture(warm_start=True) splits means_ and covariances_:

      from sklearn.mixture import GaussianMixture
      from sklearn.naive_bayes import GaussianNB
      
      gnb = GaussianNB().partial_fit(X[:10].astype(np.float32), np.array([0, 1] * 5), classes=[0, 1])
      gnb.partial_fit(X[10:], np.array([0, 1] * 5))
      print(gnb.theta_.dtype, gnb.epsilon_.dtype)  # float32 float64
      
      gmm = GaussianMixture(warm_start=True, max_iter=2, random_state=0).fit(X)
      gmm.fit(X.astype(np.float32))
      print(gmm.means_.dtype, gmm.covariances_.dtype)  # float64 float32
    3. SGD* / PassiveAggressive* / Perceptron allocate coef_ in float32 but intercept_ in float64, so even fit(f32).predict(f32) returns float64 (and SGDRegressor(warm_start=True) crashes while SGDClassifier(warm_start=True) does not):

      from sklearn.linear_model import SGDRegressor
      
      sgd = SGDRegressor().partial_fit(X[:10].astype(np.float32), rng.standard_normal(10).astype(np.float32))
      print(sgd.coef_.dtype, sgd.intercept_.dtype)         # float32 float64
      print(sgd.predict(X[10:].astype(np.float32)).dtype)  # float64
    4. Mixed fit vs transform/predict behavior splits across estimators:

      • fit(f64).transform(f32) $\to$ float32: StandardScaler, MinMaxScaler, MaxAbsScaler, MiniBatchDictionaryLearning, MiniBatchNMF.
      • fit(f64).transform/predict_proba(f32) $\to$ float64: IncrementalPCA, Birch, MiniBatchKMeans.transform, GaussianNB, MLPClassifier, MLPRegressor, BernoulliRBM, *NB.
      • fit(f32).transform(f64) $\to$ float32 (follows attribute dtype, not X): LatentDirichletAllocation.

    I hope this helps.

    I have missed some auditing locally for these two however:

    1. Array API backends (array_api_dispatch=True): array_api_strict, torch, cupy, and jax (If you want I can try putting them up).
    2. Cross-argument mismatches within a single call: like, X in float32 while sample_weight or y is in float64, or DataFrame/categorical mixed dtypes.

    I have attached my audit script for reference:

    audit_partial_fit_and_warm_start_dtypes.py

    audit_output.log

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

    BugNeeds Triage

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions