
    0PhfB                         d dl Z d dlmZ d dlZddlmZmZmZ ddl	m
Z
 ddlmZ ddlmZmZ ddlmZ dd	lmZmZmZmZmZmZmZmZmZ d
 Z G d dee          ZdS )    N)partial   )BaseEstimatorTransformerMixin_fit_context)_VisualBlock)
StrOptions)_get_adapter_from_container_get_output_config)available_if)	_allclose_dense_sparse_check_feature_names_check_feature_names_in_check_n_features_get_feature_names_is_pandas_df_is_polars_dfcheck_arrayvalidate_datac                     | S )zThe identity function. )Xs    k/var/www/html/test/jupyter/venv/lib/python3.11/site-packages/sklearn/preprocessing/_function_transformer.py	_identityr      s    H    c            	       &    e Zd ZU dZedgedgdgdgdge edh          dgedgedgdZeed<   	 	 dddddddd	d
Z	d Z
d Z ed          dd            Zd Zd Z ed           dd            ZddZd Z fdZdddZd Zd Z xZS )FunctionTransformera  Constructs a transformer from an arbitrary callable.

    A FunctionTransformer forwards its X (and optionally y) arguments to a
    user-defined function or function object and returns the result of this
    function. This is useful for stateless transformations such as taking the
    log of frequencies, doing custom scaling, etc.

    Note: If a lambda is used as the function, then the resulting
    transformer will not be pickleable.

    .. versionadded:: 0.17

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

    Parameters
    ----------
    func : callable, default=None
        The callable to use for the transformation. This will be passed
        the same arguments as transform, with args and kwargs forwarded.
        If func is None, then func will be the identity function.

    inverse_func : callable, default=None
        The callable to use for the inverse transformation. This will be
        passed the same arguments as inverse transform, with args and
        kwargs forwarded. If inverse_func is None, then inverse_func
        will be the identity function.

    validate : bool, default=False
        Indicate that the input X array should be checked before calling
        ``func``. The possibilities are:

        - If False, there is no input validation.
        - If True, then X will be converted to a 2-dimensional NumPy array or
          sparse matrix. If the conversion is not possible an exception is
          raised.

        .. versionchanged:: 0.22
           The default of ``validate`` changed from True to False.

    accept_sparse : bool, default=False
        Indicate that func accepts a sparse matrix as input. If validate is
        False, this has no effect. Otherwise, if accept_sparse is false,
        sparse matrix inputs will cause an exception to be raised.

    check_inverse : bool, default=True
       Whether to check that or ``func`` followed by ``inverse_func`` leads to
       the original inputs. It can be used for a sanity check, raising a
       warning when the condition is not fulfilled.

       .. versionadded:: 0.20

    feature_names_out : callable, 'one-to-one' or None, default=None
        Determines the list of feature names that will be returned by the
        `get_feature_names_out` method. If it is 'one-to-one', then the output
        feature names will be equal to the input feature names. If it is a
        callable, then it must take two positional arguments: this
        `FunctionTransformer` (`self`) and an array-like of input feature names
        (`input_features`). It must return an array-like of output feature
        names. The `get_feature_names_out` method is only defined if
        `feature_names_out` is not None.

        See ``get_feature_names_out`` for more details.

        .. versionadded:: 1.1

    kw_args : dict, default=None
        Dictionary of additional keyword arguments to pass to func.

        .. versionadded:: 0.18

    inv_kw_args : dict, default=None
        Dictionary of additional keyword arguments to pass to inverse_func.

        .. versionadded:: 0.18

    Attributes
    ----------
    n_features_in_ : int
        Number of features seen during :term:`fit`.

        .. versionadded:: 0.24

    feature_names_in_ : ndarray of shape (`n_features_in_`,)
        Names of features seen during :term:`fit`. Defined only when `X` has feature
        names that are all strings.

        .. versionadded:: 1.0

    See Also
    --------
    MaxAbsScaler : Scale each feature by its maximum absolute value.
    StandardScaler : Standardize features by removing the mean and
        scaling to unit variance.
    LabelBinarizer : Binarize labels in a one-vs-all fashion.
    MultiLabelBinarizer : Transform between iterable of iterables
        and a multilabel format.

    Notes
    -----
    If `func` returns an output with a `columns` attribute, then the columns is enforced
    to be consistent with the output of `get_feature_names_out`.

    Examples
    --------
    >>> import numpy as np
    >>> from sklearn.preprocessing import FunctionTransformer
    >>> transformer = FunctionTransformer(np.log1p)
    >>> X = np.array([[0, 1], [2, 3]])
    >>> transformer.transform(X)
    array([[0.       , 0.6931...],
           [1.0986..., 1.3862...]])
    Nboolean
