ó
‡ˆ\c           @   s…  d  Z  d d l m Z d d l Z d d l m Z d d l Z d d l m	 Z	 d d l
 m Z d d l m Z m Z m Z m Z d d	 l m Z m Z d d
 l m Z m Z m Z 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% d e e f d „  ƒ  YZ& d e' f d „  ƒ  YZ( d d „ Z* d e e f d „  ƒ  YZ+ e, d d „ Z- d S(   s'   Calibration of predicted probabilities.iÿÿÿÿ(   t   divisionN(   t   log(   t	   fmin_bfgs(   t   LabelEncoderi   (   t   BaseEstimatort   ClassifierMixint   RegressorMixint   clone(   t   label_binarizet   LabelBinarizer(   t	   check_X_yt   check_arrayt	   indexablet   column_or_1d(   t   check_is_fittedt   check_consistent_length(   t	   signature(   t   IsotonicRegression(   t	   LinearSVC(   t   check_cv(   t'   _check_binary_probabilistic_predictionst   CalibratedClassifierCVc           B   s>   e  Z d  Z d d d d „ Z d d „ Z d „  Z d „  Z RS(   sÜ  Probability calibration with isotonic regression or sigmoid.

    See glossary entry for :term:`cross-validation estimator`.

    With this class, the base_estimator is fit on the train set of the
    cross-validation generator and the test set is used for calibration.
    The probabilities for each of the folds are then averaged
    for prediction. In case that cv="prefit" is passed to __init__,
    it is assumed that base_estimator has been fitted already and all
    data is used for calibration. Note that data for fitting the
    classifier and for calibrating it must be disjoint.

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

    Parameters
    ----------
    base_estimator : instance BaseEstimator
        The classifier whose output decision function needs to be calibrated
        to offer more accurate predict_proba outputs. If cv=prefit, the
        classifier must have been fit already on data.

    method : 'sigmoid' or 'isotonic'
        The method to use for calibration. Can be 'sigmoid' which
        corresponds to Platt's method or 'isotonic' which is a
        non-parametric approach. It is not advised to use isotonic calibration
        with too few calibration samples ``(<<1000)`` since it tends to
        overfit.
        Use sigmoids (Platt's calibration) in this case.

    cv : integer, cross-validation generator, iterable or "prefit", optional
        Determines the cross-validation splitting strategy.
        Possible inputs for cv are:

        - None, to use the default 3-fold cross-validation,
        - integer, to specify the number of folds.
        - :term:`CV splitter`,
        - An iterable yielding (train, test) splits as arrays of indices.

        For integer/None inputs, if ``y`` is binary or multiclass,
        :class:`sklearn.model_selection.StratifiedKFold` is used. If ``y`` is
        neither binary nor multiclass, :class:`sklearn.model_selection.KFold`
        is used.

        Refer :ref:`User Guide <cross_validation>` for the various
        cross-validation strategies that can be used here.

        If "prefit" is passed, it is assumed that base_estimator has been
        fitted already and all data is used for calibration.

        .. versionchanged:: 0.20
            ``cv`` default value if None will change from 3-fold to 5-fold
            in v0.22.

    Attributes
    ----------
    classes_ : array, shape (n_classes)
        The class labels.

    calibrated_classifiers_ : list (len() equal to cv or 1 if cv == "prefit")
        The list of calibrated classifiers, one for each crossvalidation fold,
        which has been fitted on all but the validation fold and calibrated
        on the validation fold.

    References
    ----------
    .. [1] Obtaining calibrated probability estimates from decision trees
           and naive Bayesian classifiers, B. Zadrozny & C. Elkan, ICML 2001

    .. [2] Transforming Classifier Scores into Accurate Multiclass
           Probability Estimates, B. Zadrozny & C. Elkan, (KDD 2002)

    .. [3] Probabilistic Outputs for Support Vector Machines and Comparisons to
           Regularized Likelihood Methods, J. Platt, (1999)

    .. [4] Predicting Good Probabilities with Supervised Learning,
           A. Niculescu-Mizil & R. Caruana, ICML 2005
    t   sigmoidt   warnc         C   s   | |  _  | |  _ | |  _ d  S(   N(   t   base_estimatort   methodt   cv(   t   selfR   R   R   (    (    s2   lib/python2.7/site-packages/sklearn/calibration.pyt   __init__l   s    		c         C   s   t  | | d d d d g d t ƒ\ } } t | | ƒ \ } } t ƒ  j | ƒ } | j |  _ t |  j t ƒ rx |  j n! t	 |  j d ƒ r– |  j j
 n d } | rõ t j g  |  j D]! } t j | | k ƒ | k  ^ q² ƒ rõ t d | | f ƒ ‚ n  g  |  _ |  j d k rt d d	 ƒ } n	 |  j } |  j d
 k r‘t | d |  j ƒ} | d k	 rn| j | | | ƒ n | j | | ƒ |  j j | ƒ n‹t |  j | d t ƒ}	 t | j ƒ j }
 t | ƒ j } | d k	 rüd |
 k rüt j d | ƒ d } n4 | d k	 r*t | d t ƒ} t | | ƒ n  | } xé |	 j  | | ƒ D]Õ \ } } t! | ƒ } | d k	 rŒ| j | | | | d | | ƒn | j | | | | ƒ t | d |  j d |  j ƒ} | d k	 rð| j | | | | | | ƒ n | j | | | | ƒ |  j j | ƒ qCW|  S(   sÉ  Fit the calibrated model

        Parameters
        ----------
        X : array-like, shape (n_samples, n_features)
            Training data.

        y : array-like, shape (n_samples,)
            Target values.

        sample_weight : array-like, shape = [n_samples] or None
            Sample weights. If None, then samples are equally weighted.

        Returns
        -------
        self : object
            Returns an instance of self.
        t   accept_sparset   csct   csrt   coot   force_all_finitet   n_foldss^   Requesting %d-fold cross-validation but provided less than %d examples for at least one class.t   random_statei    t   prefitR   t
   classifiert   sample_weights\   %s does not support sample_weight. Samples weights are only used for the calibration itself.t	   ensure_2dt   classesN("   R
   t   FalseR   R	   t   fitt   classes_t
   isinstanceR   t   intt   hasattrR"   t   Nonet   npt   anyt   sumt
   ValueErrort   calibrated_classifiers_R   R   t   _CalibratedClassifierR   t   appendR   t   TrueR   t
   parameterst   typet   __name__t   warningsR   R   R   t   splitR   (   R   t   Xt   yR&   t   leR"   t   class_R   t   calibrated_classifierR   t   fit_parameterst   estimator_namet   base_estimator_sample_weightt   traint   testt   this_estimator(    (    s2   lib/python2.7/site-packages/sklearn/calibration.pyR*   q   sf    $	1				c         C   s   t  |  d d g ƒ t | d d d d g d t ƒ} t j | j d t |  j ƒ f ƒ } x* |  j D] } | j	 | ƒ } | | 7} qc W| t |  j ƒ } | S(	   s£  Posterior probabilities of classification

        This function returns posterior probabilities of classification
        according to each class on an array of test vectors X.

        Parameters
        ----------
        X : array-like, shape (n_samples, n_features)
            The samples.

        Returns
        -------
        C : array, shape (n_samples, n_classes)
            The predicted probas.
        R+   R4   R   R   R   R    R!   i    (
   R   R   R)   R0   t   zerost   shapet   lenR+   R4   t   predict_proba(   R   R=   t
   mean_probaRA   t   proba(    (    s2   lib/python2.7/site-packages/sklearn/calibration.pyRK   É   s    	%c         C   s6   t  |  d d g ƒ |  j t j |  j | ƒ d d ƒS(   sV  Predict the target of new samples. Can be different from the
        prediction of the uncalibrated classifier.

        Parameters
        ----------
        X : array-like, shape (n_samples, n_features)
            The samples.

        Returns
        -------
        C : array, shape (n_samples,)
            The predicted class.
        R+   R4   t   axisi   (   R   R+   R0   t   argmaxRK   (   R   R=   (    (    s2   lib/python2.7/site-packages/sklearn/calibration.pyt   predictç   s    N(   R:   t
   __module__t   __doc__R/   R   R*   RK   RP   (    (    (    s2   lib/python2.7/site-packages/sklearn/calibration.pyR      s
   MX	R5   c           B   s;   e  Z d  Z d d d „ Z d „  Z d d „ Z d „  Z RS(   s”  Probability calibration with isotonic regression or sigmoid.

    It assumes that base_estimator has already been fit, and trains the
    calibration on the input set of the fit function. Note that this class
    should not be used as an estimator directly. Use CalibratedClassifierCV
    with cv="prefit" instead.

    Parameters
    ----------
    base_estimator : instance BaseEstimator
        The classifier whose output decision function needs to be calibrated
        to offer more accurate predict_proba outputs. No default value since
        it has to be an already fitted estimator.

    method : 'sigmoid' | 'isotonic'
        The method to use for calibration. Can be 'sigmoid' which
        corresponds to Platt's method or 'isotonic' which is a
        non-parametric approach based on isotonic regression.

    classes : array-like, shape (n_classes,), optional
            Contains unique classes used to fit the base estimator.
            if None, then classes is extracted from the given target values
            in fit().

    See also
    --------
    CalibratedClassifierCV

    References
    ----------
    .. [1] Obtaining calibrated probability estimates from decision trees
           and naive Bayesian classifiers, B. Zadrozny & C. Elkan, ICML 2001

    .. [2] Transforming Classifier Scores into Accurate Multiclass
           Probability Estimates, B. Zadrozny & C. Elkan, (KDD 2002)

    .. [3] Probabilistic Outputs for Support Vector Machines and Comparisons to
           Regularized Likelihood Methods, J. Platt, (1999)

    .. [4] Predicting Good Probabilities with Supervised Learning,
           A. Niculescu-Mizil & R. Caruana, ICML 2005
    R   c         C   s   | |  _  | |  _ | |  _ d  S(   N(   R   R   R(   (   R   R   R   R(   (    (    s2   lib/python2.7/site-packages/sklearn/calibration.pyR   $  s    		c         C   sá   t  |  j ƒ } t |  j d ƒ ra |  j j | ƒ } | j d k r¿ | d  d  … t j f } q¿ n^ t |  j d ƒ r³ |  j j | ƒ } | d k r¿ | d  d  … d d  … f } q¿ n t	 d ƒ ‚ |  j
 j |  j j ƒ } | | f S(   Nt   decision_functioni   RK   i   s<   classifier has no decision_function or predict_proba method.(   RJ   R+   R.   R   RS   t   ndimR0   t   newaxisRK   t   RuntimeErrort   label_encoder_t	   transform(   R   R=   t	   n_classest   dft   idx_pos_class(    (    s2   lib/python2.7/site-packages/sklearn/calibration.pyt   _preproc)  s    "	c   
      C   s)  t  ƒ  |  _ |  j d k r. |  j j | ƒ n |  j j |  j ƒ |  j j |  _ t | |  j ƒ } |  j | ƒ \ } } g  |  _ x¢ t	 | | j
 ƒ D]Ž \ } } |  j d k rÀ t d d ƒ }	 n. |  j d k rÛ t ƒ  }	 n t d |  j ƒ ‚ |	 j | | d d … | f | ƒ |  j j |	 ƒ q“ W|  S(   sË  Calibrate the fitted model

        Parameters
        ----------
        X : array-like, shape (n_samples, n_features)
            Training data.

        y : array-like, shape (n_samples,)
            Target values.

        sample_weight : array-like, shape = [n_samples] or None
            Sample weights. If None, then samples are equally weighted.

        Returns
        -------
        self : object
            Returns an instance of self.
        t   isotonict   out_of_boundst   clipR   s1   method should be "sigmoid" or "isotonic". Got %s.N(   R   RW   R(   R/   R*   R+   R   R\   t   calibrators_t   zipt   TR   R   t   _SigmoidCalibrationR3   R6   (
   R   R=   R>   R&   t   YRZ   R[   t   kt   this_dft
   calibrator(    (    s2   lib/python2.7/site-packages/sklearn/calibration.pyR*   <  s$    	#c   	      C   s>  t  |  j ƒ } t j | j d | f ƒ } |  j | ƒ \ } } xa t | | j |  j ƒ D]G \ } } } | d k r | d 7} n  | j	 | ƒ | d d … | f <qY W| d k rÝ d | d d … d f | d d … d f <n, | t j
 | d d ƒd d … t j f } d | | t j | ƒ <d | d | k  | d k @<| S(	   s·  Posterior probabilities of classification

        This function returns posterior probabilities of classification
        according to each class on an array of test vectors X.

        Parameters
        ----------
        X : array-like, shape (n_samples, n_features)
            The samples.

        Returns
        -------
        C : array, shape (n_samples, n_classes)
            The predicted probas. Can be exact zeros.
        i    i   i   Ng      ð?RN   gñhãˆµøä>grÄZ|
 ð?(   RJ   R+   R0   RH   RI   R\   Ra   Rb   R`   RP   R2   RU   t   isnan(	   R   R=   RY   RM   RZ   R[   Re   Rf   Rg   (    (    s2   lib/python2.7/site-packages/sklearn/calibration.pyRK   i  s    %#-,N(   R:   RQ   RR   R/   R   R\   R*   RK   (    (    (    s2   lib/python2.7/site-packages/sklearn/calibration.pyR5   ù   s
   *	-c   	         s6  t  |  ƒ }  t  | ƒ } |  ‰  t j t j ƒ j ‰ t t j | d k ƒ ƒ } | j d | } t j | j ƒ ‰ | d | d ˆ | d k <d | d ˆ | d k <d ˆ ‰ ‡  ‡ ‡ ‡ ‡ f d †  } ‡  ‡ ‡ ‡ f d †  } t j d t	 | d | d ƒ g ƒ } t
 | | d | d t ƒ} | d | d	 f S(
   s:  Probability Calibration with sigmoid method (Platt 2000)

    Parameters
    ----------
    df : ndarray, shape (n_samples,)
        The decision function or predict proba for the samples.

    y : ndarray, shape (n_samples,)
        The targets.

    sample_weight : array-like, shape = [n_samples] or None
        Sample weights. If None, then samples are equally weighted.

    Returns
    -------
    a : float
        The slope.

    b : float
        The intercept.

    References
    ----------
    Platt, "Probabilistic Outputs for Support Vector Machines"
    i    g      ð?g       @c            s†   t  j |  d ˆ  |  d ƒ } d d | } ˆ t  j | ˆ ƒ ˆ t  j d | ˆ ƒ } ˆ d  k	 rx ˆ | j ƒ  S| j ƒ  Sd  S(   Ni    i   g      ð?(   R0   t   expR   R/   R2   (   t   ABt   Et   Pt   l(   t   FRb   t   T1R&   t   tiny(    s2   lib/python2.7/site-packages/sklearn/calibration.pyt	   objective»  s    1c            sŒ   t  j |  d ˆ  |  d ƒ } d d | } | ˆ | ˆ } ˆ d  k	 rX | ˆ 9} n  t  j | ˆ  ƒ } t  j | ƒ } t  j | | g ƒ S(   Ni    i   g      ð?(   R0   Ri   R/   t   dotR2   t   array(   Rj   Rk   Rl   t   TEP_minus_T1Pt   dAt   dB(   Rn   Rb   Ro   R&   (    s2   lib/python2.7/site-packages/sklearn/calibration.pyt   gradÅ  s    g        t   fprimet   dispi   (   R   R0   t   finfot   floatRp   R2   RI   RH   Rs   R   R   R)   (	   RZ   R>   R&   t   prior0t   prior1Rq   Rw   t   AB0t   AB_(    (   Rn   Rb   Ro   R&   Rp   s2   lib/python2.7/site-packages/sklearn/calibration.pyt   _sigmoid_calibration“  s    

'Rc   c           B   s#   e  Z d  Z d d „ Z d „  Z RS(   s†   Sigmoid regression model.

    Attributes
    ----------
    a_ : float
        The slope.

    b_ : float
        The intercept.
    c         C   sO   t  | ƒ } t  | ƒ } t | | ƒ \ } } t | | | ƒ \ |  _ |  _ |  S(   sÒ  Fit the model using X, y as training data.

        Parameters
        ----------
        X : array-like, shape (n_samples,)
            Training data.

        y : array-like, shape (n_samples,)
            Training target.

        sample_weight : array-like, shape = [n_samples] or None
            Sample weights. If None, then samples are equally weighted.

        Returns
        -------
        self : object
            Returns an instance of self.
        (   R   R   R€   t   a_t   b_(   R   R=   R>   R&   (    (    s2   lib/python2.7/site-packages/sklearn/calibration.pyR*   à  s
    c         C   s/   t  | ƒ } d d t j |  j | |  j ƒ S(   s  Predict new data by linear interpolation.

        Parameters
        ----------
        T : array-like, shape (n_samples,)
            Data to predict from.

        Returns
        -------
        T_ : array, shape (n_samples,)
            The predicted data.
        g      ð?(   R   R0   Ri   R   R‚   (   R   Rb   (    (    s2   lib/python2.7/site-packages/sklearn/calibration.pyRP   ú  s    N(   R:   RQ   RR   R/   R*   RP   (    (    (    s2   lib/python2.7/site-packages/sklearn/calibration.pyRc   Õ  s   
i   c         C   sM  t  |  ƒ }  t  | ƒ } | rE | | j ƒ  | j ƒ  | j ƒ  } n3 | j ƒ  d k  si | j ƒ  d k rx t d ƒ ‚ n  t |  | ƒ }  t j d d	 | d ƒ } t j | | ƒ d } t j | d | d t	 | ƒ ƒ} t j | d |  d t	 | ƒ ƒ} t j | d t	 | ƒ ƒ} | d k }	 | |	 | |	 }
 | |	 | |	 } |
 | f S(
   s¶  Compute true and predicted probabilities for a calibration curve.

    The method assumes the inputs come from a binary classifier.

    Calibration curves may also be referred to as reliability diagrams.

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

    Parameters
    ----------
    y_true : array, shape (n_samples,)
        True targets.

    y_prob : array, shape (n_samples,)
        Probabilities of the positive class.

    normalize : bool, optional, default=False
        Whether y_prob needs to be normalized into the bin [0, 1], i.e. is not
        a proper probability. If True, the smallest value in y_prob is mapped
        onto 0 and the largest one onto 1.

    n_bins : int
        Number of bins. A bigger number requires more data. Bins with no data
        points (i.e. without corresponding values in y_prob) will not be
        returned, thus there may be fewer than n_bins in the return value.

    Returns
    -------
    prob_true : array, shape (n_bins,) or smaller
        The true probability in each bin (fraction of positives).

    prob_pred : array, shape (n_bins,) or smaller
        The mean predicted probability in each bin.

    References
    ----------
    Alexandru Niculescu-Mizil and Rich Caruana (2005) Predicting Good
    Probabilities With Supervised Learning, in Proceedings of the 22nd
    International Conference on Machine Learning (ICML).
    See section 4 (Qualitative Analysis of Predictions).
    i    i   s?   y_prob has values outside [0, 1] and normalize is set to False.g        g      ð?g:Œ0âŽyE>t   weightst	   minlengthgÜ1¯  ð?(
   R   t   mint   maxR3   R   R0   t   linspacet   digitizet   bincountRJ   (   t   y_truet   y_probt	   normalizet   n_binst   binst   binidst   bin_sumst   bin_truet	   bin_totalt   nonzerot	   prob_truet	   prob_pred(    (    s2   lib/python2.7/site-packages/sklearn/calibration.pyt   calibration_curve  s     *'$!!(.   RR   t
   __future__R    R;   t   mathR   t   numpyR0   t   scipy.optimizeR   t   sklearn.preprocessingR   t   baseR   R   R   R   t   preprocessingR   R	   t   utilsR
   R   R   R   t   utils.validationR   R   t   utils.fixesR   R]   R   t   svmR   t   model_selectionR   t   metrics.classificationR   R   t   objectR5   R/   R€   Rc   R)   R–   (    (    (    s2   lib/python2.7/site-packages/sklearn/calibration.pyt   <module>   s(   	""ÛšB6