Ë
    8Ò^jq=  ã                   ó>  — d Z ddlZddlmZ ddlmZmZ ddlZddl	m
Z
 ddl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 ddlmZ ddlmZ ddlmZmZ ddlm Z   ejB                  ejD                  «      jF                  Z$d„ Z%dd„Z&d„ Z'd„ Z( G d„ dee«      Z)y)z<
A Theil-Sen Estimator for Multiple Linear Regression Model
é    N)Úcombinations)ÚIntegralÚReal)Úeffective_n_jobs)Úlinalg)Úget_lapack_funcs)Úbinom)ÚRegressorMixinÚ_fit_context)ÚConvergenceWarning)ÚLinearModel)Úcheck_random_state)ÚInterval)ÚParallelÚdelayed)Úvalidate_datac                 óF  — | |z
  }t        j                  t        j                  |dz  d¬«      «      }|t        k\  }t	        |j                  «       | j
                  d   k  «      }||   }||   dd…t         j                  f   }t        j                  t        j                  ||z  d¬«      «      }|t        kD  r=t        j                  | |dd…f   |z  d¬«      t        j                  d|z  d¬«      z  }nd}d}t        dd||z  z
  «      |z  t        d||z  «      |z  z   S )u	  Modified Weiszfeld step.

    This function defines one iteration step in order to approximate the
    spatial median (L1 median). It is a form of an iteratively re-weighted
    least squares method.

    Parameters
    ----------
    X : array-like of shape (n_samples, n_features)
        Training vector, where `n_samples` is the number of samples and
        `n_features` is the number of features.

    x_old : ndarray of shape = (n_features,)
        Current start vector.

    Returns
    -------
    x_new : ndarray of shape (n_features,)
        New iteration step.

    References
    ----------
    - On Computation of Spatial Median for Robust Data Mining, 2005
      T. KÃ¤rkkÃ¤inen and S. Ã„yrÃ¤mÃ¶
      http://users.jyu.fi/~samiayr/pdf/ayramo_eurogen05.pdf
    é   é   ©Úaxisr   Ng      ð?ç        )ÚnpÚsqrtÚsumÚ_EPSILONÚintÚshapeÚnewaxisr   ÚnormÚmaxÚmin)ÚXÚx_oldÚdiffÚ	diff_normÚmaskÚis_x_old_in_XÚquotient_normÚnew_directions           új/var/www/ramen.bs-engineer-server.com/venv/lib/python3.12/site-packages/sklearn/linear_model/_theil_sen.pyÚ_modified_weiszfeld_stepr,      s  € ð6 ˆu‰9€DÜ—‘œŸ™˜t Q™w¨QÔ/Ó0€IØœÑ €Dä˜Ÿ™›
 Q§W¡W¨Q¡ZÑ/Ó0€Mà�‰:€DØ˜$‘¢¤2§:¡: Ñ.€IÜ—K‘K¤§¡ t¨iÑ'7¸aÔ @ÓA€Mà”xÒÜŸ™˜q ¢q ™z¨IÑ5¸AÔ>ÄÇÁØ�	‰M ôB
