o
    1 i >                     @   s   d dl mZmZmZmZ d dlZd dlZd dl	m
Z
mZmZmZmZ d dlmZ d dlmZ er6d dlmZ eddG d	d
 d
eZeddG dd deZeddG dd deZeddG dd deZdS )    )TYPE_CHECKINGListOptionalTupleN)AbsMaxMaxMeanMinStd)Preprocessor)	PublicAPI)Datasetalpha)Z	stabilityc                       b   e Zd ZdZddee deee  f fddZddd	efd
dZ	de
jfddZdd Z  ZS )StandardScalerav	  Translate and scale each column by its mean and standard deviation,
    respectively.

    The general formula is given by

    .. math::

        x' = \frac{x - \bar{x}}{s}

    where :math:`x` is the column, :math:`x'` is the transformed column,
    :math:`\bar{x}` is the column average, and :math:`s` is the column's sample
    standard deviation. If :math:`s = 0` (i.e., the column is constant-valued),
    then the transformed column will contain zeros.

    .. warning::
        :class:`StandardScaler` works best when your data is normal. If your data isn't
        approximately normal, then the transformed features won't be meaningful.

    Examples:
        >>> import pandas as pd
        >>> import ray
        >>> from ray.data.preprocessors import StandardScaler
        >>>
        >>> df = pd.DataFrame({"X1": [-2, 0, 2], "X2": [-3, -3, 3], "X3": [1, 1, 1]})
        >>> ds = ray.data.from_pandas(df)  # doctest: +SKIP
        >>> ds.to_pandas()  # doctest: +SKIP
           X1  X2  X3
        0  -2  -3   1
        1   0  -3   1
        2   2   3   1

        Columns are scaled separately.

        >>> preprocessor = StandardScaler(columns=["X1", "X2"])
        >>> preprocessor.fit_transform(ds).to_pandas()  # doctest: +SKIP
                 X1        X2  X3
        0 -1.224745 -0.707107   1
        1  0.000000 -0.707107   1
        2  1.224745  1.414214   1

        Constant-valued columns get filled with zeros.

        >>> preprocessor = StandardScaler(columns=["X3"])
        >>> preprocessor.fit_transform(ds).to_pandas()  # doctest: +SKIP
           X1  X2   X3
        0  -2  -3  0.0
        1   0  -3  0.0
        2   2   3  0.0

        >>> preprocessor = StandardScaler(
        ...     columns=["X1", "X2"],
        ...     output_columns=["X1_scaled", "X2_scaled"]
        ... )
        >>> preprocessor.fit_transform(ds).to_pandas()  # doctest: +SKIP
           X1  X2  X3  X1_scaled  X2_scaled
        0  -2  -3   1  -1.224745  -0.707107
        1   0  -3   1   0.000000  -0.707107
        2   2   3   1   1.224745   1.414214

    Args:
        columns: The columns to separately scale.
        output_columns: The names of the transformed columns. If None, the transformed
            columns will be the same as the input columns. If not None, the length of
            ``output_columns`` must match the length of ``columns``, othwerwise an error
            will be raised.
    Ncolumnsoutput_columnsc                    "   t    || _t||| _d S Nsuper__init__r   r   #_derive_and_validate_output_columnsr   selfr   r   	__class__ i/home/app/PaddleOCR-VL-test/.venv_paddleocr/lib/python3.10/site-packages/ray/data/preprocessors/scaler.pyr   S   
   