one-to-onefuncinverse_funcvalidateaccept_sparsecheck_inversefeature_names_outkw_argsinv_kw_args_parameter_constraintsFT)r#   r$   r%   r&   r'   r(   c                v    || _         || _        || _        || _        || _        || _        || _        || _        d S Nr    )	selfr!   r"   r#   r$   r%   r&   r'   r(   s	            r   __init__zFunctionTransformer.__init__   sG     	( **!2&r   c                    | j         rt          | || j        |          S |r$t          | ||           t	          | ||           |S )N)r$   resetr/   )r#   r   r$   r   r   )r,   r   r/   s      r   _check_inputz FunctionTransformer._check_input   s`    = 	7 q8JRWXXXX 	7 dAU3333 q6666r   c           	         t          ddt          d|j        d         dz                      }|                     |                     ||                             }t          |d          r	|j        g}nt          |d          r|j        }t          d |D                       st          d          t          ||         |          st          j        d	t                     dS dS )
z1Check that func and inverse_func are the inverse.N   r   d   dtypedtypesc              3   T   K   | ]#}t          j        |t           j                  V  $d S r+   )np
issubdtypenumber).0ds     r   	<genexpr>z?FunctionTransformer._check_inverse_transform.<locals>.<genexpr>   s0      ??12=BI..??????r   zL'check_inverse' is only supported when all the elements in `X` is numerical.zThe provided functions are not strictly inverse of each other. If you are sure you want to proceed regardless, set 'check_inverse=False'.)slicemaxshapeinverse_transform	transformhasattrr5   r6   all
ValueErrorr   warningswarnUserWarning)r,   r   idx_selectedX_round_tripr6   s        r   _check_inverse_transformz,FunctionTransformer._check_inverse_transform   s   T4Q
c0A)B)BCC--dnnQ|_.M.MNN1g 	gYFFQ!! 	XF??????? 	  
 &ao|DD 		M.
     		 		r   )prefer_skip_nested_validationc                     |                      |d          }| j        r#| j        | j        |                     |           | S )a  Fit transformer by checking X.

        If ``validate`` is ``True``, ``X`` will be checked.

        Parameters
        ----------
        X : {array-like, sparse-matrix} of shape (n_samples, n_features)                 if `validate=True` else any object that `func` can handle
            Input array.

        y : Ignored
            Not used, present here for API consistency by convention.

        Returns
        -------
        self : object
            FunctionTransformer class instance.
        Tr0   )r1   r%   r!   r"   rK   )r,   r   ys      r   fitzFunctionTransformer.fit   sO    ( at,, 	-ty'8D<M<U))!,,,r   c           	          |                      |d          }|                     || j        | j                  }t	          d|           d         }t          |d          r| j        |                                 }t          |j	                  t          |          k    rt          |dt          |                    }|duo$t          |          t          |j	                  k    }t          d	 |j	        D                        }|s|r)t          |          }|                    |||d
          }nGt          dt          |j	                   dt          |                                            d          | j        {d}	|dk    r7t!          |          s(t#          j        |	                    d                     n<|dk    r6t)          |          s't#          j        |	                    d                     |S )a}  Transform X using the forward function.

        Parameters
        ----------
        X : {array-like, sparse-matrix} of shape (n_samples, n_features)                 if `validate=True` else any object that `func` can handle
            Input array.

        Returns
        -------
        X_out : array-like, shape (n_samples, n_features)
            Transformed input.
        Fr0   r!   r'   rB   densecolumnsNfeature_names_in_c              3   @   K   | ]}t          |t                    V  d S r+   )
isinstancestr)r;   cols     r   r=   z0FunctionTransformer.transform.<locals>.<genexpr>  s=       . .-0JsC((. . . . . .r   )X_output
X_originalrS   inplacezThe output generated by `func` have different column names than the ones provided by `get_feature_names_out`. Got output with columns names: z' and `get_feature_names_out` returned: z. The column names can be overridden by setting `set_output(transform='pandas')` or `set_output(transform='polars')` such that the column names are set to the names provided by `get_feature_names_out`.zWhen `set_output` is configured to be '{0}', `func` should return a {0} DataFrame to follow the `set_output` API  or `feature_names_out` should be defined.pandaspolars)r1   
_transformr!   r'   r   rC   r&   get_feature_names_outlistrS   getattrr   rD   r
   create_containerrE   r   rF   rG   formatr   )
