B
    0d                 @   s0  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 ddlmZ ddlmZ ddlmZmZ ddlmZ dddddgZG dd dee
edZG dd deZdZG dd deZG dd deZG dd deZ G dd deZ!G dd deZ"dS )z
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.
    N)ABCMetaabstractmethod)	logsumexp   )BaseEstimatorClassifierMixin)binarize)LabelBinarizer)label_binarize)
deprecated)safe_sparse_dot)_check_partial_fit_first_call)check_is_fittedcheck_non_negative)_check_sample_weightBernoulliNB
GaussianNBMultinomialNBComplementNBCategoricalNBc               @   s@   e Zd ZdZedd Zedd Zdd Zdd	 Zd
d Z	dS )_BaseNBz.Abstract base class for naive Bayes estimatorsc             C   s   dS )a(  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 )selfXr   r   E/var/www/html/venv/lib/python3.7/site-packages/sklearn/naive_bayes.py_joint_log_likelihood1   s    	z_BaseNB._joint_log_likelihoodc             C   s   dS )zgTo be overridden in subclasses with the actual checks.

        Only used in predict* methods.
        Nr   )r   r   r   r   r   _check_X<   s    z_BaseNB._check_Xc             C   s0   t |  | |}| |}| jtj|dd S )a;  
        Perform classification on an array of test vectors X.

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

        Returns
        -------
        C : ndarray of shape (n_samples,)
            Predicted target values for X.
        r   )axis)r   r   r   classes_npZargmax)r   r   jllr   r   r   predictC   s    

z_BaseNB.predictc             C   s8   t |  | |}| |}t|dd}|t|j S )a  
        Return log-probability estimates for the test vector X.

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

        Returns
        -------
        C : array-like of 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 :term:`classes_`.
        r   )r   )r   r   r   r   r   
atleast_2dT)r   r   r    Z
log_prob_xr   r   r   predict_log_probaV   s
    

z_BaseNB.predict_log_probac             C   s   t | |S )a  
        Return probability estimates for the test vector X.

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

        Returns
        -------
        C : array-like of 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 :term:`classes_`.
        )r   expr$   )r   r   r   r   r   predict_probam   s    z_BaseNB.predict_probaN)
__name__
__module____qualname____doc__r   r   r   r!   r$   r&   r   r   r   r   r   .   s   r   )	metaclassc               @   sp   e Zd ZdZdddddZdddZd	d
 ZedddZdddZ	dddZ
dd Zededd ZdS )r   a
  
    Gaussian Naive Bayes (GaussianNB).

    Can perform online updates to model parameters via :meth:`partial_fit`.
    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 of shape (n_classes,)
        Prior probabilities of the classes. If specified the priors are not
        adjusted according to the data.

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

        .. versionadded:: 0.20

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

    class_prior_ : ndarray of shape (n_classes,)
        probability of each class.

    classes_ : ndarray of shape (n_classes,)
        class labels known to the classifier.

    epsilon_ : float
        absolute additive value to variances.

    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

    sigma_ : ndarray of shape (n_classes, n_features)
        Variance of each feature per class.

        .. deprecated:: 1.0
           `sigma_` is deprecated in 1.0 and will be removed in 1.2.
           Use `var_` instead.

    var_ : ndarray of shape (n_classes, n_features)
        Variance of each feature per class.

        .. versionadded:: 1.0

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

    See Also
    --------
    BernoulliNB : Naive Bayes classifier for multivariate Bernoulli models.
    CategoricalNB : Naive Bayes classifier for categorical features.
    ComplementNB : Complement Naive Bayes classifier.
    MultinomialNB : Naive Bayes classifier for multinomial models.

    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()
    >>> print(clf.predict([[-0.8, -1]]))
    [1]
    >>> clf_pf = GaussianNB()
    >>> clf_pf.partial_fit(X, Y, np.unique(Y))
    GaussianNB()
    >>> print(clf_pf.predict([[-0.8, -1]]))
    [1]
    Ng&.>)priorsvar_smoothingc            C   s   || _ || _d S )N)r,   r-   )r   r,   r-   r   r   r   __init__   s    zGaussianNB.__init__c             C   s&   | j |d}| j||t|d|dS )a  Fit Gaussian Naive Bayes according to X, y.

        Parameters
        ----------
        X : array-like of 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 of shape (n_samples,)
            Target values.

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

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

        Returns
        -------
        self : object
            Returns the instance itself.
        )yT)_refitsample_weight)_validate_data_partial_fitr   unique)r   r   r/   r1   r   r   r   fit   s    zGaussianNB.fitc             C   s   | j |ddS )z*Validate X, used only in predict* methods.F)reset)r2   )r   r   r   r   r   r      s    zGaussianNB._check_Xc             C   s   |j d dkr||fS |dk	rTt| }tj|d|d}tj|| d d|d}n&|j d }tj|dd}tj|dd}| dkr||fS t| | }|| | |  | }	| | }