zStandardScaler.__init__datasetr   returnc                 C   s,   | j jt| jd | j jdd | jd | S )N)Zaggregator_fnr   c                 S   s   t | ddS )Nr   )Zddof)r
   colr   r   r   <lambda>`   s    z%StandardScaler._fit.<locals>.<lambda>)Zstat_computation_planZadd_aggregatorr   r   )r   r    r   r   r   _fitZ   s   zStandardScaler._fitdfc                    .   dt jf fdd}| j || j< |S )Nsc                    sb    j d| j d } j d| j d }|d u s|d u r%tj| d d < | S |dkr+d}| | | S )Nzmean()zstd(r      )stats_namenpnan)r(   Zs_meanZs_stdr   r   r   column_standard_scalerf   s   z@StandardScaler._transform_pandas.<locals>.column_standard_scalerpdZSeriesr   Z	transformr   )r   r&   r0   r   r/   r   _transform_pandase   s   z StandardScaler._transform_pandasc                 C      | j j d| jd| jdS N	(columns=z, output_columns=r)   r   __name__r   r   r/   r   r   r   __repr__x      zStandardScaler.__repr__r   r8   
__module____qualname____doc__r   strr   r   r   r%   r2   	DataFramer3   r9   __classcell__r   r   r   r   r      s    $Cr   c                       r   )MinMaxScalera  Scale each column by its range.

    The general formula is given by

    .. math::

        x' = \frac{x - \min(x)}{\max{x} - \min{x}}

    where :math:`x` is the column and :math:`x'` is the transformed column. If
    :math:`\max{x} - \min{x} = 0` (i.e., the column is constant-valued), then the
    transformed column will get filled with zeros.

    Transformed values are always in the range :math:`[0, 1]`.

    .. tip::
        This can be used as an alternative to :py:class:`StandardScaler`.

    Examples:
        >>> import pandas as pd
        >>> import ray
        >>> from ray.data.preprocessors import MinMaxScaler
        >>>
        >>> df = pd.DataFrame({"X1": [-2, 0, 2], "X2": [-3, -3, 3], "X3": [1, 1, 1]})   # noqa: E501
        >>> ds = ray.data.from_pandas(df)  # doctest: +SKIP
        >>> ds.to_pandas()  # doctest: +SKIP
           X1  X2  X3
        0  -2  -3   1
        1   0  -3   1
        2   2   3   1

        Columns are scaled separately.

        >>> preprocessor = MinMaxScaler(columns=["X1", "X2"])
        >>> preprocessor.fit_transform(ds).to_pandas()  # doctest: +SKIP
            X1   X2  X3
        0  0.0  0.0   1
        1  0.5  0.0   1
        2  1.0  1.0   1

        Constant-valued columns get filled with zeros.

        >>> preprocessor = MinMaxScaler(columns=["X3"])
        >>> preprocessor.fit_transform(ds).to_pandas()  # doctest: +SKIP
           X1  X2   X3
        0  -2  -3  0.0
        1   0  -3  0.0
        2   2   3  0.0

        >>> preprocessor = MinMaxScaler(columns=["X1", "X2"], output_columns=["X1_scaled", "X2_scaled"])
        >>> preprocessor.fit_transform(ds).to_pandas()  # doctest: +SKIP
           X1  X2  X3  X1_scaled  X2_scaled
        0  -2  -3   1        0.0        0.0
        1   0  -3   1        0.5        0.0
        2   2   3   1        1.0        1.0

    Args:
        columns: The columns to separately scale.
        output_columns: The names of the transformed columns. If None, the transformed
            columns will be the same as the input columns. If not None, the length of
            ``output_columns`` must match the length of ``columns``, othwerwise an error
            will be raised.
    Nr   r   c                    r   r   r   r   r   r   r   r      r   zMinMaxScaler.__init__r    r   r!   c                    s&    fddt tfD }|j|  _ S )Nc                    s    g | ]} j D ]}||qqS r   )r   ).0ZAggr#   r/   r   r   
