<commit_before>
from time import time
from collections import namedtuple
import warnings

from scipy import stats
import numpy as np

from ..base import clone
from ..exceptions import ConvergenceWarning
from ..preprocessing import normalize
from ..utils import (check_array, check_random_state, _safe_indexing,
                     is_scalar_nan)
from ..utils.validation import FLOAT_DTYPES, check_is_fitted
from ..utils._mask import _get_mask

from ._base import _BaseImputer
from ._base import SimpleImputer
from ._base import _check_inputs_dtype


_ImputerTriplet = namedtuple('_ImputerTriplet', ['feat_idx',
                                                 'neighbor_feat_idx',
                                                 'estimator'])


class IterativeImputer(_BaseImputer):
    """Multivariate imputer that estimates each feature from all the others.

    A strategy for imputing missing values by modeling each feature with
    missing values as a function of other features in a round-robin fashion.

    Read more in the :ref:`User Guide <iterative_imputer>`.

    .. versionadded:: 0.21

    .. note::

      This estimator is still **experimental** for now: the predictions
      and the API might change without any deprecation cycle. To use it,
      you need to explicitly import ``enable_iterative_imputer``::

        >>> # explicitly require this experimental feature
        >>> from sklearn.experimental import enable_iterative_imputer  # noqa
        >>> # now you can import normally from sklearn.impute
        >>> from sklearn.impute import IterativeImputer

    Parameters
    ----------
    estimator : estimator object, default=BayesianRidge()
        The estimator to use at each step of the round-robin imputation.
        If ``sample_posterior`` is True, the estimator must support
        ``return_std`` in its ``predict`` method.

    missing_values : int, np.nan, default=np.nan
        The placeholder for the missing values. All occurrences of
        `missing_values` will be imputed. For pandas' dataframes with
        nullable integer dtypes with missing values, `missing_values`
        should be set to `np.nan`, since `pd.NA` will be converted to `np.nan`.

    sample_posterior : boolean, default=False
        Whether to sample from the (Gaussian) predictive posterior of the
        fitted estimator for each imputation. Estimator must support
        ``return_std`` in its ``predict`` method if set to ``True``. Set to
        ``True`` if using ``IterativeImputer`` for multiple imputations.

    max_iter : int, default=10
        Maximum number of imputation rounds to perform before returning the
        imputations computed during the final round. A round is a single
        imputation of each feature with missing values. The stopping criterion
        is met once `abs(max(X_t - X_{t-1}))/abs(max(X[known_vals]))` < tol,
        where `X_t` is `X` at iteration `t. Note that early stopping is only
        applied if ``sample_posterior=False``.

    tol : float, default=1e-3
        Tolerance of the stopping condition.

    n_nearest_features : int, default=None
        Number of other features to use to estimate the missing values of
        each feature column. Nearness between features is measured using
        the absolute correlation coefficient between each feature pair (after
        initial imputation). To ensure coverage of features throughout the
        imputation process, the neighbor features are not necessarily nearest,
        but are drawn with probability proportional to correlation for each
        imputed target feature. Can provide significant speed-up when the
        number of features is huge. If ``None``, all features will be used.

    initial_strategy : str, default='mean'
        Which strategy to use to initialize the missing values. Same as the
        ``strategy`` parameter in :class:`~sklearn.impute.SimpleImputer`
        Valid values: {"mean", "median", "most_frequent", or "constant"}.

    imputation_order : str, default='ascending'
        The order in which the features will be imputed. Possible values:

        "ascending"
            From features with fewest missing values to most.
        "descending"
            From features with most missing values to fewest.
        "roman"
            Left to right.
        "arabic"<commit_msg>DOC Fixed typo in IterativeImputer:  switch abs and max positions (#18478)<commit_after>
from time import time
from collections import namedtuple
import warnings

from scipy import stats
import numpy as np

from ..base import clone
from ..exceptions import ConvergenceWarning
from ..preprocessing import normalize
from ..utils import (check_array, check_random_state, _safe_indexing,
                     is_scalar_nan)
from ..utils.validation import FLOAT_DTYPES, check_is_fitted
from ..utils._mask import _get_mask

from ._base import _BaseImputer
from ._base import SimpleImputer
from ._base import _check_inputs_dtype


_ImputerTriplet = namedtuple('_ImputerTriplet', ['feat_idx',
                                                 'neighbor_feat_idx',
                                                 'estimator'])


class IterativeImputer(_BaseImputer):
    """Multivariate imputer that estimates each feature from all the others.

    A strategy for imputing missing values by modeling each feature with
    missing values as a function of other features in a round-robin fashion.

    Read more in the :ref:`User Guide <iterative_imputer>`.

    .. versionadded:: 0.21

    .. note::

      This estimator is still **experimental** for now: the predictions
      and the API might change without any deprecation cycle. To use it,
      you need to explicitly import ``enable_iterative_imputer``::

        >>> # explicitly require this experimental feature
        >>> from sklearn.experimental import enable_iterative_imputer  # noqa
        >>> # now you can import normally from sklearn.impute
        >>> from sklearn.impute import IterativeImputer

    Parameters
    ----------
    estimator : estimator object, default=BayesianRidge()
        The estimator to use at each step of the round-robin imputation.
        If ``sample_posterior`` is True, the estimator must support
        ``return_std`` in its ``predict`` method.

    missing_values : int, np.nan, default=np.nan
        The placeholder for the missing values. All occurrences of
        `missing_values` will be imputed. For pandas' dataframes with
        nullable integer dtypes with missing values, `missing_values`
        should be set to `np.nan`, since `pd.NA` will be converted to `np.nan`.

    sample_posterior : boolean, default=False
        Whether to sample from the (Gaussian) predictive posterior of the
        fitted estimator for each imputation. Estimator must support
        ``return_std`` in its ``predict`` method if set to ``True``. Set to
        ``True`` if using ``IterativeImputer`` for multiple imputations.

    max_iter : int, default=10
        Maximum number of imputation rounds to perform before returning the
        imputations computed during the final round. A round is a single
        imputation of each feature with missing values. The stopping criterion
        is met once `max(abs(X_t - X_{t-1}))/max(abs(X[known_vals]))` < tol,
        where `X_t` is `X` at iteration `t. Note that early stopping is only
        applied if ``sample_posterior=False``.

    tol : float, default=1e-3
        Tolerance of the stopping condition.

    n_nearest_features : int, default=None
        Number of other features to use to estimate the missing values of
        each feature column. Nearness between features is measured using
        the absolute correlation coefficient between each feature pair (after
        initial imputation). To ensure coverage of features throughout the
        imputation process, the neighbor features are not necessarily nearest,
        but are drawn with probability proportional to correlation for each
        imputed target feature. Can provide significant speed-up when the
        number of features is huge. If ``None``, all features will be used.

    initial_strategy : str, default='mean'
        Which strategy to use to initialize the missing values. Same as the
        ``strategy`` parameter in :class:`~sklearn.impute.SimpleImputer`
        Valid values: {"mean", "median", "most_frequent", or "constant"}.

    imputation_order : str, default='ascending'
        The order in which the features will be imputed. Possible values:

        "ascending"
            From features with fewest missing values to most.
        "descending"
            From features with most missing values to fewest.
        "roman"
            Left to right.
        "arabic"
{'fraction_non_alphanumeric': 0.06681108197468932, 'fraction_numerical': 0.0023942537909018356, 'mean_word_length': 2.843996494303243, 'pattern_counts': {'":': 0, '<': 7, '<?xml version=': 0, '>': 29, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 8, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '3839447', 'n_tokens_mistral': 2289, 'n_tokens_neox': 2165, 'n_words': 957}