|| }|
| ||  | || d   }|| }|	|fS )a  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 of shape (number of Gaussians,)
            Means for Gaussians in original set.

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

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

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

        total_var : array-like of shape (number of Gaussians,)
            Updated variance for each Gaussian over the combined set.
        r   N)r   weights   )r   )shapefloatsumr   ZaveragevarZmean)Zn_pastmur<   r   r1   Zn_newZnew_muZnew_varZn_totalZtotal_muZold_ssdZnew_ssdZ	total_ssdZ	total_varr   r   r   _update_mean_variance   s$    (
 z GaussianNB._update_mean_variancec             C   s   | j |||d|dS )a{  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 of 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 of shape (n_samples,)
            Target values.

        classes : array-like of 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 of shape (n_samples,), default=None
            Weights applied to individual samples (1. for unweighted).

            .. versionadded:: 0.17

        Returns
        -------
        self : object
            Returns the instance itself.
        F)r0   r1   )r3   )r   r   r/   classesr1   r   r   r   partial_fitE  s    (zGaussianNB.partial_fitFc          	   C   s  |r
d| _ t| |}| j|||d\}}|dk	r:t||}| jtj|dd  | _|r|j	d }t
| j }t||f| _t||f| _tj|tjd| _| jdk	rt| j}	t
|	|krtdt|	 dstd	|	dk  rtd
|	| _ntjt
| j tjd| _nZ|j	d | jj	d krRd}
t|
|j	d | jj	d f | jddddf  | j8  < | j }t|}t||}t|std||  |f x|D ]}||}|||kddf }|dk	r|||k }| }nd}|j	d }| | j| | j|ddf | j|ddf ||\}}|| j|ddf< || j|ddf< | j|  |7  < qW | jddddf  | j7  < | jdkr| j| j  | _| S )a  Actual implementation of Gaussian NB fitting.

        Parameters
        ----------
        X : array-like of 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 of shape (n_samples,)
            Target values.

        classes : array-like of 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.

        _refit : bool, 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 of shape (n_samples,), default=None
            Weights applied to individual samples (1. for unweighted).

        Returns
        -------
        self : object
        N)r6   r   )r   r   )dtypez.Number of priors must match number of classes.g      ?z"The sum of the priors should be 1.zPriors must be non-negative.z6Number of features %d does not match previous data %d.zBThe target label(s) %s in y do not exist in the initial classes %s)r   r   r2   r   r-   r   r<   maxZepsilon_r9   lenzerostheta_var_float64class_count_r,   Zasarray
ValueErroriscloser;   anyclass_prior_r4   Zin1dallZsearchsortedr>   )r   r   r/   r?   r0   r1   
first_call
n_features	n_classesr,   msgZunique_yZunique_y_in_classesZy_iiZX_iZsw_iZN_iZ	new_thetaZ	new_sigmar   r   r   r3   q  sf    




 