<listcomp>   s     z%MinMaxScaler._fit.<locals>.<listcomp>)r	   r   	aggregater+   r   r    Z
aggregatesr   r/   r   r%      s   zMinMaxScaler._fitr&   c                    r'   )Nr(   c                    sH    j d| j d } j d| j d }|| }|dkrd}| | | S )Nzmin(r)   zmax(r   r*   r+   r,   )r(   Zs_minZs_maxdiffr/   r   r   column_min_max_scaler   s   z=MinMaxScaler._transform_pandas.<locals>.column_min_max_scalerr1   )r   r&   rI   r   r/   r   r3      s   zMinMaxScaler._transform_pandasc                 C   r4   r5   r7   r/   r   r   r   r9      r:   zMinMaxScaler.__repr__r   r;   r   r   r   r   rB   |   s    $?rB   c                       r   )MaxAbsScalera@  Scale each column by its absolute max value.

    The general formula is given by

    .. math::

        x' = \frac{x}{\max{\vert x \vert}}

    where :math:`x` is the column and :math:`x'` is the transformed column. If
    :math:`\max{\vert x \vert} = 0` (i.e., the column contains all zeros), then the
    column is unmodified.

    .. tip::
        This is the recommended way to scale sparse data. If you data isn't sparse,
        you can use :class:`MinMaxScaler` or :class:`StandardScaler` instead.

    Examples:
        >>> import pandas as pd
        >>> import ray
        >>> from ray.data.preprocessors import MaxAbsScaler
        >>>
        >>> df = pd.DataFrame({"X1": [-6, 3], "X2": [2, -4], "X3": [0, 0]})   # noqa: E501
        >>> ds = ray.data.from_pandas(df)  # doctest: +SKIP
        >>> ds.to_pandas()  # doctest: +SKIP
           X1  X2  X3
        0  -6   2   0
        1   3  -4   0

        Columns are scaled separately.

        >>> preprocessor = MaxAbsScaler(columns=["X1", "X2"])
        >>> preprocessor.fit_transform(ds).to_pandas()  # doctest: +SKIP
            X1   X2  X3
        0 -1.0  0.5   0
        1  0.5 -1.0   0

        Zero-valued columns aren't scaled.

        >>> preprocessor = MaxAbsScaler(columns=["X3"])
        >>> preprocessor.fit_transform(ds).to_pandas()  # doctest: +SKIP
           X1  X2   X3
        0  -6   2  0.0
        1   3  -4  0.0

        >>> preprocessor = MaxAbsScaler(columns=["X1", "X2"], output_columns=["X1_scaled", "X2_scaled"])
        >>> preprocessor.fit_transform(ds).to_pandas()  # doctest: +SKIP
           X1  X2  X3  X1_scaled  X2_scaled
        0  -2  -3   1       -1.0       -1.0
        1   0  -3   1        0.0       -1.0
        2   2   3   1        1.0        1.0

    Args:
        columns: The columns to separately scale.
        output_columns: The names of the transformed columns. If None, the transformed
            columns will be the same as the input columns. If not None, the length of
            ``output_columns`` must match the length of ``columns``, othwerwise an error
            will be raised.
    Nr   r   c                    r   r   r   r   r   r   r   r     r   zMaxAbsScaler.__init__r    r   r!   c                 C   s    dd | j D }|j| | _| S )Nc                 S   s   g | ]}t |qS r   )r   )rC   r#   r   r   r   rD   "  s    z%MaxAbsScaler._fit.<locals>.<listcomp>)r   rE   r+   rF   r   r   r   r%   !  s   zMaxAbsScaler._fitr&   c                    r'   )Nr(   c                    s(    j d| j d }|dkrd}| | S )Nzabs_max(r)   r   r*   rG   )r(   Z	s_abs_maxr/   r   r   column_abs_max_scaler'  s   z=MaxAbsScaler._transform_pandas.<locals>.column_abs_max_scalerr1   )r   r&   rK   r   r/   r   r3   &  s   
