_base.py 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056
  1. # Authors: Nicolas Tresegnie <nicolas.tresegnie@gmail.com>
  2. # Sergey Feldman <sergeyfeldman@gmail.com>
  3. # License: BSD 3 clause
  4. import numbers
  5. import warnings
  6. from collections import Counter
  7. import numpy as np
  8. import numpy.ma as ma
  9. from scipy import sparse as sp
  10. from ..base import BaseEstimator, TransformerMixin, _fit_context
  11. from ..utils import _is_pandas_na, is_scalar_nan
  12. from ..utils._mask import _get_mask
  13. from ..utils._param_validation import MissingValues, StrOptions
  14. from ..utils.fixes import _mode
  15. from ..utils.sparsefuncs import _get_median
  16. from ..utils.validation import FLOAT_DTYPES, _check_feature_names_in, check_is_fitted
  17. def _check_inputs_dtype(X, missing_values):
  18. if _is_pandas_na(missing_values):
  19. # Allow using `pd.NA` as missing values to impute numerical arrays.
  20. return
  21. if X.dtype.kind in ("f", "i", "u") and not isinstance(missing_values, numbers.Real):
  22. raise ValueError(
  23. "'X' and 'missing_values' types are expected to be"
  24. " both numerical. Got X.dtype={} and "
  25. " type(missing_values)={}.".format(X.dtype, type(missing_values))
  26. )
  27. def _most_frequent(array, extra_value, n_repeat):
  28. """Compute the most frequent value in a 1d array extended with
  29. [extra_value] * n_repeat, where extra_value is assumed to be not part
  30. of the array."""
  31. # Compute the most frequent value in array only
  32. if array.size > 0:
  33. if array.dtype == object:
  34. # scipy.stats.mode is slow with object dtype array.
  35. # Python Counter is more efficient
  36. counter = Counter(array)
  37. most_frequent_count = counter.most_common(1)[0][1]
  38. # tie breaking similarly to scipy.stats.mode
  39. most_frequent_value = min(
  40. value
  41. for value, count in counter.items()
  42. if count == most_frequent_count
  43. )
  44. else:
  45. mode = _mode(array)
  46. most_frequent_value = mode[0][0]
  47. most_frequent_count = mode[1][0]
  48. else:
  49. most_frequent_value = 0
  50. most_frequent_count = 0
  51. # Compare to array + [extra_value] * n_repeat
  52. if most_frequent_count == 0 and n_repeat == 0:
  53. return np.nan
  54. elif most_frequent_count < n_repeat:
  55. return extra_value
  56. elif most_frequent_count > n_repeat:
  57. return most_frequent_value
  58. elif most_frequent_count == n_repeat:
  59. # tie breaking similarly to scipy.stats.mode
  60. return min(most_frequent_value, extra_value)
  61. class _BaseImputer(TransformerMixin, BaseEstimator):
  62. """Base class for all imputers.
  63. It adds automatically support for `add_indicator`.
  64. """
  65. _parameter_constraints: dict = {
  66. "missing_values": [MissingValues()],
  67. "add_indicator": ["boolean"],
  68. "keep_empty_features": ["boolean"],
  69. }
  70. def __init__(
  71. self, *, missing_values=np.nan, add_indicator=False, keep_empty_features=False
  72. ):
  73. self.missing_values = missing_values
  74. self.add_indicator = add_indicator
  75. self.keep_empty_features = keep_empty_features
  76. def _fit_indicator(self, X):
  77. """Fit a MissingIndicator."""
  78. if self.add_indicator:
  79. self.indicator_ = MissingIndicator(
  80. missing_values=self.missing_values, error_on_new=False
  81. )
  82. self.indicator_._fit(X, precomputed=True)
  83. else:
  84. self.indicator_ = None
  85. def _transform_indicator(self, X):
  86. """Compute the indicator mask.'
  87. Note that X must be the original data as passed to the imputer before
  88. any imputation, since imputation may be done inplace in some cases.
  89. """
  90. if self.add_indicator:
  91. if not hasattr(self, "indicator_"):
  92. raise ValueError(
  93. "Make sure to call _fit_indicator before _transform_indicator"
  94. )
  95. return self.indicator_.transform(X)
  96. def _concatenate_indicator(self, X_imputed, X_indicator):
  97. """Concatenate indicator mask with the imputed data."""
  98. if not self.add_indicator:
  99. return X_imputed
  100. hstack = sp.hstack if sp.issparse(X_imputed) else np.hstack
  101. if X_indicator is None:
  102. raise ValueError(
  103. "Data from the missing indicator are not provided. Call "
  104. "_fit_indicator and _transform_indicator in the imputer "
  105. "implementation."
  106. )
  107. return hstack((X_imputed, X_indicator))
  108. def _concatenate_indicator_feature_names_out(self, names, input_features):
  109. if not self.add_indicator:
  110. return names
  111. indicator_names = self.indicator_.get_feature_names_out(input_features)
  112. return np.concatenate([names, indicator_names])
  113. def _more_tags(self):
  114. return {"allow_nan": is_scalar_nan(self.missing_values)}
  115. class SimpleImputer(_BaseImputer):
  116. """Univariate imputer for completing missing values with simple strategies.
  117. Replace missing values using a descriptive statistic (e.g. mean, median, or
  118. most frequent) along each column, or using a constant value.
  119. Read more in the :ref:`User Guide <impute>`.
  120. .. versionadded:: 0.20
  121. `SimpleImputer` replaces the previous `sklearn.preprocessing.Imputer`
  122. estimator which is now removed.
  123. Parameters
  124. ----------
  125. missing_values : int, float, str, np.nan, None or pandas.NA, default=np.nan
  126. The placeholder for the missing values. All occurrences of
  127. `missing_values` will be imputed. For pandas' dataframes with
  128. nullable integer dtypes with missing values, `missing_values`
  129. can be set to either `np.nan` or `pd.NA`.
  130. strategy : str, default='mean'
  131. The imputation strategy.
  132. - If "mean", then replace missing values using the mean along
  133. each column. Can only be used with numeric data.
  134. - If "median", then replace missing values using the median along
  135. each column. Can only be used with numeric data.
  136. - If "most_frequent", then replace missing using the most frequent
  137. value along each column. Can be used with strings or numeric data.
  138. If there is more than one such value, only the smallest is returned.
  139. - If "constant", then replace missing values with fill_value. Can be
  140. used with strings or numeric data.
  141. .. versionadded:: 0.20
  142. strategy="constant" for fixed value imputation.
  143. fill_value : str or numerical value, default=None
  144. When strategy == "constant", `fill_value` is used to replace all
  145. occurrences of missing_values. For string or object data types,
  146. `fill_value` must be a string.
  147. If `None`, `fill_value` will be 0 when imputing numerical
  148. data and "missing_value" for strings or object data types.
  149. copy : bool, default=True
  150. If True, a copy of X will be created. If False, imputation will
  151. be done in-place whenever possible. Note that, in the following cases,
  152. a new copy will always be made, even if `copy=False`:
  153. - If `X` is not an array of floating values;
  154. - If `X` is encoded as a CSR matrix;
  155. - If `add_indicator=True`.
  156. add_indicator : bool, default=False
  157. If True, a :class:`MissingIndicator` transform will stack onto output
  158. of the imputer's transform. This allows a predictive estimator
  159. to account for missingness despite imputation. If a feature has no
  160. missing values at fit/train time, the feature won't appear on
  161. the missing indicator even if there are missing values at
  162. transform/test time.
  163. keep_empty_features : bool, default=False
  164. If True, features that consist exclusively of missing values when
  165. `fit` is called are returned in results when `transform` is called.
  166. The imputed value is always `0` except when `strategy="constant"`
  167. in which case `fill_value` will be used instead.
  168. .. versionadded:: 1.2
  169. Attributes
  170. ----------
  171. statistics_ : array of shape (n_features,)
  172. The imputation fill value for each feature.
  173. Computing statistics can result in `np.nan` values.
  174. During :meth:`transform`, features corresponding to `np.nan`
  175. statistics will be discarded.
  176. indicator_ : :class:`~sklearn.impute.MissingIndicator`
  177. Indicator used to add binary indicators for missing values.
  178. `None` if `add_indicator=False`.
  179. n_features_in_ : int
  180. Number of features seen during :term:`fit`.
  181. .. versionadded:: 0.24
  182. feature_names_in_ : ndarray of shape (`n_features_in_`,)
  183. Names of features seen during :term:`fit`. Defined only when `X`
  184. has feature names that are all strings.
  185. .. versionadded:: 1.0
  186. See Also
  187. --------
  188. IterativeImputer : Multivariate imputer that estimates values to impute for
  189. each feature with missing values from all the others.
  190. KNNImputer : Multivariate imputer that estimates missing features using
  191. nearest samples.
  192. Notes
  193. -----
  194. Columns which only contained missing values at :meth:`fit` are discarded
  195. upon :meth:`transform` if strategy is not `"constant"`.
  196. In a prediction context, simple imputation usually performs poorly when
  197. associated with a weak learner. However, with a powerful learner, it can
  198. lead to as good or better performance than complex imputation such as
  199. :class:`~sklearn.impute.IterativeImputer` or :class:`~sklearn.impute.KNNImputer`.
  200. Examples
  201. --------
  202. >>> import numpy as np
  203. >>> from sklearn.impute import SimpleImputer
  204. >>> imp_mean = SimpleImputer(missing_values=np.nan, strategy='mean')
  205. >>> imp_mean.fit([[7, 2, 3], [4, np.nan, 6], [10, 5, 9]])
  206. SimpleImputer()
  207. >>> X = [[np.nan, 2, 3], [4, np.nan, 6], [10, np.nan, 9]]
  208. >>> print(imp_mean.transform(X))
  209. [[ 7. 2. 3. ]
  210. [ 4. 3.5 6. ]
  211. [10. 3.5 9. ]]
  212. For a more detailed example see
  213. :ref:`sphx_glr_auto_examples_impute_plot_missing_values.py`.
  214. """
  215. _parameter_constraints: dict = {
  216. **_BaseImputer._parameter_constraints,
  217. "strategy": [StrOptions({"mean", "median", "most_frequent", "constant"})],
  218. "fill_value": "no_validation", # any object is valid
  219. "copy": ["boolean"],
  220. }
  221. def __init__(
  222. self,
  223. *,
  224. missing_values=np.nan,
  225. strategy="mean",
  226. fill_value=None,
  227. copy=True,
  228. add_indicator=False,
  229. keep_empty_features=False,
  230. ):
  231. super().__init__(
  232. missing_values=missing_values,
  233. add_indicator=add_indicator,
  234. keep_empty_features=keep_empty_features,
  235. )
  236. self.strategy = strategy
  237. self.fill_value = fill_value
  238. self.copy = copy
  239. def _validate_input(self, X, in_fit):
  240. if self.strategy in ("most_frequent", "constant"):
  241. # If input is a list of strings, dtype = object.
  242. # Otherwise ValueError is raised in SimpleImputer
  243. # with strategy='most_frequent' or 'constant'
  244. # because the list is converted to Unicode numpy array
  245. if isinstance(X, list) and any(
  246. isinstance(elem, str) for row in X for elem in row
  247. ):
  248. dtype = object
  249. else:
  250. dtype = None
  251. else:
  252. dtype = FLOAT_DTYPES
  253. if not in_fit and self._fit_dtype.kind == "O":
  254. # Use object dtype if fitted on object dtypes
  255. dtype = self._fit_dtype
  256. if _is_pandas_na(self.missing_values) or is_scalar_nan(self.missing_values):
  257. force_all_finite = "allow-nan"
  258. else:
  259. force_all_finite = True
  260. try:
  261. X = self._validate_data(
  262. X,
  263. reset=in_fit,
  264. accept_sparse="csc",
  265. dtype=dtype,
  266. force_all_finite=force_all_finite,
  267. copy=self.copy,
  268. )
  269. except ValueError as ve:
  270. if "could not convert" in str(ve):
  271. new_ve = ValueError(
  272. "Cannot use {} strategy with non-numeric data:\n{}".format(
  273. self.strategy, ve
  274. )
  275. )
  276. raise new_ve from None
  277. else:
  278. raise ve
  279. if in_fit:
  280. # Use the dtype seen in `fit` for non-`fit` conversion
  281. self._fit_dtype = X.dtype
  282. _check_inputs_dtype(X, self.missing_values)
  283. if X.dtype.kind not in ("i", "u", "f", "O"):
  284. raise ValueError(
  285. "SimpleImputer does not support data with dtype "
  286. "{0}. Please provide either a numeric array (with"
  287. " a floating point or integer dtype) or "
  288. "categorical data represented either as an array "
  289. "with integer dtype or an array of string values "
  290. "with an object dtype.".format(X.dtype)
  291. )
  292. return X
  293. @_fit_context(prefer_skip_nested_validation=True)
  294. def fit(self, X, y=None):
  295. """Fit the imputer on `X`.
  296. Parameters
  297. ----------
  298. X : {array-like, sparse matrix}, shape (n_samples, n_features)
  299. Input data, where `n_samples` is the number of samples and
  300. `n_features` is the number of features.
  301. y : Ignored
  302. Not used, present here for API consistency by convention.
  303. Returns
  304. -------
  305. self : object
  306. Fitted estimator.
  307. """
  308. X = self._validate_input(X, in_fit=True)
  309. # default fill_value is 0 for numerical input and "missing_value"
  310. # otherwise
  311. if self.fill_value is None:
  312. if X.dtype.kind in ("i", "u", "f"):
  313. fill_value = 0
  314. else:
  315. fill_value = "missing_value"
  316. else:
  317. fill_value = self.fill_value
  318. # fill_value should be numerical in case of numerical input
  319. if (
  320. self.strategy == "constant"
  321. and X.dtype.kind in ("i", "u", "f")
  322. and not isinstance(fill_value, numbers.Real)
  323. ):
  324. raise ValueError(
  325. "'fill_value'={0} is invalid. Expected a "
  326. "numerical value when imputing numerical "
  327. "data".format(fill_value)
  328. )
  329. if sp.issparse(X):
  330. # missing_values = 0 not allowed with sparse data as it would
  331. # force densification
  332. if self.missing_values == 0:
  333. raise ValueError(
  334. "Imputation not possible when missing_values "
  335. "== 0 and input is sparse. Provide a dense "
  336. "array instead."
  337. )
  338. else:
  339. self.statistics_ = self._sparse_fit(
  340. X, self.strategy, self.missing_values, fill_value
  341. )
  342. else:
  343. self.statistics_ = self._dense_fit(
  344. X, self.strategy, self.missing_values, fill_value
  345. )
  346. return self
  347. def _sparse_fit(self, X, strategy, missing_values, fill_value):
  348. """Fit the transformer on sparse data."""
  349. missing_mask = _get_mask(X, missing_values)
  350. mask_data = missing_mask.data
  351. n_implicit_zeros = X.shape[0] - np.diff(X.indptr)
  352. statistics = np.empty(X.shape[1])
  353. if strategy == "constant":
  354. # for constant strategy, self.statistics_ is used to store
  355. # fill_value in each column
  356. statistics.fill(fill_value)
  357. else:
  358. for i in range(X.shape[1]):
  359. column = X.data[X.indptr[i] : X.indptr[i + 1]]
  360. mask_column = mask_data[X.indptr[i] : X.indptr[i + 1]]
  361. column = column[~mask_column]
  362. # combine explicit and implicit zeros
  363. mask_zeros = _get_mask(column, 0)
  364. column = column[~mask_zeros]
  365. n_explicit_zeros = mask_zeros.sum()
  366. n_zeros = n_implicit_zeros[i] + n_explicit_zeros
  367. if len(column) == 0 and self.keep_empty_features:
  368. # in case we want to keep columns with only missing values.
  369. statistics[i] = 0
  370. else:
  371. if strategy == "mean":
  372. s = column.size + n_zeros
  373. statistics[i] = np.nan if s == 0 else column.sum() / s
  374. elif strategy == "median":
  375. statistics[i] = _get_median(column, n_zeros)
  376. elif strategy == "most_frequent":
  377. statistics[i] = _most_frequent(column, 0, n_zeros)
  378. super()._fit_indicator(missing_mask)
  379. return statistics
  380. def _dense_fit(self, X, strategy, missing_values, fill_value):
  381. """Fit the transformer on dense data."""
  382. missing_mask = _get_mask(X, missing_values)
  383. masked_X = ma.masked_array(X, mask=missing_mask)
  384. super()._fit_indicator(missing_mask)
  385. # Mean
  386. if strategy == "mean":
  387. mean_masked = np.ma.mean(masked_X, axis=0)
  388. # Avoid the warning "Warning: converting a masked element to nan."
  389. mean = np.ma.getdata(mean_masked)
  390. mean[np.ma.getmask(mean_masked)] = 0 if self.keep_empty_features else np.nan
  391. return mean
  392. # Median
  393. elif strategy == "median":
  394. median_masked = np.ma.median(masked_X, axis=0)
  395. # Avoid the warning "Warning: converting a masked element to nan."
  396. median = np.ma.getdata(median_masked)
  397. median[np.ma.getmaskarray(median_masked)] = (
  398. 0 if self.keep_empty_features else np.nan
  399. )
  400. return median
  401. # Most frequent
  402. elif strategy == "most_frequent":
  403. # Avoid use of scipy.stats.mstats.mode due to the required
  404. # additional overhead and slow benchmarking performance.
  405. # See Issue 14325 and PR 14399 for full discussion.
  406. # To be able access the elements by columns
  407. X = X.transpose()
  408. mask = missing_mask.transpose()
  409. if X.dtype.kind == "O":
  410. most_frequent = np.empty(X.shape[0], dtype=object)
  411. else:
  412. most_frequent = np.empty(X.shape[0])
  413. for i, (row, row_mask) in enumerate(zip(X[:], mask[:])):
  414. row_mask = np.logical_not(row_mask).astype(bool)
  415. row = row[row_mask]
  416. if len(row) == 0 and self.keep_empty_features:
  417. most_frequent[i] = 0
  418. else:
  419. most_frequent[i] = _most_frequent(row, np.nan, 0)
  420. return most_frequent
  421. # Constant
  422. elif strategy == "constant":
  423. # for constant strategy, self.statistcs_ is used to store
  424. # fill_value in each column
  425. return np.full(X.shape[1], fill_value, dtype=X.dtype)
  426. def transform(self, X):
  427. """Impute all missing values in `X`.
  428. Parameters
  429. ----------
  430. X : {array-like, sparse matrix}, shape (n_samples, n_features)
  431. The input data to complete.
  432. Returns
  433. -------
  434. X_imputed : {ndarray, sparse matrix} of shape \
  435. (n_samples, n_features_out)
  436. `X` with imputed values.
  437. """
  438. check_is_fitted(self)
  439. X = self._validate_input(X, in_fit=False)
  440. statistics = self.statistics_
  441. if X.shape[1] != statistics.shape[0]:
  442. raise ValueError(
  443. "X has %d features per sample, expected %d"
  444. % (X.shape[1], self.statistics_.shape[0])
  445. )
  446. # compute mask before eliminating invalid features
  447. missing_mask = _get_mask(X, self.missing_values)
  448. # Decide whether to keep missing features
  449. if self.strategy == "constant" or self.keep_empty_features:
  450. valid_statistics = statistics
  451. valid_statistics_indexes = None
  452. else:
  453. # same as np.isnan but also works for object dtypes
  454. invalid_mask = _get_mask(statistics, np.nan)
  455. valid_mask = np.logical_not(invalid_mask)
  456. valid_statistics = statistics[valid_mask]
  457. valid_statistics_indexes = np.flatnonzero(valid_mask)
  458. if invalid_mask.any():
  459. invalid_features = np.arange(X.shape[1])[invalid_mask]
  460. # use feature names warning if features are provided
  461. if hasattr(self, "feature_names_in_"):
  462. invalid_features = self.feature_names_in_[invalid_features]
  463. warnings.warn(
  464. "Skipping features without any observed values:"
  465. f" {invalid_features}. At least one non-missing value is needed"
  466. f" for imputation with strategy='{self.strategy}'."
  467. )
  468. X = X[:, valid_statistics_indexes]
  469. # Do actual imputation
  470. if sp.issparse(X):
  471. if self.missing_values == 0:
  472. raise ValueError(
  473. "Imputation not possible when missing_values "
  474. "== 0 and input is sparse. Provide a dense "
  475. "array instead."
  476. )
  477. else:
  478. # if no invalid statistics are found, use the mask computed
  479. # before, else recompute mask
  480. if valid_statistics_indexes is None:
  481. mask = missing_mask.data
  482. else:
  483. mask = _get_mask(X.data, self.missing_values)
  484. indexes = np.repeat(
  485. np.arange(len(X.indptr) - 1, dtype=int), np.diff(X.indptr)
  486. )[mask]
  487. X.data[mask] = valid_statistics[indexes].astype(X.dtype, copy=False)
  488. else:
  489. # use mask computed before eliminating invalid mask
  490. if valid_statistics_indexes is None:
  491. mask_valid_features = missing_mask
  492. else:
  493. mask_valid_features = missing_mask[:, valid_statistics_indexes]
  494. n_missing = np.sum(mask_valid_features, axis=0)
  495. values = np.repeat(valid_statistics, n_missing)
  496. coordinates = np.where(mask_valid_features.transpose())[::-1]
  497. X[coordinates] = values
  498. X_indicator = super()._transform_indicator(missing_mask)
  499. return super()._concatenate_indicator(X, X_indicator)
  500. def inverse_transform(self, X):
  501. """Convert the data back to the original representation.
  502. Inverts the `transform` operation performed on an array.
  503. This operation can only be performed after :class:`SimpleImputer` is
  504. instantiated with `add_indicator=True`.
  505. Note that `inverse_transform` can only invert the transform in
  506. features that have binary indicators for missing values. If a feature
  507. has no missing values at `fit` time, the feature won't have a binary
  508. indicator, and the imputation done at `transform` time won't be
  509. inverted.
  510. .. versionadded:: 0.24
  511. Parameters
  512. ----------
  513. X : array-like of shape \
  514. (n_samples, n_features + n_features_missing_indicator)
  515. The imputed data to be reverted to original data. It has to be
  516. an augmented array of imputed data and the missing indicator mask.
  517. Returns
  518. -------
  519. X_original : ndarray of shape (n_samples, n_features)
  520. The original `X` with missing values as it was prior
  521. to imputation.
  522. """
  523. check_is_fitted(self)
  524. if not self.add_indicator:
  525. raise ValueError(
  526. "'inverse_transform' works only when "
  527. "'SimpleImputer' is instantiated with "
  528. "'add_indicator=True'. "
  529. f"Got 'add_indicator={self.add_indicator}' "
  530. "instead."
  531. )
  532. n_features_missing = len(self.indicator_.features_)
  533. non_empty_feature_count = X.shape[1] - n_features_missing
  534. array_imputed = X[:, :non_empty_feature_count].copy()
  535. missing_mask = X[:, non_empty_feature_count:].astype(bool)
  536. n_features_original = len(self.statistics_)
  537. shape_original = (X.shape[0], n_features_original)
  538. X_original = np.zeros(shape_original)
  539. X_original[:, self.indicator_.features_] = missing_mask
  540. full_mask = X_original.astype(bool)
  541. imputed_idx, original_idx = 0, 0
  542. while imputed_idx < len(array_imputed.T):
  543. if not np.all(X_original[:, original_idx]):
  544. X_original[:, original_idx] = array_imputed.T[imputed_idx]
  545. imputed_idx += 1
  546. original_idx += 1
  547. else:
  548. original_idx += 1
  549. X_original[full_mask] = self.missing_values
  550. return X_original
  551. def _more_tags(self):
  552. return {
  553. "allow_nan": _is_pandas_na(self.missing_values) or is_scalar_nan(
  554. self.missing_values
  555. )
  556. }
  557. def get_feature_names_out(self, input_features=None):
  558. """Get output feature names for transformation.
  559. Parameters
  560. ----------
  561. input_features : array-like of str or None, default=None
  562. Input features.
  563. - If `input_features` is `None`, then `feature_names_in_` is
  564. used as feature names in. If `feature_names_in_` is not defined,
  565. then the following input feature names are generated:
  566. `["x0", "x1", ..., "x(n_features_in_ - 1)"]`.
  567. - If `input_features` is an array-like, then `input_features` must
  568. match `feature_names_in_` if `feature_names_in_` is defined.
  569. Returns
  570. -------
  571. feature_names_out : ndarray of str objects
  572. Transformed feature names.
  573. """
  574. check_is_fitted(self, "n_features_in_")
  575. input_features = _check_feature_names_in(self, input_features)
  576. non_missing_mask = np.logical_not(_get_mask(self.statistics_, np.nan))
  577. names = input_features[non_missing_mask]
  578. return self._concatenate_indicator_feature_names_out(names, input_features)
  579. class MissingIndicator(TransformerMixin, BaseEstimator):
  580. """Binary indicators for missing values.
  581. Note that this component typically should not be used in a vanilla
  582. :class:`~sklearn.pipeline.Pipeline` consisting of transformers and a
  583. classifier, but rather could be added using a
  584. :class:`~sklearn.pipeline.FeatureUnion` or
  585. :class:`~sklearn.compose.ColumnTransformer`.
  586. Read more in the :ref:`User Guide <impute>`.
  587. .. versionadded:: 0.20
  588. Parameters
  589. ----------
  590. missing_values : int, float, str, np.nan or None, default=np.nan
  591. The placeholder for the missing values. All occurrences of
  592. `missing_values` will be imputed. For pandas' dataframes with
  593. nullable integer dtypes with missing values, `missing_values`
  594. should be set to `np.nan`, since `pd.NA` will be converted to `np.nan`.
  595. features : {'missing-only', 'all'}, default='missing-only'
  596. Whether the imputer mask should represent all or a subset of
  597. features.
  598. - If `'missing-only'` (default), the imputer mask will only represent
  599. features containing missing values during fit time.
  600. - If `'all'`, the imputer mask will represent all features.
  601. sparse : bool or 'auto', default='auto'
  602. Whether the imputer mask format should be sparse or dense.
  603. - If `'auto'` (default), the imputer mask will be of same type as
  604. input.
  605. - If `True`, the imputer mask will be a sparse matrix.
  606. - If `False`, the imputer mask will be a numpy array.
  607. error_on_new : bool, default=True
  608. If `True`, :meth:`transform` will raise an error when there are
  609. features with missing values that have no missing values in
  610. :meth:`fit`. This is applicable only when `features='missing-only'`.
  611. Attributes
  612. ----------
  613. features_ : ndarray of shape (n_missing_features,) or (n_features,)
  614. The features indices which will be returned when calling
  615. :meth:`transform`. They are computed during :meth:`fit`. If
  616. `features='all'`, `features_` is equal to `range(n_features)`.
  617. n_features_in_ : int
  618. Number of features seen during :term:`fit`.
  619. .. versionadded:: 0.24
  620. feature_names_in_ : ndarray of shape (`n_features_in_`,)
  621. Names of features seen during :term:`fit`. Defined only when `X`
  622. has feature names that are all strings.
  623. .. versionadded:: 1.0
  624. See Also
  625. --------
  626. SimpleImputer : Univariate imputation of missing values.
  627. IterativeImputer : Multivariate imputation of missing values.
  628. Examples
  629. --------
  630. >>> import numpy as np
  631. >>> from sklearn.impute import MissingIndicator
  632. >>> X1 = np.array([[np.nan, 1, 3],
  633. ... [4, 0, np.nan],
  634. ... [8, 1, 0]])
  635. >>> X2 = np.array([[5, 1, np.nan],
  636. ... [np.nan, 2, 3],
  637. ... [2, 4, 0]])
  638. >>> indicator = MissingIndicator()
  639. >>> indicator.fit(X1)
  640. MissingIndicator()
  641. >>> X2_tr = indicator.transform(X2)
  642. >>> X2_tr
  643. array([[False, True],
  644. [ True, False],
  645. [False, False]])
  646. """
  647. _parameter_constraints: dict = {
  648. "missing_values": [MissingValues()],
  649. "features": [StrOptions({"missing-only", "all"})],
  650. "sparse": ["boolean", StrOptions({"auto"})],
  651. "error_on_new": ["boolean"],
  652. }
  653. def __init__(
  654. self,
  655. *,
  656. missing_values=np.nan,
  657. features="missing-only",
  658. sparse="auto",
  659. error_on_new=True,
  660. ):
  661. self.missing_values = missing_values
  662. self.features = features
  663. self.sparse = sparse
  664. self.error_on_new = error_on_new
  665. def _get_missing_features_info(self, X):
  666. """Compute the imputer mask and the indices of the features
  667. containing missing values.
  668. Parameters
  669. ----------
  670. X : {ndarray, sparse matrix} of shape (n_samples, n_features)
  671. The input data with missing values. Note that `X` has been
  672. checked in :meth:`fit` and :meth:`transform` before to call this
  673. function.
  674. Returns
  675. -------
  676. imputer_mask : {ndarray, sparse matrix} of shape \
  677. (n_samples, n_features)
  678. The imputer mask of the original data.
  679. features_with_missing : ndarray of shape (n_features_with_missing)
  680. The features containing missing values.
  681. """
  682. if not self._precomputed:
  683. imputer_mask = _get_mask(X, self.missing_values)
  684. else:
  685. imputer_mask = X
  686. if sp.issparse(X):
  687. imputer_mask.eliminate_zeros()
  688. if self.features == "missing-only":
  689. n_missing = imputer_mask.getnnz(axis=0)
  690. if self.sparse is False:
  691. imputer_mask = imputer_mask.toarray()
  692. elif imputer_mask.format == "csr":
  693. imputer_mask = imputer_mask.tocsc()
  694. else:
  695. if not self._precomputed:
  696. imputer_mask = _get_mask(X, self.missing_values)
  697. else:
  698. imputer_mask = X
  699. if self.features == "missing-only":
  700. n_missing = imputer_mask.sum(axis=0)
  701. if self.sparse is True:
  702. imputer_mask = sp.csc_matrix(imputer_mask)
  703. if self.features == "all":
  704. features_indices = np.arange(X.shape[1])
  705. else:
  706. features_indices = np.flatnonzero(n_missing)
  707. return imputer_mask, features_indices
  708. def _validate_input(self, X, in_fit):
  709. if not is_scalar_nan(self.missing_values):
  710. force_all_finite = True
  711. else:
  712. force_all_finite = "allow-nan"
  713. X = self._validate_data(
  714. X,
  715. reset=in_fit,
  716. accept_sparse=("csc", "csr"),
  717. dtype=None,
  718. force_all_finite=force_all_finite,
  719. )
  720. _check_inputs_dtype(X, self.missing_values)
  721. if X.dtype.kind not in ("i", "u", "f", "O"):
  722. raise ValueError(
  723. "MissingIndicator does not support data with "
  724. "dtype {0}. Please provide either a numeric array"
  725. " (with a floating point or integer dtype) or "
  726. "categorical data represented either as an array "
  727. "with integer dtype or an array of string values "
  728. "with an object dtype.".format(X.dtype)
  729. )
  730. if sp.issparse(X) and self.missing_values == 0:
  731. # missing_values = 0 not allowed with sparse data as it would
  732. # force densification
  733. raise ValueError(
  734. "Sparse input with missing_values=0 is "
  735. "not supported. Provide a dense "
  736. "array instead."
  737. )
  738. return X
  739. def _fit(self, X, y=None, precomputed=False):
  740. """Fit the transformer on `X`.
  741. Parameters
  742. ----------
  743. X : {array-like, sparse matrix} of shape (n_samples, n_features)
  744. Input data, where `n_samples` is the number of samples and
  745. `n_features` is the number of features.
  746. If `precomputed=True`, then `X` is a mask of the input data.
  747. precomputed : bool
  748. Whether the input data is a mask.
  749. Returns
  750. -------
  751. imputer_mask : {ndarray, sparse matrix} of shape (n_samples, \
  752. n_features)
  753. The imputer mask of the original data.
  754. """
  755. if precomputed:
  756. if not (hasattr(X, "dtype") and X.dtype.kind == "b"):
  757. raise ValueError("precomputed is True but the input data is not a mask")
  758. self._precomputed = True
  759. else:
  760. self._precomputed = False
  761. # Need not validate X again as it would have already been validated
  762. # in the Imputer calling MissingIndicator
  763. if not self._precomputed:
  764. X = self._validate_input(X, in_fit=True)
  765. else:
  766. # only create `n_features_in_` in the precomputed case
  767. self._check_n_features(X, reset=True)
  768. self._n_features = X.shape[1]
  769. missing_features_info = self._get_missing_features_info(X)
  770. self.features_ = missing_features_info[1]
  771. return missing_features_info[0]
  772. @_fit_context(prefer_skip_nested_validation=True)
  773. def fit(self, X, y=None):
  774. """Fit the transformer on `X`.
  775. Parameters
  776. ----------
  777. X : {array-like, sparse matrix} of shape (n_samples, n_features)
  778. Input data, where `n_samples` is the number of samples and
  779. `n_features` is the number of features.
  780. y : Ignored
  781. Not used, present for API consistency by convention.
  782. Returns
  783. -------
  784. self : object
  785. Fitted estimator.
  786. """
  787. self._fit(X, y)
  788. return self
  789. def transform(self, X):
  790. """Generate missing values indicator for `X`.
  791. Parameters
  792. ----------
  793. X : {array-like, sparse matrix} of shape (n_samples, n_features)
  794. The input data to complete.
  795. Returns
  796. -------
  797. Xt : {ndarray, sparse matrix} of shape (n_samples, n_features) \
  798. or (n_samples, n_features_with_missing)
  799. The missing indicator for input data. The data type of `Xt`
  800. will be boolean.
  801. """
  802. check_is_fitted(self)
  803. # Need not validate X again as it would have already been validated
  804. # in the Imputer calling MissingIndicator
  805. if not self._precomputed:
  806. X = self._validate_input(X, in_fit=False)
  807. else:
  808. if not (hasattr(X, "dtype") and X.dtype.kind == "b"):
  809. raise ValueError("precomputed is True but the input data is not a mask")
  810. imputer_mask, features = self._get_missing_features_info(X)
  811. if self.features == "missing-only":
  812. features_diff_fit_trans = np.setdiff1d(features, self.features_)
  813. if self.error_on_new and features_diff_fit_trans.size > 0:
  814. raise ValueError(
  815. "The features {} have missing values "
  816. "in transform but have no missing values "
  817. "in fit.".format(features_diff_fit_trans)
  818. )
  819. if self.features_.size < self._n_features:
  820. imputer_mask = imputer_mask[:, self.features_]
  821. return imputer_mask
  822. @_fit_context(prefer_skip_nested_validation=True)
  823. def fit_transform(self, X, y=None):
  824. """Generate missing values indicator for `X`.
  825. Parameters
  826. ----------
  827. X : {array-like, sparse matrix} of shape (n_samples, n_features)
  828. The input data to complete.
  829. y : Ignored
  830. Not used, present for API consistency by convention.
  831. Returns
  832. -------
  833. Xt : {ndarray, sparse matrix} of shape (n_samples, n_features) \
  834. or (n_samples, n_features_with_missing)
  835. The missing indicator for input data. The data type of `Xt`
  836. will be boolean.
  837. """
  838. imputer_mask = self._fit(X, y)
  839. if self.features_.size < self._n_features:
  840. imputer_mask = imputer_mask[:, self.features_]
  841. return imputer_mask
  842. def get_feature_names_out(self, input_features=None):
  843. """Get output feature names for transformation.
  844. Parameters
  845. ----------
  846. input_features : array-like of str or None, default=None
  847. Input features.
  848. - If `input_features` is `None`, then `feature_names_in_` is
  849. used as feature names in. If `feature_names_in_` is not defined,
  850. then the following input feature names are generated:
  851. `["x0", "x1", ..., "x(n_features_in_ - 1)"]`.
  852. - If `input_features` is an array-like, then `input_features` must
  853. match `feature_names_in_` if `feature_names_in_` is defined.
  854. Returns
  855. -------
  856. feature_names_out : ndarray of str objects
  857. Transformed feature names.
  858. """
  859. check_is_fitted(self, "n_features_in_")
  860. input_features = _check_feature_names_in(self, input_features)
  861. prefix = self.__class__.__name__.lower()
  862. return np.asarray(
  863. [
  864. f"{prefix}_{feature_name}"
  865. for feature_name in input_features[self.features_]
  866. ],
  867. dtype=object,
  868. )
  869. def _more_tags(self):
  870. return {
  871. "allow_nan": True,
  872. "X_types": ["2darray", "string"],
  873. "preserves_dtype": [],
  874. }