ñ 
‰ð ˆØˆô 	ˆC��} }Ñ4Ñ4Ó5¸ÑEÜ
ˆc�= =Ñ0Ó
1°EÑ
9ñ	:ðó    c                 óŠ  — | j                   d   dk(  r'dt        j                  | j                  «       d¬«      fS |dz  }t        j                  | d¬«      }t        |«      D ]3  }t        | |«      }t        j                  ||z
  dz  «      |k  r ||fS |}Œ5 t        j                  dj                  |¬«      t        «       fS )	u	  Spatial median (L1 median).

    The spatial median is member of a class of so-called M-estimators which
    are defined by an optimization problem. Given a number of p points in an
    n-dimensional space, the point x minimizing the sum of all distances to the
    p other points is called spatial median.

    Parameters
    ----------
    X : array-like of shape (n_samples, n_features)
        Training vector, where `n_samples` is the number of samples and
        `n_features` is the number of features.

    max_iter : int, default=300
        Maximum number of iterations.

    tol : float, default=1.e-3
        Stop the algorithm if spatial_median has converged.

    Returns
    -------
    spatial_median : ndarray of shape = (n_features,)
        Spatial median.

    n_iter : int
        Number of iterations needed.

    References
    ----------
    - On Computation of Spatial Median for Robust Data Mining, 2005
      T. KÃ¤rkkÃ¤inen and S. Ã„yrÃ¤mÃ¶
      http://users.jyu.fi/~samiayr/pdf/ayramo_eurogen05.pdf
    r   T)Úkeepdimsr   r   r   zYMaximum number of iterations {max_iter} reached in spatial median for TheilSen regressor.)Úmax_iter)r   r   ÚmedianÚravelÚmeanÚranger,   r   ÚwarningsÚwarnÚformatr   )r#   r0   ÚtolÚspatial_median_oldÚn_iterÚspatial_medians         r+   Ú_spatial_medianr<   P   sÍ   € ðD 	‡w�wˆq�z�Q‚Ø”"—)‘)˜AŸG™G›I°Ô5Ð5Ð5àˆA�I€CÜŸ™ ¨Ô+Ðä˜“/ò 
ˆÜ1°!Ð5GÓHˆÜ�6‰6Ð%¨Ñ6¸1Ñ<Ó=ÀÒCØð �>Ð!Ð!ð "0Ñð
ô 	�‰ðç‰v˜xˆvÓ(Üô		
ð �>Ð!Ð!r-   c                 ó<   — ddd|z  z  | |z
  dz   z  |z   dz
  | z  z
  S )a  Approximation of the breakdown point.

    Parameters
    ----------
    n_samples : int
        Number of samples.

    n_subsamples : int
        Number of subsamples to consider.

    Returns
    -------
    breakdown_point : float
        Approximation of breakdown point.
    r   g      à?© )Ú	n_samplesÚn_subsampless     r+   Ú_breakdown_pointrA   ˆ   sG   € ð" 	
à�A˜Ñ$Ñ%¨°\Ñ)AÀAÑ)EÑFØñàñð ññ	ðr-   c                 ó°  — t        |«      }| j                  d   |z   }|j                  d   }t        j                  |j                  d   |f«      }t        j                  ||f«      }t        j
                  t        ||«      «      }t        d||f«      \  }	t        |«      D ]1  \  }
}| |dd…f   |dd…|d…f<   ||   |d|  |	||«      d   d| ||
<   Œ3 |S )a�  Least Squares Estimator for TheilSenRegressor class.

    This function calculates the least squares method on a subset of rows of X
    and y defined by the indices array. Optionally, an intercept column is
    added if intercept is set to true.

    Parameters
    ----------
    X : array-like of shape (n_samples, n_features)
        Design matrix, where `n_samples` is the number of samples and
        `n_features` is the number of features.

    y : ndarray of shape (n_samples,)
        Target vector, where `n_samples` is the number of samples.

    indices : ndarray of shape (n_subpopulation, n_subsamples)
        Indices of all subsamples with respect to the chosen subpopulation.

    fit_intercept : bool
        Fit intercept or not.

    Returns
    -------
    weights : ndarray of shape (n_subpopulation, n_features + intercept)
        Solution matrix of n_subpopulation solved least square problems.
    r   r   )ÚgelssN)	r   r   r   ÚemptyÚonesÚzerosr!   r   Ú	enumerate)r#   ÚyÚindicesÚfit_interceptÚ
n_featuresr@   ÚweightsÚX_subpopulationÚy_subpopulationÚlstsqÚindexÚsubsets               r+   Ú_lstsqrR   £   së   € ô6 ˜Ó&€MØ—‘˜‘˜mÑ+€JØ—=‘= Ñ#€LÜ�h‰h˜Ÿ™ aÑ(¨*Ð5Ó6€GÜ—g‘g˜|¨ZÐ8Ó9€Oä—h‘h¤ L°*Ó =Ó?€OÜ 
¨_¸oÐ,NÓO�H€Uä" 7Ó+ò Q‰ˆˆvØ-.¨v²q¨y©\ˆš˜=™>Ð)Ñ*Ø)*¨6©ˆ˜˜Ð&Ù˜°Ó@ÀÑCÀKÀZÐPˆ�ŠðQð
 €Nr-   c            
       óÀ   — e Zd ZU dZdg eeddd¬«      gdeg eeddd¬«      g eeddd¬«      gd	gdegd