zMaxAbsScaler._transform_pandasc                 C   r4   r5   r7   r/   r   r   r   r9   4  r:   zMaxAbsScaler.__repr__r   r;   r   r   r   r   rJ      s    $;rJ   c                	       sr   e Zd ZdZ		ddee deeef deee  f fddZ	d	d
de
fddZdejfddZdd Z  ZS )RobustScalera	  Scale and translate each column using quantiles.

    The general formula is given by

    .. math::
        x' = \frac{x - \mu_{1/2}}{\mu_h - \mu_l}

    where :math:`x` is the column, :math:`x'` is the transformed column,
    :math:`\mu_{1/2}` is the column median. :math:`\mu_{h}` and :math:`\mu_{l}` are the
    high and low quantiles, respectively. By default, :math:`\mu_{h}` is the third
    quartile and :math:`\mu_{l}` is the first quartile.

    .. tip::
        This scaler works well when your data contains many outliers.

    Examples:
        >>> import pandas as pd
        >>> import ray
        >>> from ray.data.preprocessors import RobustScaler
        >>>
        >>> df = pd.DataFrame({
        ...     "X1": [1, 2, 3, 4, 5],
        ...     "X2": [13, 5, 14, 2, 8],
        ...     "X3": [1, 2, 2, 2, 3],
        ... })
        >>> ds = ray.data.from_pandas(df)  # doctest: +SKIP
        >>> ds.to_pandas()  # doctest: +SKIP
           X1  X2  X3
        0   1  13   1
        1   2   5   2
        2   3  14   2
        3   4   2   2
        4   5   8   3

        :class:`RobustScaler` separately scales each column.

        >>> preprocessor = RobustScaler(columns=["X1", "X2"])
        >>> preprocessor.fit_transform(ds).to_pandas()  # doctest: +SKIP
            X1     X2  X3
        0 -1.0  0.625   1
        1 -0.5 -0.375   2
        2  0.0  0.750   2
        3  0.5 -0.750   2
        4  1.0  0.000   3

        >>> preprocessor = RobustScaler(
        ...    columns=["X1", "X2"],
        ...    output_columns=["X1_scaled", "X2_scaled"]
        ... )
        >>> preprocessor.fit_transform(ds).to_pandas()  # doctest: +SKIP
           X1  X2  X3  X1_scaled  X2_scaled
        0   1  13   1       -1.0      0.625
        1   2   5   2       -0.5     -0.375
        2   3  14   2        0.0      0.750
        3   4   2   2        0.5     -0.750
        4   5   8   3        1.0      0.000

    Args:
        columns: The columns to separately scale.
        quantile_range: A tuple that defines the lower and upper quantiles. Values
            must be between 0 and 1. Defaults to the 1st and 3rd quartiles:
            ``(0.25, 0.75)``.
        output_columns: The names of the transformed columns. If None, the transformed
            columns will be the same as the input columns. If not None, the length of
            ``output_columns`` must match the length of ``columns``, othwerwise an error
            will be raised.
    g      ?g      ?Nr   quantile_ranger   c                    s(   t    || _|| _t||| _d S r   )r   r   r   rN   r   r   r   )r   r   rN   r   r   r   r   r   ~  s   

zRobustScaler.__init__r    r   r!   c                    s   | j d }d}| j d }| }|d fdd|||fD }i | _| jD ]N |j fdddd	}| }||\}	}}}d
ddtfdd}
|
| }|
| }|
| }|| jd  d< || jd  d< || jd  d< q&| S )Nr   g      ?r*   c                    s   g | ]}t |  qS r   )int)rC   Z
percentile)	max_indexr   r   rD     s    z%RobustScaler._fit.<locals>.<listcomp>c                    s
   |  g S r   r   )r&   r"   r   r   r$     s   
 z#RobustScaler._fit.<locals>.<lambda>pandas)Zbatch_formatdsr   cc                 S   s   |  dd | S )Nr*   r   )Ztake)rR   rS   r   r   r   _get_first_value  s   z+RobustScaler._fit.<locals>._get_first_valuelow_quantile(r)   median(high_quantile()rN   countr+   r   Zmap_batchessortZsplit_at_indicesr?   )r   r    lowZmedhighZnum_recordsZsplit_indicesZfiltered_datasetZsorted_dataset_rT   Zlow_valZmed_valZhigh_valr   )r#   rP   r   r%     s*   






zRobustScaler._fitr&   c                    r'   )Nr(   c                    sb    j d| j d } j d| j d } j d| j d }|| }|dkr+t| S | | | S )NrU   r)   rV   rW   r   )r+   r,   r-   Z
zeros_like)r(   Zs_low_qZs_medianZs_high_qrH   r/   r   r   column_robust_scaler  s   
z<RobustScaler._transform_pandas.<locals>.column_robust_scalerr1   )r   r&   r]   r   r/   r   r3     s   zRobustScaler._transform_pandasc                 C   s&   | j j d| jd| jd| jdS )Nr6   z, quantile_range=z), output_columns=r)   )r   r8   r   rN   r   r/   r   r   r   r9     s   zRobustScaler.__repr__)rM   N)r8   r<   r=   r>   r   r?   r   floatr   r   r   r%   r2   r@   r3   r9   rA   r   r   r   r   rL   8  s    G

"rL   )typingr   r   r   r   numpyr-   rQ   r2   Zray.data.aggregater   r   r   r	   r
   Zray.data.preprocessorr   Zray.util.annotationsr   Zray.data.datasetr   r   rB   rJ   rL   r   r   r   r   <module>   s     m`Z