r,   r   outoutput_configr&   feature_names_insame_feature_names_in_outnot_all_str_columnsadapterwarn_msgs
             r   rB   zFunctionTransformer.transform   sQ    au--ooadioFF*;==gF3	"" '	t'='I !% : : < <CK  D):$;$;;; $+*,>q,A,A$ $  -=D,H -'T$N N#+&&N') +. . .47K. . . + + '# - 0C 9#>>G!22!$#& 1 %	 3  CC %T:>s{:K:KT T   : : < <==	T T T
 
 
 !)& 
 ((s1C1C(hooh778888(**=3E3E*hooh77888
r   c                     | j         rt          || j                  }|                     || j        | j                  S )a  Transform X using the inverse function.

        Parameters
        ----------
        X : {array-like, sparse-matrix} of shape (n_samples, n_features)                 if `validate=True` else any object that `inverse_func` can handle
            Input array.

        Returns
        -------
        X_out : array-like, shape (n_samples, n_features)
            Transformed input.
        )r$   rQ   )r#   r   r$   r^   r"   r(   )r,   r   s     r   rA   z%FunctionTransformer.inverse_transform=  sB     = 	AAT-?@@@Aqt'8$BRSSSr   c                     | j         d uS r+   )r&   r,   s    r   <lambda>zFunctionTransformer.<lambda>O  s    t5TA r   c                    t          | d          s|t          | |          }| j        dk    r|}nCt          | j                  r|                     | |          }nt	          d| j        d          t          j        |t                    S )a/  Get output feature names for transformation.

        This method is only defined if `feature_names_out` is not None.

        Parameters
        ----------
        input_features : array-like of str or None, default=None
            Input feature names.

            - If `input_features` is None, then `feature_names_in_` is
              used as the input feature names. If `feature_names_in_` is not
              defined, then names are generated:
              `[x0, x1, ..., x(n_features_in_ - 1)]`.
            - If `input_features` is array-like, then `input_features` must
              match `feature_names_in_` if `feature_names_in_` is defined.

        Returns
        -------
        feature_names_out : ndarray of str objects
            Transformed feature names.

            - If `feature_names_out` is 'one-to-one', the input feature names
              are returned (see `input_features` above). This requires
              `feature_names_in_` and/or `n_features_in_` to be defined, which
              is done automatically if `validate=True`. Alternatively, you can
              set them in `func`.
            - If `feature_names_out` is a callable, then it is called with two
              arguments, `self` and `input_features`, and its return value is
              returned by this method.
        n_features_in_Nr   zfeature_names_out=z is invalid. It must either be "one-to-one" or a callable with two arguments: the function transformer and an array-like of input feature names. The callable must return an array-like of output feature names.)r5   )rC   r   r&   callablerE   r8   asarrayobject)r,   input_features	names_outs      r   r_   z)FunctionTransformer.get_feature_names_outO  s    @ 4)** 	Kn.H4T>JJN!\11&IId,-- 		..t^DDII+T%; + + +   z)62222r   c                 .    |t           } ||fi |r|ni S r+   )r   )r,   r   r!   r'   s       r   r^   zFunctionTransformer._transform  s-    <DtA66W4''"666r   c                     dS )z2Return True since FunctionTransfomer is stateless.Tr   rm   s    r   __sklearn_is_fitted__z)FunctionTransformer.__sklearn_is_fitted__  s    tr   c                     t                                                      }| j         |_        d|_        | j         p| j        |j        _        |S )NF)super__sklearn_tags__r#   no_validationrequires_fitr$   
input_tagssparse)r,   tags	__class__s     r   r{   z$FunctionTransformer.__sklearn_tags__  sI    ww''))!%.!%)]!2!Hd6Hr   )rB   c                H    t          | d          si | _        || j        d<   | S )a  Set output container.

        See :ref:`sphx_glr_auto_examples_miscellaneous_plot_set_output.py`
        for an example on how to use the API.

        Parameters
        ----------
        transform : {"default", "pandas", "polars"}, default=None
            Configure output of `transform` and `fit_transform`.

            - `"default"`: Default output format of a transformer
            - `"pandas"`: DataFrame output
            - `"polars"`: Polars output
            - `None`: Transform configuration is unchanged

            .. versionadded:: 1.4
                `"polars"` option was added.

        Returns
        -------
        self : estimator instance
            Estimator instance.
        _sklearn_output_configrB   )rC   r   )r,   rB   s     r   
set_outputzFunctionTransformer.set_output  s1    0 t566 	-*,D'3<#K0r   c                     t          | j        d          r| j        j        S t          | j        t                    r| j        j        j        S | j        j        j         dS )z?Get the name display of the `func` used in HTML representation.__name__z(...))rC   r!   r   rV   r   r   rm   s    r   _get_function_namez&FunctionTransformer._get_function_name  sY    49j)) 	&9%%di)) 	+9>**)%.5555r   c                 j    t          d| |                                 t          |           dd          S )Nsingler   )namesname_detailsname_captiondoc_link_label)r   r   rW   rm   s    r   _sk_visual_block_z%FunctionTransformer._sk_visual_block_  s=    ))++T.0
 
 
 	
r   )NNr+   )r   
__module____qualname____doc__rq   r	   dictr)   __annotations__r-   r1   rK   r   rO   rB   rA   r   r_   r^   rx   r{   r   r   r   __classcell__)r   s   @r   r   r   #   s        o od 4 !4(K##&

L>(B(BDI$<d|	$ 	$D 	 	 	 '
 ' ' ' ' '*	 	 	  8 \555   650F F FPT T T$ \AABB-3 -3 -3 CB-3^7 7 7 7       '+     <6 6 6
 
 
 
 
 
 
r   r   )rF   	functoolsr   numpyr8   baser   r   r   utils._estimator_html_reprr   utils._param_validationr	   utils._set_outputr
   r   utils.metaestimatorsr   utils.validationr   r   r   r   r   r   r   r   r   r   r   r   r   r   <module>r      sj              @ @ @ @ @ @ @ @ @ @ 5 5 5 5 5 5 0 0 0 0 0 0        0 / / / / /
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
  
[
 [
 [
 [
 [
*M [
 [
 [
 [
 [
r   