gdœZee	d<   dddddddddœd„Z
d„ Z ed¬«      d„ «       Zy)ÚTheilSenRegressoraë  Theil-Sen Estimator: robust multivariate regression model.

    The algorithm calculates least square solutions on subsets with size
    n_subsamples of the samples in X. Any value of n_subsamples between the
    number of features and samples leads to an estimator with a compromise
    between robustness and efficiency. Since the number of least square
    solutions is "n_samples choose n_subsamples", it can be extremely large
    and can therefore be limited with max_subpopulation. If this limit is
    reached, the subsets are chosen randomly. In a final step, the spatial
    median (or L1 median) is calculated of all least square solutions.

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

    Parameters
    ----------
    fit_intercept : bool, default=True
        Whether to calculate the intercept for this model. If set
        to false, no intercept will be used in calculations.

    max_subpopulation : int, default=1e4
        Instead of computing with a set of cardinality 'n choose k', where n is
        the number of samples and k is the number of subsamples (at least
        number of features), consider only a stochastic subpopulation of a
        given maximal size if 'n choose k' is larger than max_subpopulation.
        For other than small problem sizes this parameter will determine
        memory usage and runtime if n_subsamples is not changed. Note that the
        data type should be int but floats such as 1e4 can be accepted too.

    n_subsamples : int, default=None
        Number of samples to calculate the parameters. This is at least the
        number of features (plus 1 if fit_intercept=True) and the number of
        samples as a maximum. A lower number leads to a higher breakdown
        point and a low efficiency while a high number leads to a low
        breakdown point and a high efficiency. If None, take the
        minimum number of subsamples leading to maximal robustness.
        If n_subsamples is set to n_samples, Theil-Sen is identical to least
        squares.

    max_iter : int, default=300
        Maximum number of iterations for the calculation of spatial median.

    tol : float, default=1e-3
        Tolerance when calculating spatial median.

    random_state : int, RandomState instance or None, default=None
        A random number generator instance to define the state of the random
        permutations generator. Pass an int for reproducible output across
        multiple function calls.
        See :term:`Glossary <random_state>`.

    n_jobs : int, default=None
        Number of CPUs to use during the cross validation.
        ``None`` means 1 unless in a :obj:`joblib.parallel_backend` context.
        ``-1`` means using all processors. See :term:`Glossary <n_jobs>`
        for more details.

    verbose : bool, default=False
        Verbose mode when fitting the model.

    Attributes
    ----------
    coef_ : ndarray of shape (n_features,)
        Coefficients of the regression model (median of distribution).

    intercept_ : float
        Estimated intercept of regression model.

    breakdown_ : float
        Approximated breakdown point.

    n_iter_ : int
        Number of iterations needed for the spatial median.

    n_subpopulation_ : int
        Number of combinations taken into account from 'n choose k', where n is
        the number of samples and k is the number of subsamples.

    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
    --------
    HuberRegressor : Linear regression model that is robust to outliers.
    RANSACRegressor : RANSAC (RANdom SAmple Consensus) algorithm.
    SGDRegressor : Fitted by minimizing a regularized empirical loss with SGD.

    References
    ----------
    - Theil-Sen Estimators in a Multiple Linear Regression Model, 2009
      Xin Dang, Hanxiang Peng, Xueqin Wang and Heping Zhang
      http://home.olemiss.edu/~xdang/papers/MTSE.pdf

    Examples
    --------
    >>> from sklearn.linear_model import TheilSenRegressor
    >>> from sklearn.datasets import make_regression
    >>> X, y = make_regression(
    ...     n_samples=200, n_features=2, noise=4.0, random_state=0)
    >>> reg = TheilSenRegressor(random_state=0).fit(X, y)
    >>> reg.score(X, y)
    0.9884
    >>> reg.predict(X[:1,])
    array([-31.5871])
    Úbooleanr   NÚleft)Úclosedr   r   Úrandom_stateÚverbose©rJ   Úmax_subpopulationr@   r0   r8   rX   Ún_jobsrY   Ú_parameter_constraintsTg     ˆÃ@é,  çü©ñÒMbP?Fc                ót   — || _         || _        || _        || _        || _        || _        || _        || _        y ©NrZ   )	ÚselfrJ   r[   r@   r0   r8   rX   r\   rY   s	            r+   Ú__init__zTheilSenRegressor.__init__M  s@   € ð +ˆÔØ!2ˆÔØ(ˆÔØ ˆŒØˆŒØ(ˆÔØˆŒØˆ�r-   c           	      óâ  — | j                   }| j                  r|dz   }n|}|�v||kD  rt        dj                  ||«      «      ‚||k\  r1||kD  rX| j                  rdnd}t        dj                  |||«      «      ‚||k7  r't        dj                  ||«      «      ‚t	        ||«      }t        dt        j                  t        ||«      «      «      }t        t	        | j                  |«      «      }||fS )Nr   z=Invalid parameter since n_subsamples > n_samples ({0} > {1}).z+1Ú zAInvalid parameter since n_features{0} > n_subsamples ({1} > {2}).z\Invalid parameter since n_subsamples != n_samples ({0} != {1}) while n_samples < n_features.)r@   rJ   Ú