4 zGaussianNB._partial_fitc             C   s   g }xt t| jD ]}t| j| }dttdtj | j|d d f   }|dt|| j	|d d f  d | j|d d f  d 8 }|
||  qW t|j}|S )Ng      g       @g      ?r8   r   )ranger   sizer   logrL   r;   pirF   rE   appendarrayr#   )r   r   Zjoint_log_likelihoodrR   ZjointiZn_ijr   r   r   r     s    ,<z GaussianNB._joint_log_likelihoodzWAttribute `sigma_` was deprecated in 1.0 and will be removed in1.2. Use `var_` instead.c             C   s   | j S )N)rF   )r   r   r   r   sigma_  s    zGaussianNB.sigma_)N)N)NN)NFN)r'   r(   r)   r*   r.   r5   r   staticmethodr>   r@   r3   r   r   propertyrY   r   r   r   r   r      s   W
G
,
tg|=c               @   s   e Zd ZdZdd ZdddZddd	Zd
d ZdddZd ddZ	dd Z
ededd Zededd Zdd Zededd ZdS )!_BaseDiscreteNBzAbstract 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   | j |dddS )z*Validate X, used only in predict* methods.csrF)accept_sparser6   )r2   )r   r   r   r   r   r     s    z_BaseDiscreteNB._check_XTc             C   s   | j ||d|dS )z Validate X and y in fit methods.r]   )r^   r6   )r2   )r   r   r/   r6   r   r   r   
_check_X_y	  s    z_BaseDiscreteNB._check_X_yNc          	   C   s   t | j}|d k	r4t ||kr&tdt|| _n`| jr~t  t	dt
 t| j}W d Q R X |t| j  | _nt|t| | _d S )Nz.Number of priors must match number of classes.ignore)rC   r   rI   r   rU   class_log_prior_	fit_priorwarningscatch_warningssimplefilterRuntimeWarningrH   r;   full)r   class_priorrP   Zlog_class_countr   r   r   _update_class_log_prior  s    

z'_BaseDiscreteNB._update_class_log_priorc             C   s~   t | jdk r$tdt | j t| jt jrL| jjd | jksLtdt | jtk rxt	
dt  t | jtS | jS )Nr   z6Smoothing parameter alpha = %.1e. alpha should be > 0.zAalpha should be a scalar or a numpy array with shape [n_features]zCalpha too small will result in numeric errors, setting alpha = %.1e)r   minalpharI   
isinstanceZndarrayr9   n_features_in_
_ALPHA_MINrc   warnmaximum)r   r   r   r   _check_alpha  s    z_BaseDiscreteNB._check_alphac             C   s2  t | d }| j|||d\}}|j\}}t| |rHt|}| || t|| jd}	|	jd dkrt| jdkrtj	d|	 |	fdd}	n
t
|	}	|jd |	jd krd}
t|
|jd |jd f |	jtjd	d
}	|dk	rt||}t|}|	|j9 }	| j}| ||	 |  }| | | j|d | S )aG  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} of 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 of shape (n_samples,)
            Target values.

        classes : array-like of 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 of shape (n_samples,), default=None
            Weights applied to individual samples (1. for unweighted).

        Returns
        -------
        self : object
            Returns the instance itself.
        r   )r6   )r?   r   r8   )r   r   z1X.shape[0]=%d and y.shape[0]=%d are incompatible.F)copyN)rh   )hasattrr_   r9   r   rC   _init_countersr
   r   r   concatenate	ones_likerI   astyperG   r   r"   r#   rh   _countrq   _update_feature_log_probri   )r   r   r/   r?   r1   rN   _rO   rP   YrQ   rh   rk   r   r   r   r@   2  s2    %






z_BaseDiscreteNB.partial_fitc             C   s   |  ||\}}|j\}}t }||}|j| _|jd dkrpt| jdkrftjd| |fdd}n
t|}|dk	r|j	tj
dd}t||}t|}||j9 }| j}|jd }	| |	| | || |  }
| |
 | j|d | S )a_  Fit Naive Bayes classifier according to X, y.

        Parameters
        ----------
        X : {array-like, sparse matrix} of 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 of shape (n_samples,)
            Target values.

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

        Returns
        -------
        self : object
            Returns the instance itself.
        r   r8   )r   NF)rr   )rh   )r_   r9   r	   Zfit_transformr   rC   r   ru   rv   rw   rG   r   r"   r#   rh   rt   rx   rq   ry   ri   )r   r   r/   r1   rz   rO   Zlabelbinr{   rh   rP   rk   r   r   r   r5     s,    







z_BaseDiscreteNB.fitc             C   s,   t j|t jd| _t j||ft jd| _d S )N)rA   )r   rD   rG   rH   feature_count_)r   rP   rO   r   r   r   rt     s    z_BaseDiscreteNB._init_countersz_Attribute `coef_` was deprecated in version 0.24 and will be removed in 1.1 (renaming of 0.26).c             C   s"   t | jdkr| jdd  S | jS )Nr8   r   )rC   r   feature_log_prob_)r   r   r   r   coef_  s    z_BaseDiscreteNB.coef_zdAttribute `intercept_` was deprecated in version 0.24 and will be removed in 1.1 (renaming of 0.26).c             C   s"   t | jdkr| jdd  S | jS )Nr8   r   )rC   r   ra   )r   r   r   r   
intercept_  s    z_BaseDiscreteNB.intercept_c             C   s   ddiS )NZ
poor_scoreTr   )r   r   r   r   
_more_tags  s    z_BaseDiscreteNB._more_tagszoAttribute `n_features_` was deprecated in version 1.0 and will be removed in 1.2. Use `n_features_in_` instead.c             C   s   | j S )N)rm   )r   r   r   r   n_features_  s    z_BaseDiscreteNB.n_features_)T)N)NN)N)r'   r(   r)   r*   r   r_   ri   rq   r@   r5   rt   r   r[   r~   r   r   r   r   r   r   r   r\     s$   


Q
5	r\   c               @   sB   e Zd ZdZddddddZdd	 Zd
d Zdd Zdd ZdS )r   aC  
    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, default=1.0
        Additive (Laplace/Lidstone) smoothing parameter
        (0 for no smoothing).

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

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

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

    class_log_prior_ : ndarray of shape (n_classes,)
        Smoothed empirical log probability for each class.

    classes_ : ndarray of shape (n_classes,)
        Class labels known to the classifier

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

        .. deprecated:: 0.24
            ``coef_`` is deprecated in 0.24 and will be removed in 1.1
            (renaming of 0.26).

    feature_count_ : ndarray of 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_log_prob_ : ndarray of shape (n_classes, n_features)
        Empirical log probability of features
        given a class, ``P(x_i|y)``.

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

        .. deprecated:: 0.24
            ``intercept_`` is deprecated in 0.24 and will be removed in 1.1
            (renaming of 0.26).

    n_features_ : int
        Number of features of each sample.

        .. deprecated:: 1.0
            Attribute `n_features_` was deprecated in version 1.0 and will be
            removed in 1.2. Use `n_features_in_` instead.

    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
    --------
    BernoulliNB : Naive Bayes classifier for multivariate Bernoulli models.
    CategoricalNB : Naive Bayes classifier for categorical features.
    ComplementNB : Complement Naive Bayes classifier.
    GaussianNB : Gaussian Naive Bayes.

    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.
    https://nlp.stanford.edu/IR-book/html/htmledition/naive-bayes-text-classification-1.html

    Examples
    --------
    >>> import numpy as np
    >>> rng = np.random.RandomState(1)
    >>> X = rng.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()
    >>> print(clf.predict(X[2:3]))
    [3]
    g      ?TN)rk   rb   rh   c            C   s   || _ || _|| _d S )N)rk   rb   rh   )r   rk   rb   rh   r   r   r   r.   U  s    zMultinomialNB.__init__c             C   s   ddiS )Nrequires_positive_XTr   )r   r   r   r   r   Z  s    zMultinomialNB._more_tagsc             C   s:   t |d |  jt|j|7  _|  j|jdd7  _dS )z%Count and smooth feature occurrences.zMultinomialNB (input X)r   )r   N)r   r|   r   r#   rH   r;   )r   r   r{   r   r   r   rx   ]  s    
zMultinomialNB._countc             C   s8   | j | }|jdd}t|t|dd | _dS )z=Apply smoothing to raw counts and recompute log probabilitiesr   )r   N)r|   r;   r   rU   reshaper}   )r   rk   smoothed_fcsmoothed_ccr   r   r   ry   c  s    
z&MultinomialNB._update_feature_log_probc             C   s   t || jj| j S )z8Calculate the posterior log probability of the samples X)r   r}   r#   ra   )r   r   r   r   r   r   l  s    z#MultinomialNB._joint_log_likelihood)	r'   r(   r)   r*   r.   r   rx   ry   r   r   r   r   r   r     s   o	c               @   sD   e Zd ZdZdddddddZd	d
 Zdd Zdd Zdd ZdS )r   a  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>`.

    .. versionadded:: 0.20

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

    fit_prior : bool, default=True
        Only used in edge case with a single class in the training set.

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

    norm : bool, 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_count_ : ndarray of shape (n_classes,)
        Number of samples encountered for each class during fitting. This
        value is weighted by the sample weight when provided.

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

    classes_ : ndarray of shape (n_classes,)
        Class labels known to the classifier

    coef_ : ndarray of shape (n_classes, n_features)
        Mirrors ``feature_log_prob_`` for interpreting `ComplementNB`
        as a linear model.

        .. deprecated:: 0.24
            ``coef_`` is deprecated in 0.24 and will be removed in 1.1
            (renaming of 0.26).

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

    feature_count_ : ndarray of 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_log_prob_ : ndarray of shape (n_classes, n_features)
        Empirical weights for class complements.

    intercept_ : ndarray of shape (n_classes,)
        Mirrors ``class_log_prior_`` for interpreting `ComplementNB`
        as a linear model.

        .. deprecated:: 0.24
            ``coef_`` is deprecated in 0.24 and will be removed in 1.1
            (renaming of 0.26).

    n_features_ : int
        Number of features of each sample.

        .. deprecated:: 1.0
            Attribute `n_features_` was deprecated in version 1.0 and will be
            removed in 1.2. Use `n_features_in_` instead.

    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
    --------
    BernoulliNB : Naive Bayes classifier for multivariate Bernoulli models.
    CategoricalNB : Naive Bayes classifier for categorical features.
    GaussianNB : Gaussian Naive Bayes.
    MultinomialNB : Naive Bayes classifier for multinomial models.

    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

    Examples
    --------
    >>> import numpy as np
    >>> rng = np.random.RandomState(1)
    >>> X = rng.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()
    >>> print(clf.predict(X[2:3]))
    [3]
    g      ?TNF)rk   rb   rh   normc            C   s   || _ || _|| _|| _d S )N)rk   rb   rh   r   )r   rk   rb   rh   r   r   r   r   r.     s    zComplementNB.__init__c             C   s   ddiS )Nr   Tr   )r   r   r   r   r     s    zComplementNB._more_tagsc             C   sJ   t |d |  jt|j|7  _|  j|jdd7  _| jjdd| _dS )zCount feature occurrences.zComplementNB (input X)r   )r   N)r   r|   r   r#   rH   r;   feature_all_)r   r   r{   r   r   r   rx     s    
