使用scikit-learn/XGBoost作为MICE模型时fancyimpute报TypeError求助
Hey there, I’ve run into this exact issue before! The problem here is how you’re passing the model to MICE — you’re giving it an already-instantiated object (like RandomForestRegressor()), but fancyimpute expects you to pass the model class itself instead.
Why this happens
Under the hood, MICE creates multiple instances of your model (one for each feature with missing values) and manages initialization parameters internally. When you pass a pre-made instance, it tries to reuse it in ways that break the expected interface, leading directly to that TypeError.
The Fix
Instead of passing RandomForestRegressor() (with parentheses), pass just RandomForestRegressor (the class reference). The same rule applies to XGBoost’s XGBRegressor — pass the class, not an instance.
Here’s your corrected code:
from fancyimpute import MICE from sklearn.ensemble import RandomForestRegressor import pandas as pd # Pass the model CLASS, not an instantiated object mice = MICE(n_imputations=1, verbose=False, model=RandomForestRegressor) df = pd.DataFrame(data=mice.complete(d), columns=d.columns, index=d.index)
For XGBoost Users
If you want to use XGBoost instead, the approach is identical — make sure to pass the XGBRegressor class (from the xgboost library) without instantiating it first:
from xgboost import XGBRegressor mice = MICE(n_imputations=1, verbose=False, model=XGBRegressor) df = pd.DataFrame(data=mice.complete(d), columns=d.columns, index=d.index)
Bonus: Customizing Model Parameters
If you want to set specific hyperparameters for your model (like n_estimators for RandomForest), use the model_kwargs parameter in MICE to pass them in:
mice = MICE( n_imputations=1, verbose=False, model=RandomForestRegressor, model_kwargs={"n_estimators": 200, "random_state": 42} )
That should resolve the TypeError you’re seeing. Let me know if you hit any other snags!
内容的提问来源于stack exchange,提问作者NicolasWoloszko