ValueErrorr7   r"   r!   r   Úrintr	   r   r[   )rb   r?   rK   r@   Ún_dimÚplus_1Úall_combinationsÚn_subpopulations           r+   Ú_check_subparamsz"TheilSenRegressor._check_subparamsb  s  € Ø×(Ñ(ˆà×ÒØ ‘N‰EàˆEàÐ#Ø˜iÒ'Ü ð-ß-3©V°LÀ)Ó-Lóð ð ˜JÒ&Ø˜<Ò'Ø%)×%7Ò%7™T¸R�FÜ$ðç!™6 &¨%°Ó>óð ð   9Ò,Ü$ð(ç(.©¨|¸YÓ(Góð ô ˜u iÓ0ˆLä˜q¤"§'¡'¬%°	¸<Ó*HÓ"IÓJÐÜœc $×"8Ñ"8Ð:JÓKÓLˆà˜_Ð,Ð,r-   )Úprefer_skip_nested_validationc                 ó°  ‡ ‡‡‡— t        ‰ j                  «      }t        ‰ ‰‰d¬«      \  ŠŠ‰j                  \  }}‰ j	                  ||«      \  }‰ _        t        ||«      ‰ _        ‰ j                  r”t        dj                  ‰ j                  «      «       t        dj                  |«      «       t        ‰ j                  |z  «      }t        dj                  |«      «       t        dj                  ‰ j
                  «      «       t        j                  t        ||«      «      ‰ j                  k  rt!        t#        t%        |«      |«      «      }n4t%        ‰ j
                  «      D �	cg c]  }	|j'                  ||d¬«      ‘Œ }}	t)        ‰ j*                  «      }
t        j,                  ||
«      Š t/        |
‰ j                  ¬	«      ˆˆˆ ˆfd
„t%        |
«      D «       «      }t        j0                  |«      }t3        |‰ j4                  ‰ j6                  ¬«      \  ‰ _        }‰ j:                  r|d   ‰ _        |dd ‰ _        ‰ S d‰ _        |‰ _        ‰ S c c}	w )aU  Fit linear model.

        Parameters
        ----------
        X : ndarray of shape (n_samples, n_features)
            Training data.
        y : ndarray of shape (n_samples,)
            Target values.

        Returns
        -------
        self : returns an instance of self.
            Fitted `TheilSenRegressor` estimator.
        T)Ú	y_numericzBreakdown point: {0}zNumber of samples: {0}zTolerable outliers: {0}zNumber of subpopulations: {0}F)ÚsizeÚreplace)r\   rY   c              3   óh   •K  — | ])  } t        t        «      ‰‰‰|   ‰j                  «      –— Œ+ y ­wra   )r   rR   rJ   )Ú.0Újobr#   Ú