zComplementNB._countc             C   sV   | j | | j }t||jddd }| jrF|jddd}|| }n| }|| _dS )z6Apply smoothing to raw counts and compute the weights.r   T)r   ZkeepdimsN)r   r|   r   rU   r;   r   r}   )r   rk   Z
comp_countZloggedZsummedfeature_log_probr   r   r   ry     s    
z%ComplementNB._update_feature_log_probc             C   s*   t || jj}t| jdkr&|| j7 }|S )z0Calculate the class scores for the samples in X.r   )r   r}   r#   rC   r   ra   )r   r   r    r   r   r   r     s    
z"ComplementNB._joint_log_likelihood)	r'   r(   r)   r*   r.   r   rx   ry   r   r   r   r   r   r   q  s   pc                   sZ   e Zd ZdZdddddddZ fd	d
Zd fdd	Zdd Zdd Zdd Z	  Z
S )r   a  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, default=1.0
        Additive (Laplace/Lidstone) smoothing parameter
        (0 for no smoothing).

    binarize : float or None, 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 : bool, default=True
        Whether to learn class prior probabilities or not.
        If false, a uniform prior will be used.

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

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

    class_log_prior_ : ndarray of shape (n_classes,)
        Log probability of each class (smoothed).

    classes_ : ndarray of shape (n_classes,)
        Class labels known to the classifier

    coef_ : ndarray of shape (n_classes, n_features)
        Mirrors ``feature_log_prob_`` for interpreting `BernoulliNB`
        as a linear model.

    feature_count_ : ndarray of 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_log_prob_ : ndarray of shape (n_classes, n_features)
        Empirical log probability of features given a class, P(x_i|y).

    intercept_ : ndarray of shape (n_classes,)
        Mirrors ``class_log_prior_`` for interpreting `BernoulliNB`
        as a linear model.

    n_features_ : int
        Number of features of each sample.

        .. deprecated:: 1.0
            Attribute `n_features_` was deprecated in version 1.0 and will be
            removed in 1.2. Use `n_features_in_` instead.

    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
    --------
    CategoricalNB : Naive Bayes classifier for categorical features.
    ComplementNB : The Complement Naive Bayes classifier
        described in Rennie et al. (2003).
    GaussianNB : Gaussian Naive Bayes (GaussianNB).
    MultinomialNB : Naive Bayes classifier for multinomial models.

    References
    ----------
    C.D. Manning, P. Raghavan and H. Schuetze (2008). Introduction to
    Information Retrieval. Cambridge University Press, pp. 234-265.
    https://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).

    Examples
    --------
    >>> import numpy as np
    >>> rng = np.random.RandomState(1)
    >>> X = rng.randint(5, 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()
    >>> print(clf.predict(X[2:3]))
    [3]
    g      ?g        TN)rk   r   rb   rh   c            C   s   || _ || _|| _|| _d S )N)rk   r   rb   rh   )r   rk   r   rb   rh   r   r   r   r.   s  s    zBernoulliNB.__init__c                s(   t  |}| jdk	r$t|| jd}|S )z*Validate X, used only in predict* methods.N)	threshold)superr   r   )r   r   )	__class__r   r   r   y  s    
