OneHotEncoder.init() got an unexpected keyword argument 'sparse'
- User
OneHotEncoder.init() got an unexpected keyword argument 'sparse'
- Assistant
The error message:
codeOneHotEncoder.__init__() got an unexpected keyword argument 'sparse'typically occurs because of a version mismatch or change in the
sklearn.preprocessing.OneHotEncoderAPI.What's going on?
In versions of scikit-learn prior to v1.2,
OneHotEncoderhad asparseparameter to control whether the output is a sparse matrix or a dense NumPy array:pythonOneHotEncoder(sparse=True)From scikit-learn v1.2 and onwards, the
sparseparameter was deprecated and replaced by thesparse_outputparameter. So the correct argument in newer versions is:pythonOneHotEncoder(sparse_output=True)If you use
sparse=...with scikit-learn 1.2+, you will get the error you described.
How to fix it?
- Check your scikit-learn version:
pythonimport sklearn print(sklearn.__version__)- If scikit-learn >= 1.2, replace:
pythonOneHotEncoder(sparse=True)with
pythonOneHotEncoder(sparse_output=True)- If you are using an older scikit-learn (<1.2), keep using:
pythonOneHotEncoder(sparse=True)
Example
For scikit-learn < 1.2
pythonfrom sklearn.preprocessing import OneHotEncoder encoder = OneHotEncoder(sparse=True) X_transformed = encoder.fit_transform(X)For scikit-learn >= 1.2
pythonfrom sklearn.preprocessing import OneHotEncoder encoder = OneHotEncoder(sparse_output=True) X_transformed = encoder.fit_transform(X)