index_listrb   rH   s     €€€€r+   ú	<genexpr>z(TheilSenRegressor.fit.<locals>.<genexpr>±  s6   øè ø€ ò @
àð ŒG”F‹O˜A˜q *¨S¡/°4×3EÑ3E×Fñ@
ùs   ƒ/2)r0   r8   r   r   Nr   ) r   rX   r   r   rl   Ún_subpopulation_rA   Ú
breakdown_rY   Úprintr7   r   r   rg   r	   r[   Úlistr   r4   Úchoicer   r\   Úarray_splitr   Úvstackr<   r0   r8   Ún_iter_rJ   Ú
intercept_Úcoef_)rb   r#   rH   rX   r?   rK   r@   Útol_outliersrI   Ú_r\   rL   Úcoefsru   s   ```          @r+   ÚfitzTheilSenRegressor.fit‡  s  û€ ô  *¨$×*;Ñ*;Ó<ˆÜ˜T 1 a°4Ô8‰ˆˆ1Ø !§¡Ñˆ	�:Ø.2×.CÑ.CØ�zó/
Ñ+ˆ�dÔ+ô +¨9°lÓCˆŒà�<Š<ÜÐ(×/Ñ/°·±Ó@ÔAÜÐ*×1Ñ1°)Ó<Ô=Ü˜tŸ™°Ñ:Ó;ˆLÜÐ+×2Ñ2°<Ó@ÔAÜÐ1×8Ñ8¸×9NÑ9NÓOÔPô �7‰7”5˜ LÓ1Ó2°d×6LÑ6LÒLÜœ<¬¨iÓ(8¸,ÓGÓH‰Gô ˜t×4Ñ4Ó5öàð ×#Ñ# I°LÈ%Ð#ÕPðˆGð ô
 " $§+¡+Ó.ˆÜ—^‘^ G¨VÓ4ˆ
Ø?”( &°$·,±,Ô?ö @
ä˜V“}ô@
ó 
ˆô —)‘)˜GÓ$ˆÜ-Ø˜dŸm™m°·±ô
ÑˆŒ�eð ×ÒØ# A™hˆDŒOØ˜q˜r˜ˆDŒJð
 ˆð "ˆDŒOØˆDŒJàˆùò/s   Å(I)Ú__name__Ú
__module__Ú__qualname__Ú__doc__r   r   r   r]   ÚdictÚ__annotations__rc   rl   r   r„   r>   r-   r+   rT   rT   Ï   s«   … ñoðd $˜á& t¨Q°¸VÔDÐEØ˜xÐ(Ù˜h¨¨4¸Ô?Ð@Ù˜˜s D°Ô8Ð9Ø'Ð(Ø˜Ð"Ø�;ñ
$Ð˜Dó 
ð ØØØØØØØôò*#-ñJ °Ô5ñ9ó 6ñ9r-   rT   )r^   r_   )*rˆ   r5   Ú	itertoolsr   Únumbersr   r   Únumpyr   Újoblibr   Úscipyr   Úscipy.linalg.lapackr   Úscipy.specialr	   Úsklearn.baser
   r   Úsklearn.exceptionsr   Úsklearn.linear_model._baser   Úsklearn.utilsr   Úsklearn.utils._param_validationr   Úsklearn.utils.parallelr   r   Úsklearn.utils.validationr   ÚfinfoÚdoubleÚepsr   r,   r<   rA   rR   rT   r>   r-   r+   ú<module>rœ      sz   ðñó Ý "ß "ã Ý #Ý Ý 0Ý ç 5Ý 1Ý 2Ý ,Ý 4ß 4Ý 2àˆ2�8‰8�B—I‘IÓ×"Ñ"€ò0óf5"òpò6)ôXr˜¨õ rr-   