zBernoulliNB._check_Xc                s6   t  j|||d\}}| jd k	r.t|| jd}||fS )N)r6   )r   )r   r_   r   )r   r   r/   r6   )r   r   r   r_     s    
zBernoulliNB._check_X_yc             C   s0   |  j t|j|7  _ |  j|jdd7  _dS )z%Count and smooth feature occurrences.r   )r   N)r|   r   r#   rH   r;   )r   r   r{   r   r   r   rx     s    zBernoulliNB._countc             C   s:   | j | }| j|d  }t|t|dd | _dS )z=Apply smoothing to raw counts and recompute log probabilitiesr8   r   r   N)r|   rH   r   rU   r   r}   )r   rk   r   r   r   r   r   ry     s    
z$BernoulliNB._update_feature_log_probc             C   sp   | j jd }|jd }||kr.td||f tdt| j  }t|| j | j}|| j|j	dd 7 }|S )z8Calculate the posterior log probability of the samples Xr   z/Expected input with %d features, got %d instead)r   )
r}   r9   rI   r   rU   r%   r   r#   ra   r;   )r   r   rO   Zn_features_XZneg_probr    r   r   r   r     s    
z!BernoulliNB._joint_log_likelihood)T)r'   r(   r)   r*   r.   r   r_   rx   ry   r   __classcell__r   r   )r   r   r     s   j	c                   s   e Zd ZdZdddddddZd fdd		Zd fd
d	Zdd Zdd ZdddZ	dd Z
edd Zdd Zdd Zdd Z  ZS )r   a  Naive Bayes classifier for categorical features.

    The categorical Naive Bayes classifier is suitable for classification with
    discrete features that are categorically distributed. The categories of
    each feature are drawn from a categorical distribution.

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

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

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

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

    min_categories : int or array-like of shape (n_features,), default=None
        Minimum number of categories per feature.

        - integer: Sets the minimum number of categories per feature to
          `n_categories` for each features.
        - array-like: shape (n_features,) where `n_categories[i]` holds the
          minimum number of categories for the ith column of the input.
        - None (default): Determines the number of categories automatically
          from the training data.

        .. versionadded:: 0.24

    Attributes
    ----------
    category_count_ : list of arrays of shape (n_features,)
        Holds arrays of shape (n_classes, n_categories of respective feature)
        for each feature. Each array provides the number of samples
        encountered for each class and category of the specific feature.

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

    class_log_prior_ : ndarray of shape (n_classes,)
        Smoothed empirical log probability for each class.

    classes_ : ndarray of shape (n_classes,)
        Class labels known to the classifier

    feature_log_prob_ : list of arrays of shape (n_features,)
        Holds arrays of shape (n_classes, n_categories of respective feature)
        for each feature. Each array provides the empirical log probability
        of categories given the respective feature and class, ``P(x_i|y)``.

    n_features_ : int
        Number of features of each sample.

        .. deprecated:: 1.0
            Attribute `n_features_` was deprecated in version 1.0 and will be
            removed in 1.2. Use `n_features_in_` instead.

    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

    n_categories_ : ndarray of shape (n_features,), dtype=np.int64
        Number of categories for each feature. This value is
        inferred from the data or set by the minimum number of categories.

        .. versionadded:: 0.24

    See Also
    --------
    BernoulliNB : Naive Bayes classifier for multivariate Bernoulli models.
    ComplementNB : Complement Naive Bayes classifier.
    GaussianNB : Gaussian Naive Bayes.
    MultinomialNB : Naive Bayes classifier for multinomial models.

    Examples
    --------
    >>> import numpy as np
    >>> rng = np.random.RandomState(1)
    >>> X = rng.randint(5, size=(6, 100))
    >>> y = np.array([1, 2, 3, 4, 5, 6])
    >>> from sklearn.naive_bayes import CategoricalNB
    >>> clf = CategoricalNB()
    >>> clf.fit(X, y)
    CategoricalNB()
    >>> print(clf.predict(X[2:3]))
    [3]
    g      ?TN)rk   rb   rh   min_categoriesc            C   s   || _ || _|| _|| _d S )N)rk   rb   rh   r   )r   rk   rb   rh   r   r   r   r   r.     s    zCategoricalNB.__init__c                s   t  j|||dS )a  Fit Naive Bayes classifier according to X, y.

        Parameters
        ----------
        X : {array-like, sparse matrix} of shape (n_samples, n_features)
            Training vectors, where `n_samples` is the number of samples and
            `n_features` is the number of features. Here, each feature of X is
            assumed to be from a different categorical distribution.
            It is further assumed that all categories of each feature are
            represented by the numbers 0, ..., n - 1, where n refers to the
            total number of categories for the given feature. This can, for
            instance, be achieved with the help of OrdinalEncoder.

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

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

        Returns
        -------
        self : object
            Returns the instance itself.
        )r1   )r   r5   )r   r   r/   r1   )r   r   r   r5     s    zCategoricalNB.fitc                s   t  j||||dS )a  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} of shape (n_samples, n_features)
            Training vectors, where `n_samples` is the number of samples and
            `n_features` is the number of features. Here, each feature of X is
            assumed to be from a different categorical distribution.
            It is further assumed that all categories of each feature are
            represented by the numbers 0, ..., n - 1, where n refers to the
            total number of categories for the given feature. This can, for
            instance, be achieved with the help of OrdinalEncoder.

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

        classes : array-like of 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 of shape (n_samples,), default=None
            Weights applied to individual samples (1. for unweighted).

        Returns
        -------
        self : object
            Returns the instance itself.
        )r1   )r   r@   )r   r   r/   r?   r1   )r   r   r   r@   0  s    *zCategoricalNB.partial_fitc             C   s   ddiS )Nr   Tr   )r   r   r   r   r   \  s    zCategoricalNB._more_tagsc             C   s"   | j |ddddd}t|d |S )z*Validate X, used only in predict* methods.intFT)rA   r^   force_all_finiter6   zCategoricalNB (input X))r2   r   )r   r   r   r   r   r   _  s    
