ó
‡ˆ\c           @   s¥  d  Z  d d l Z d d l m Z m Z d d l 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 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 d d d g Z d e j e e
 e ƒ f d „  ƒ  YZ  d e  f d „  ƒ  YZ! d Z" d e  f d „  ƒ  YZ# d e# f d „  ƒ  YZ$ d e# f d „  ƒ  YZ% d e# f d „  ƒ  YZ& d S(   sÇ   
The :mod:`sklearn.naive_bayes` module implements Naive Bayes algorithms. These
are supervised learning methods based on applying Bayes' theorem with strong
(naive) feature independence assumptions.
iÿÿÿÿN(   t   ABCMetat   abstractmethod(   t   issparsei   (   t   BaseEstimatort   ClassifierMixin(   t   binarize(   t   LabelBinarizer(   t   label_binarize(   t	   check_X_yt   check_arrayt   check_consistent_length(   t   safe_sparse_dot(   t	   logsumexp(   t   _check_partial_fit_first_call(   t   check_is_fitted(   t   sixt   BernoulliNBt
   GaussianNBt   MultinomialNBt   ComplementNBt   BaseNBc           B   s8   e  Z d  Z e d „  ƒ Z d „  Z d „  Z d „  Z RS(   s.   Abstract base class for naive Bayes estimatorsc         C   s   d S(   s(  Compute the unnormalized posterior log probability of X

        I.e. ``log P(c) + log P(x|c)`` for all rows x of X, as an array-like of
        shape [n_classes, n_samples].

        Input is passed to _joint_log_likelihood as-is by predict,
        predict_proba and predict_log_proba.
        N(    (   t   selft   X(    (    s2   lib/python2.7/site-packages/sklearn/naive_bayes.pyt   _joint_log_likelihood*   s    c         C   s)   |  j  | ƒ } |  j t j | d d ƒS(   s  
        Perform classification on an array of test vectors X.

        Parameters
        ----------
        X : array-like, shape = [n_samples, n_features]

        Returns
        -------
        C : array, shape = [n_samples]
            Predicted target values for X
        t   axisi   (   R   t   classes_t   npt   argmax(   R   R   t   jll(    (    s2   lib/python2.7/site-packages/sklearn/naive_bayes.pyt   predict5   s    c         C   s5   |  j  | ƒ } t | d d ƒ} | t j | ƒ j S(   sÏ  
        Return log-probability estimates for the test vector X.

        Parameters
        ----------
        X : array-like, shape = [n_samples, n_features]

        Returns
        -------
        C : array-like, shape = [n_samples, n_classes]
            Returns the log-probability of the samples for each class in
            the model. The columns correspond to the classes in sorted
            order, as they appear in the attribute `classes_`.
        R   i   (   R   R   R   t
   atleast_2dt   T(   R   R   R   t
   log_prob_x(    (    s2   lib/python2.7/site-packages/sklearn/naive_bayes.pyt   predict_log_probaE   s    c         C   s   t  j |  j | ƒ ƒ S(   sÇ  
        Return probability estimates for the test vector X.

        Parameters
        ----------
        X : array-like, shape = [n_samples, n_features]

        Returns
        -------
        C : array-like, shape = [n_samples, n_classes]
            Returns the probability of the samples for each class in
            the model. The columns correspond to the classes in sorted
            order, as they appear in the attribute `classes_`.
        (   R   t   expR!   (   R   R   (    (    s2   lib/python2.7/site-packages/sklearn/naive_bayes.pyt   predict_probaY   s    (   t   __name__t
   __module__t   __doc__R   R   R   R!   R#   (    (    (    s2   lib/python2.7/site-packages/sklearn/naive_bayes.pyR   '   s
   		c           B   se   e  Z d  Z d d d „ Z d d „ Z e d d „ ƒ Z d d d „ Z d e	 d d „ Z
 d „  Z RS(	   s  
    Gaussian Naive Bayes (GaussianNB)

    Can perform online updates to model parameters via `partial_fit` method.
    For details on algorithm used to update feature means and variance online,
    see Stanford CS tech report STAN-CS-79-773 by Chan, Golub, and LeVeque:

        http://i.stanford.edu/pub/cstr/reports/cs/tr/79/773/CS-TR-79-773.pdf

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

    Parameters
    ----------
    priors : array-like, shape (n_classes,)
        Prior probabilities of the classes. If specified the priors are not
        adjusted according to the data.

    var_smoothing : float, optional (default=1e-9)
        Portion of the largest variance of all features that is added to
        variances for calculation stability.

    Attributes
    ----------
    class_prior_ : array, shape (n_classes,)
        probability of each class.

    class_count_ : array, shape (n_classes,)
        number of training samples observed in each class.

    theta_ : array, shape (n_classes, n_features)
        mean of each feature per class

    sigma_ : array, shape (n_classes, n_features)
        variance of each feature per class

    epsilon_ : float
        absolute additive value to variances

    Examples
    --------
    >>> import numpy as np
    >>> X = np.array([[-1, -1], [-2, -1], [-3, -2], [1, 1], [2, 1], [3, 2]])
    >>> Y = np.array([1, 1, 1, 2, 2, 2])
    >>> from sklearn.naive_bayes import GaussianNB
    >>> clf = GaussianNB()
    >>> clf.fit(X, Y)
    GaussianNB(priors=None, var_smoothing=1e-09)
    >>> print(clf.predict([[-0.8, -1]]))
    [1]
    >>> clf_pf = GaussianNB()
    >>> clf_pf.partial_fit(X, Y, np.unique(Y))
    GaussianNB(priors=None, var_smoothing=1e-09)
    >>> print(clf_pf.predict([[-0.8, -1]]))
    [1]
    g•Ö&è.>c         C   s   | |  _  | |  _ d  S(   N(   t   priorst   var_smoothing(   R   R'   R(   (    (    s2   lib/python2.7/site-packages/sklearn/naive_bayes.pyt   __init__¤   s    	c         C   s=   t  | | ƒ \ } } |  j | | t j | ƒ d t d | ƒS(   s’  Fit Gaussian Naive Bayes according to X, y

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

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

        sample_weight : array-like, shape (n_samples,), optional (default=None)
            Weights applied to individual samples (1. for unweighted).

            .. versionadded:: 0.17
               Gaussian Naive Bayes supports fitting with *sample_weight*.

        Returns
        -------
        self : object
        t   _refitt   sample_weight(   R   t   _partial_fitR   t   uniquet   True(   R   R   t   yR+   (    (    s2   lib/python2.7/site-packages/sklearn/naive_bayes.pyt   fit¨   s    !c         C   sO  | j  d d k r | | f S| d k	 r„ t | j ƒ  ƒ } t j | d d d | | ƒ} t j | | d d d d | | ƒ} n7 | j  d } t j | d d ƒ} t j | d d ƒ} |  d k rÑ | | f St |  | ƒ } | | |  | | }	 |  | }
 | | } |
 | |  t | | ƒ | | | | d } | | } |	 | f S(   s  Compute online update of Gaussian mean and variance.

        Given starting sample count, mean, and variance, a new set of
        points X, and optionally sample weights, return the updated mean and
        variance. (NB - each dimension (column) in X is treated as independent
        -- you get variance, not covariance).

        Can take scalar mean and variance, or vector mean and variance to
        simultaneously update a number of independent Gaussians.

        See Stanford CS tech report STAN-CS-79-773 by Chan, Golub, and LeVeque:

        http://i.stanford.edu/pub/cstr/reports/cs/tr/79/773/CS-TR-79-773.pdf

        Parameters
        ----------
        n_past : int
            Number of samples represented in old mean and variance. If sample
            weights were given, this should contain the sum of sample
            weights represented in old mean and variance.

        mu : array-like, shape (number of Gaussians,)
            Means for Gaussians in original set.

        var : array-like, shape (number of Gaussians,)
            Variances for Gaussians in original set.

        sample_weight : array-like, shape (n_samples,), optional (default=None)
            Weights applied to individual samples (1. for unweighted).

        Returns
        -------
        total_mu : array-like, shape (number of Gaussians,)
            Updated mean for each Gaussian over the combined set.

        total_var : array-like, shape (number of Gaussians,)
            Updated variance for each Gaussian over the combined set.
        i    R   t   weightsi   N(   t   shapet   Nonet   floatt   sumR   t   averaget   vart   mean(   t   n_pastt   muR7   R   R+   t   n_newt   new_mut   new_vart   n_totalt   total_mut   old_ssdt   new_ssdt	   total_ssdt	   total_var(    (    s2   lib/python2.7/site-packages/sklearn/naive_bayes.pyt   _update_mean_varianceÂ   s*    (




c         C   s   |  j  | | | d t d | ƒS(   s\  Incremental fit on a batch of samples.

        This method is expected to be called several times consecutively
        on different chunks of a dataset so as to implement out-of-core
        or online learning.

        This is especially useful when the whole dataset is too big to fit in
        memory at once.

        This method has some performance and numerical stability overhead,
        hence it is better to call partial_fit on chunks of data that are
        as large as possible (as long as fitting in the memory budget) to
        hide the overhead.

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

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

        classes : array-like, shape (n_classes,), optional (default=None)
            List of all the classes that can possibly appear in the y vector.

            Must be provided at the first call to partial_fit, can be omitted
            in subsequent calls.

        sample_weight : array-like, shape (n_samples,), optional (default=None)
            Weights applied to individual samples (1. for unweighted).

            .. versionadded:: 0.17

        Returns
        -------
        self : object
        R*   R+   (   R,   t   False(   R   R   R/   t   classesR+   (    (    s2   lib/python2.7/site-packages/sklearn/naive_bayes.pyt   partial_fit  s    'c         C   sÝ  t  | | ƒ \ } } | d k	 rC t | d t ƒ} t | | ƒ n  |  j t j | d d ƒj ƒ  |  _	 | rz d |  _
 n  t |  | ƒ r­| j d } t |  j
 ƒ } t j | | f ƒ |  _ t j | | f ƒ |  _ t j | d t j ƒ|  _ |  j d k	 r†t j |  j ƒ } t | ƒ | k r2t d ƒ ‚ n  t j | j ƒ  d ƒ sYt d ƒ ‚ n  | d k  j ƒ  rzt d	 ƒ ‚ n  | |  _ q"t j t |  j
 ƒ d t j ƒ|  _ nu | j d |  j j d k rúd
 }	 t |	 | j d |  j j d f ƒ ‚ n  |  j d d … d d … f c |  j	 8<|  j
 } t j | ƒ }
 t j |
 | ƒ } t j | ƒ syt d |
 | | f ƒ ‚ n  x
|
 D]} | j | ƒ } | | | k d d … f } | d k	 rÜ| | | k } | j ƒ  } n d } | j d } |  j |  j | |  j | d d … f |  j | d d … f | | ƒ \ } } | |  j | d d … f <| |  j | d d … f <|  j | c | 7<q€W|  j d d … d d … f c |  j	 7<|  j d k rÙ|  j |  j j ƒ  |  _ n  |  S(   sñ  Actual implementation of Gaussian NB fitting.

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

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

        classes : array-like, shape (n_classes,), optional (default=None)
            List of all the classes that can possibly appear in the y vector.

            Must be provided at the first call to partial_fit, can be omitted
            in subsequent calls.

        _refit : bool, optional (default=False)
            If true, act as though this were the first time we called
            _partial_fit (ie, throw away any past fitting and start over).

        sample_weight : array-like, shape (n_samples,), optional (default=None)
            Weights applied to individual samples (1. for unweighted).

        Returns
        -------
        self : object
        t	   ensure_2dR   i    i   t   dtypes.   Number of priors must match number of classes.g      ð?s"   The sum of the priors should be 1.s   Priors must be non-negative.s6   Number of features %d does not match previous data %d.NsB   The target label(s) %s in y do not exist in the initial classes %s(   R   R3   R	   RE   R
   R(   R   R7   t   maxt   epsilon_R   R   R2   t   lent   zerost   theta_t   sigma_t   float64t   class_count_R'   t   asarrayt
   ValueErrort   iscloseR5   t   anyt   class_prior_R-   t   in1dt   allt   searchsortedRD   (   R   R   R/   RF   R*   R+   t
   n_featurest	   n_classesR'   t   msgt   unique_yt   unique_y_in_classest   y_it   it   X_it   sw_it   N_it	   new_thetat	   new_sigma(    (    s2   lib/python2.7/site-packages/sklearn/naive_bayes.pyR,   7  sh    %*(	6(c      	   C   s  t  |  d ƒ t | ƒ } g  } xÍ t t j |  j ƒ ƒ D]³ } t j |  j | ƒ } d t j t j d t j	 |  j
 | d  d  … f ƒ ƒ } | d t j | |  j | d  d  … f d |  j
 | d  d  … f d ƒ 8} | j | | ƒ q8 Wt j | ƒ j } | S(   NR   g      à¿g       @g      à?i   i   (   R   R	   t   rangeR   t   sizeR   t   logRV   R5   t   piRO   RN   t   appendt   arrayR   (   R   R   t   joint_log_likelihoodR`   t   jointit   n_ij(    (    s2   lib/python2.7/site-packages/sklearn/naive_bayes.pyR   ­  s    :*"N(   R$   R%   R&   R3   R)   R0   t   staticmethodRD   RG   RE   R,   R   (    (    (    s2   lib/python2.7/site-packages/sklearn/naive_bayes.pyR   k   s   7J*ug»½×Ùß|Û=t   BaseDiscreteNBc           B   sh   e  Z d  Z d d „ Z d „  Z d d d „ Z d d „ Z d „  Z d „  Z	 e
 e ƒ Z e
 e	 ƒ Z RS(   sµ   Abstract base class for naive Bayes on discrete/categorical data

    Any estimator based on this class should provide:

    __init__
    _joint_log_likelihood(X) as per BaseNB
    c         C   s«   t  |  j ƒ } | d  k	 rQ t  | ƒ | k r< t d ƒ ‚ n  t j | ƒ |  _ nV |  j rˆ t j |  j ƒ t j |  j j	 ƒ  ƒ |  _ n t j
 | t j | ƒ ƒ |  _ d  S(   Ns.   Number of priors must match number of classes.(   RL   R   R3   RS   R   Rh   t   class_log_prior_t	   fit_priorRQ   R5   t   full(   R   t   class_priorR[   (    (    s2   lib/python2.7/site-packages/sklearn/naive_bayes.pyt   _update_class_log_priorÈ  s    	c         C   sÁ   t  j |  j ƒ d k  r7 t d t  j |  j ƒ ƒ ‚ n  t |  j t  j ƒ r~ |  j j d |  j j d k s~ t d ƒ ‚ q~ n  t  j |  j ƒ t k  rº t	 j
 d t ƒ t  j |  j t ƒ S|  j S(   Ni    s6   Smoothing parameter alpha = %.1e. alpha should be > 0.i   sA   alpha should be a scalar or a numpy array with shape [n_features]sC   alpha too small will result in numeric errors, setting alpha = %.1e(   R   t   mint   alphaRS   t
   isinstancet   ndarrayR2   t   feature_count_t
   _ALPHA_MINt   warningst   warnt   maximum(   R   (    (    s2   lib/python2.7/site-packages/sklearn/naive_bayes.pyt   _check_alphaÖ  s     	c         C   s  t  | d d d t j ƒ} | j \ } } t |  | ƒ rœ t | ƒ d k rW t | ƒ n d } t j | d t j ƒ|  _ t j | | f d t j ƒ|  _ n? | |  j	 j d k rÛ d } t
 | | |  j	 j d f ƒ ‚ n  t | d |  j ƒ}	 |	 j d d k r%t j d |	 |	 f d	 d ƒ}	 n  |	 j \ }
 } | j d
 |	 j d
 k r{d } t
 | | j d
 | j d
 f ƒ ‚ n  |	 j t j ƒ }	 | d k	 r¾t j | ƒ } |	 t  | ƒ j 9}	 n  |  j } |  j | |	 ƒ |  j ƒ  } |  j | ƒ |  j d | ƒ |  S(   s  Incremental fit on a batch of samples.

        This method is expected to be called several times consecutively
        on different chunks of a dataset so as to implement out-of-core
        or online learning.

        This is especially useful when the whole dataset is too big to fit in
        memory at once.

        This method has some performance overhead hence it is better to call
        partial_fit on chunks of data that are as large as possible
        (as long as fitting in the memory budget) to hide the overhead.

        Parameters
        ----------
        X : {array-like, sparse matrix}, shape = [n_samples, n_features]
            Training vectors, where n_samples is the number of samples and
            n_features is the number of features.

        y : array-like, shape = [n_samples]
            Target values.

        classes : array-like, shape = [n_classes] (default=None)
            List of all the classes that can possibly appear in the y vector.

            Must be provided at the first call to partial_fit, can be omitted
            in subsequent calls.

        sample_weight : array-like, shape = [n_samples] (default=None)
            Weights applied to individual samples (1. for unweighted).

        Returns
        -------
        self : object
        t   accept_sparset   csrRI   i   i   s6   Number of features %d does not match previous data %d.iÿÿÿÿRF   R   i    s1   X.shape[0]=%d and y.shape[0]=%d are incompatible.Rt   N(   R	   R   RP   R2   R   RL   RM   RQ   Rz   t   coef_RS   R   R   t   concatenatet   astypeR3   R   R   Rt   t   _countR   t   _update_feature_log_probRu   (   R   R   R/   RF   R+   t   _RZ   t   n_effective_classesR\   t   Yt	   n_samplesR[   Rt   Rw   (    (    s2   lib/python2.7/site-packages/sklearn/naive_bayes.pyRG   ä  s6    $$#"'	c         C   sR  t  | | d ƒ \ } } | j \ } } t ƒ  } | j | ƒ } | j |  _ | j d d k r€ t j d | | f d d ƒ} n  | j t j ƒ } | d k	 rÃ t j
 | ƒ } | t | ƒ j 9} n  |  j } | j d }	 t j |	 d t j ƒ|  _ t j |	 | f d t j ƒ|  _ |  j | | ƒ |  j ƒ  }
 |  j |
 ƒ |  j d | ƒ |  S(   s1  Fit Naive Bayes classifier according to X, y

        Parameters
        ----------
        X : {array-like, sparse matrix}, shape = [n_samples, n_features]
            Training vectors, where n_samples is the number of samples and
            n_features is the number of features.

        y : array-like, shape = [n_samples]
            Target values.

        sample_weight : array-like, shape = [n_samples], (default=None)
            Weights applied to individual samples (1. for unweighted).

        Returns
        -------
        self : object
        R   i   R   RI   Rt   N(   R   R2   R   t   fit_transformR   R   Rƒ   R„   RP   R3   R   R	   R   Rt   RM   RQ   Rz   R…   R   R†   Ru   (   R   R   R/   R+   R‡   RZ   t   labelbinR‰   Rt   Rˆ   Rw   (    (    s2   lib/python2.7/site-packages/sklearn/naive_bayes.pyR0   6  s*    	"	c         C   s'   t  |  j ƒ d k r  |  j d S|  j S(   Ni   i   (   RL   R   t   feature_log_prob_(   R   (    (    s2   lib/python2.7/site-packages/sklearn/naive_bayes.pyt	   _get_coefj  s    c         C   s'   t  |  j ƒ d k r  |  j d S|  j S(   Ni   i   (   RL   R   Rq   (   R   (    (    s2   lib/python2.7/site-packages/sklearn/naive_bayes.pyt   _get_interceptn  s    N(   R$   R%   R&   R3   Ru   R   RG   R0   RŽ   R   t   propertyR‚   t
   intercept_(    (    (    s2   lib/python2.7/site-packages/sklearn/naive_bayes.pyRp   ¿  s   	R4		c           B   s;   e  Z d  Z d e d d „ Z d „  Z d „  Z d „  Z RS(   s´
  
    Naive Bayes classifier for multinomial models

    The multinomial Naive Bayes classifier is suitable for classification with
    discrete features (e.g., word counts for text classification). The
    multinomial distribution normally requires integer feature counts. However,
    in practice, fractional counts such as tf-idf may also work.

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

    Parameters
    ----------
    alpha : float, optional (default=1.0)
        Additive (Laplace/Lidstone) smoothing parameter
        (0 for no smoothing).

    fit_prior : boolean, optional (default=True)
        Whether to learn class prior probabilities or not.
        If false, a uniform prior will be used.

    class_prior : array-like, size (n_classes,), optional (default=None)
        Prior probabilities of the classes. If specified the priors are not
        adjusted according to the data.

    Attributes
    ----------
    class_log_prior_ : array, shape (n_classes, )
        Smoothed empirical log probability for each class.

    intercept_ : array, shape (n_classes, )
        Mirrors ``class_log_prior_`` for interpreting MultinomialNB
        as a linear model.

    feature_log_prob_ : array, shape (n_classes, n_features)
        Empirical log probability of features
        given a class, ``P(x_i|y)``.

    coef_ : array, shape (n_classes, n_features)
        Mirrors ``feature_log_prob_`` for interpreting MultinomialNB
        as a linear model.

    class_count_ : array, shape (n_classes,)
        Number of samples encountered for each class during fitting. This
        value is weighted by the sample weight when provided.

    feature_count_ : array, shape (n_classes, n_features)
        Number of samples encountered for each (class, feature)
        during fitting. This value is weighted by the sample weight when
        provided.

    Examples
    --------
    >>> import numpy as np
    >>> X = np.random.randint(5, size=(6, 100))
    >>> y = np.array([1, 2, 3, 4, 5, 6])
    >>> from sklearn.naive_bayes import MultinomialNB
    >>> clf = MultinomialNB()
    >>> clf.fit(X, y)
    MultinomialNB(alpha=1.0, class_prior=None, fit_prior=True)
    >>> print(clf.predict(X[2:3]))
    [3]

    Notes
    -----
    For the rationale behind the names `coef_` and `intercept_`, i.e.
    naive Bayes as a linear classifier, see J. Rennie et al. (2003),
    Tackling the poor assumptions of naive Bayes text classifiers, ICML.

    References
    ----------
    C.D. Manning, P. Raghavan and H. Schuetze (2008). Introduction to
    Information Retrieval. Cambridge University Press, pp. 234-265.
    http://nlp.stanford.edu/IR-book/html/htmledition/naive-bayes-text-classification-1.html
    g      ð?c         C   s   | |  _  | |  _ | |  _ d  S(   N(   Rw   Rr   Rt   (   R   Rw   Rr   Rt   (    (    s2   lib/python2.7/site-packages/sklearn/naive_bayes.pyR)   Â  s    		c         C   ss   t  j t | ƒ r | j n | d k  ƒ r9 t d ƒ ‚ n  |  j t | j | ƒ 7_ |  j | j	 d d ƒ 7_ d S(   s%   Count and smooth feature occurrences.i    s   Input X must be non-negativeR   N(
   R   RU   R   t   dataRS   Rz   R   R   RQ   R5   (   R   R   R‰   (    (    s2   lib/python2.7/site-packages/sklearn/naive_bayes.pyR…   Ç  s    *c         C   sN   |  j  | } | j d d ƒ } t j | ƒ t j | j d d ƒ ƒ |  _ d S(   s=   Apply smoothing to raw counts and recompute log probabilitiesR   i   iÿÿÿÿN(   Rz   R5   R   Rh   t   reshapeR   (   R   Rw   t   smoothed_fct   smoothed_cc(    (    s2   lib/python2.7/site-packages/sklearn/naive_bayes.pyR†   Î  s    c         C   s9   t  |  d ƒ t | d d ƒ} t | |  j j ƒ |  j S(   s8   Calculate the posterior log probability of the samples XR   R€   R   (   R   R	   R   R   R   Rq   (   R   R   (    (    s2   lib/python2.7/site-packages/sklearn/naive_bayes.pyR   Ö  s    N(	   R$   R%   R&   R.   R3   R)   R…   R†   R   (    (    (    s2   lib/python2.7/site-packages/sklearn/naive_bayes.pyR   v  s
   J		c           B   s>   e  Z d  Z d e d e d „ Z d „  Z d „  Z d „  Z	 RS(   s
  The Complement Naive Bayes classifier described in Rennie et al. (2003).

    The Complement Naive Bayes classifier was designed to correct the "severe
    assumptions" made by the standard Multinomial Naive Bayes classifier. It is
    particularly suited for imbalanced data sets.

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

    Parameters
    ----------
    alpha : float, optional (default=1.0)
        Additive (Laplace/Lidstone) smoothing parameter (0 for no smoothing).

    fit_prior : boolean, optional (default=True)
        Only used in edge case with a single class in the training set.

    class_prior : array-like, size (n_classes,), optional (default=None)
        Prior probabilities of the classes. Not used.

    norm : boolean, optional (default=False)
        Whether or not a second normalization of the weights is performed. The
        default behavior mirrors the implementations found in Mahout and Weka,
        which do not follow the full algorithm described in Table 9 of the
        paper.

    Attributes
    ----------
    class_log_prior_ : array, shape (n_classes, )
        Smoothed empirical log probability for each class. Only used in edge
        case with a single class in the training set.

    feature_log_prob_ : array, shape (n_classes, n_features)
        Empirical weights for class complements.

    class_count_ : array, shape (n_classes,)
        Number of samples encountered for each class during fitting. This
        value is weighted by the sample weight when provided.

    feature_count_ : array, shape (n_classes, n_features)
        Number of samples encountered for each (class, feature) during fitting.
        This value is weighted by the sample weight when provided.

    feature_all_ : array, shape (n_features,)
        Number of samples encountered for each feature during fitting. This
        value is weighted by the sample weight when provided.

    Examples
    --------
    >>> import numpy as np
    >>> X = np.random.randint(5, size=(6, 100))
    >>> y = np.array([1, 2, 3, 4, 5, 6])
    >>> from sklearn.naive_bayes import ComplementNB
    >>> clf = ComplementNB()
    >>> clf.fit(X, y)
    ComplementNB(alpha=1.0, class_prior=None, fit_prior=True, norm=False)
    >>> print(clf.predict(X[2:3]))
    [3]

    References
    ----------
    Rennie, J. D., Shih, L., Teevan, J., & Karger, D. R. (2003).
    Tackling the poor assumptions of naive bayes text classifiers. In ICML
    (Vol. 3, pp. 616-623).
    https://people.csail.mit.edu/jrennie/papers/icml03-nb.pdf
    g      ð?c         C   s(   | |  _  | |  _ | |  _ | |  _ d  S(   N(   Rw   Rr   Rt   t   norm(   R   Rw   Rr   Rt   R–   (    (    s2   lib/python2.7/site-packages/sklearn/naive_bayes.pyR)   "  s    			c         C   s‹   t  j t | ƒ r | j n | d k  ƒ r9 t d ƒ ‚ n  |  j t | j | ƒ 7_ |  j | j	 d d ƒ 7_ |  j j	 d d ƒ |  _
 d S(   s   Count feature occurrences.i    s   Input X must be non-negativeR   N(   R   RU   R   R’   RS   Rz   R   R   RQ   R5   t   feature_all_(   R   R   R‰   (    (    s2   lib/python2.7/site-packages/sklearn/naive_bayes.pyR…   )  s
    *c         C   s|   |  j  | |  j } t j | | j d d d t ƒ ƒ } | } |  j ro | j d d d t ƒ } | | } n  | |  _ d S(   s6   Apply smoothing to raw counts and compute the weights.R   i   t   keepdimsN(   R—   Rz   R   Rh   R5   R.   R–   R   (   R   Rw   t
   comp_countt   loggedt   feature_log_probt   summed(    (    s2   lib/python2.7/site-packages/sklearn/naive_bayes.pyR†   1  s    %	c         C   s]   t  |  d ƒ t | d d ƒ} t | |  j j ƒ } t |  j ƒ d k rY | |  j 7} n  | S(   s0   Calculate the class scores for the samples in X.R   R€   R   i   (   R   R	   R   R   R   RL   R   Rq   (   R   R   R   (    (    s2   lib/python2.7/site-packages/sklearn/naive_bayes.pyR   <  s    N(
   R$   R%   R&   R.   R3   RE   R)   R…   R†   R   (    (    (    s2   lib/python2.7/site-packages/sklearn/naive_bayes.pyR   ß  s   A			c           B   s>   e  Z d  Z d d e d d „ Z d „  Z d „  Z d „  Z RS(   sj
  Naive Bayes classifier for multivariate Bernoulli models.

    Like MultinomialNB, this classifier is suitable for discrete data. The
    difference is that while MultinomialNB works with occurrence counts,
    BernoulliNB is designed for binary/boolean features.

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

    Parameters
    ----------
    alpha : float, optional (default=1.0)
        Additive (Laplace/Lidstone) smoothing parameter
        (0 for no smoothing).

    binarize : float or None, optional (default=0.0)
        Threshold for binarizing (mapping to booleans) of sample features.
        If None, input is presumed to already consist of binary vectors.

    fit_prior : boolean, optional (default=True)
        Whether to learn class prior probabilities or not.
        If false, a uniform prior will be used.

    class_prior : array-like, size=[n_classes,], optional (default=None)
        Prior probabilities of the classes. If specified the priors are not
        adjusted according to the data.

    Attributes
    ----------
    class_log_prior_ : array, shape = [n_classes]
        Log probability of each class (smoothed).

    feature_log_prob_ : array, shape = [n_classes, n_features]
        Empirical log probability of features given a class, P(x_i|y).

    class_count_ : array, shape = [n_classes]
        Number of samples encountered for each class during fitting. This
        value is weighted by the sample weight when provided.

    feature_count_ : array, shape = [n_classes, n_features]
        Number of samples encountered for each (class, feature)
        during fitting. This value is weighted by the sample weight when
        provided.

    Examples
    --------
    >>> import numpy as np
    >>> X = np.random.randint(2, size=(6, 100))
    >>> Y = np.array([1, 2, 3, 4, 4, 5])
    >>> from sklearn.naive_bayes import BernoulliNB
    >>> clf = BernoulliNB()
    >>> clf.fit(X, Y)
    BernoulliNB(alpha=1.0, binarize=0.0, class_prior=None, fit_prior=True)
    >>> print(clf.predict(X[2:3]))
    [3]

    References
    ----------

    C.D. Manning, P. Raghavan and H. Schuetze (2008). Introduction to
    Information Retrieval. Cambridge University Press, pp. 234-265.
    http://nlp.stanford.edu/IR-book/html/htmledition/the-bernoulli-model-1.html

    A. McCallum and K. Nigam (1998). A comparison of event models for naive
    Bayes text classification. Proc. AAAI/ICML-98 Workshop on Learning for
    Text Categorization, pp. 41-48.

    V. Metsis, I. Androutsopoulos and G. Paliouras (2006). Spam filtering with
    naive Bayes -- Which naive Bayes? 3rd Conf. on Email and Anti-Spam (CEAS).
    g      ð?g        c         C   s(   | |  _  | |  _ | |  _ | |  _ d  S(   N(   Rw   R   Rr   Rt   (   R   Rw   R   Rr   Rt   (    (    s2   lib/python2.7/site-packages/sklearn/naive_bayes.pyR)   Ž  s    			c         C   sa   |  j  d k	 r' t  | d |  j  ƒ} n  |  j t | j | ƒ 7_ |  j | j d d ƒ 7_ d S(   s%   Count and smooth feature occurrences.t	   thresholdR   i    N(   R   R3   Rz   R   R   RQ   R5   (   R   R   R‰   (    (    s2   lib/python2.7/site-packages/sklearn/naive_bayes.pyR…   •  s    c         C   sM   |  j  | } |  j | d } t j | ƒ t j | j d d ƒ ƒ |  _ d S(   s=   Apply smoothing to raw counts and recompute log probabilitiesi   iÿÿÿÿi   N(   Rz   RQ   R   Rh   R“   R   (   R   Rw   R”   R•   (    (    s2   lib/python2.7/site-packages/sklearn/naive_bayes.pyR†   œ  s    c         C   så   t  |  d ƒ t | d d ƒ} |  j d k	 rF t | d |  j ƒ} n  |  j j \ } } | j \ } } | | k rŒ t d | | f ƒ ‚ n  t j d t j	 |  j ƒ ƒ } t
 | |  j | j ƒ } | |  j | j d d ƒ 7} | S(	   s8   Calculate the posterior log probability of the samples XR   R€   R   R   s/   Expected input with %d features, got %d insteadi   R   N(   R   R	   R   R3   R   R2   RS   R   Rh   R"   R   R   Rq   R5   (   R   R   R[   RZ   RŠ   t   n_features_Xt   neg_probR   (    (    s2   lib/python2.7/site-packages/sklearn/naive_bayes.pyR   ¤  s    N(	   R$   R%   R&   R.   R3   R)   R…   R†   R   (    (    (    s2   lib/python2.7/site-packages/sklearn/naive_bayes.pyR   G  s   E			('   R&   R|   t   abcR    R   t   numpyR   t   scipy.sparseR   t   baseR   R   t   preprocessingR   R   R   t   utilsR   R	   R
   t   utils.extmathR   t   utils.fixesR   t   utils.multiclassR   t   utils.validationR   t	   externalsR   t   __all__t   with_metaclassR   R   R{   Rp   R   R   R   (    (    (    s2   lib/python2.7/site-packages/sklearn/naive_bayes.pyt   <module>   s.   %Dÿ R·ih