zCategoricalNB._check_Xc             C   s,   | j ||ddd|d\}}t|d ||fS )Nr   FT)rA   r^   r   r6   zCategoricalNB (input X))r2   r   )r   r   r/   r6   r   r   r   r_   g  s    
zCategoricalNB._check_X_yc                s.   t j t jd| _ fddt|D | _d S )N)rA   c                s   g | ]}t  d fqS )r   )r   rD   ).0rz   )rP   r   r   
<listcomp>p  s    z0CategoricalNB._init_counters.<locals>.<listcomp>)r   rD   rG   rH   rS   category_count_)r   rP   rO   r   )rP   r   rt   n  s    zCategoricalNB._init_countersc             C   s   | j ddd }t|}|d k	rt|jtjsDtd|j dtj||tjd}|j	|j	krtd| j	d  d|j	 d|S |S d S )	Nr   )r   r   z0'min_categories' should have integral type. Got z	 instead.)rA   z$'min_categories' should have shape (z',) when an array-like is provided. Got )
rB   r   rX   Z
issubdtyperA   ZsignedintegerrI   rp   int64r9   )r   r   Zn_categories_XZmin_categories_n_categories_r   r   r   _validate_n_categoriesr  s    
z$CategoricalNB._validate_n_categoriesc             C   s   dd }dd }|  j |jdd7  _ | || j| _x^t| jD ]P}|d d |f }|| j| | j| d | j|< |||| j| | j jd  qBW d S )Nc             S   s4   |d | j d  }|dkr0t| dd|fgdS | S )Nr   r   )r   r   Zconstant)r9   r   pad)	cat_countZhighest_featurediffr   r   r   _update_cat_count_dims  s    z4CategoricalNB._count.<locals>._update_cat_count_dimsc       	      S   s   x~t |D ]r}|d d |f t}|jjtjkr8d }n|||f }tj| | |d}t|d }|||f  || 7  < q
W d S )N)r7   r   )	rS   rw   boolrA   typer   r   ZbincountZnonzero)		X_featurer{   r   rP   jmaskr7   countsindicesr   r   r   _update_cat_count  s    z/CategoricalNB._count.<locals>._update_cat_countr   )r   r   )	rH   r;   r   r   r   rS   rm   r   r9   )r   r   r{   r   r   rR   r   r   r   r   rx     s    zCategoricalNB._countc          
   C   s^   g }xNt | jD ]@}| j| | }|jdd}|t|t|dd  qW || _d S )Nr   )r   r   )	rS   rm   r   r;   rW   r   rU   r   r}   )r   rk   r   rR   Zsmoothed_cat_countZsmoothed_class_countr   r   r   ry     s    "z&CategoricalNB._update_feature_log_probc             C   sx   | j |dd t|jd | jjd f}x>t| jD ]0}|d d |f }|| j| d d |f j7 }q6W || j	 }|S )NF)r6   r   )
Z_check_n_featuresr   rD   r9   rH   rS   rm   r}   r#   ra   )r   r   r    rR   r   Ztotal_llr   r   r   r     s     
z#CategoricalNB._joint_log_likelihood)N)NN)T)r'   r(   r)   r*   r.   r5   r@   r   r   r_   rt   rZ   r   rx   ry   r   r   r   r   )r   r   r     s   d,

)#r*   rc   abcr   r   numpyr   Zscipy.specialr   baser   r   Zpreprocessingr   r	   r
   utilsr   Zutils.extmathr   Zutils.multiclassr   Zutils.validationr   r   r   __all__r   r   rn   r\   r   r   r   r   r   r   r   r   <module>   s@   R  { i   !