`L iTdZddlZddlmZmZddlmZmZddlZ ddl m Z ddl m Z mZmZddlmZmZmZdd lmZdd lmZdd lmZdd lmZmZmZmZmZgd Z Gddee eZ!Gdde!Z"Gdde!Z#Gdde#Z$Gdde#Z%Gdde#Z&Gdde#Z'y)zNaive Bayes algorithms. These are supervised learning methods based on applying Bayes' theorem with strong (naive) feature independence assumptions. N)ABCMetaabstractmethod)IntegralReal) logsumexp) BaseEstimatorClassifierMixin _fit_context)LabelBinarizerbinarizelabel_binarize)Interval)safe_sparse_dot)_check_partial_fit_first_call)_check_n_features_check_sample_weightcheck_is_fittedcheck_non_negative validate_data) BernoulliNB CategoricalNB ComplementNB GaussianNB MultinomialNBcHeZdZdZedZedZdZdZdZ dZ y) _BaseNBz.Abstract base class for naive Bayes estimatorscy)aCompute 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_samples, n_classes). Public methods predict, predict_proba, predict_log_proba, and predict_joint_log_proba pass the input through _check_X before handing it over to _joint_log_likelihood. The term "joint log likelihood" is used interchangibly with "joint log probability". NselfXs Y/mnt/ssd/data/python-lab/Trading/venv/lib/python3.12/site-packages/sklearn/naive_bayes.py_joint_log_likelihoodz_BaseNB._joint_log_likelihood.cy)zgTo be overridden in subclasses with the actual checks. Only used in predict* methods. Nrr s r#_check_Xz_BaseNB._check_X;r%r&c\t||j|}|j|S)aReturn joint log probability estimates for the test vector X. For each row x of X and class y, the joint log probability is given by ``log P(x, y) = log P(y) + log P(x|y),`` where ``log P(y)`` is the class prior probability and ``log P(x|y)`` is the class-conditional probability. Parameters ---------- X : array-like of shape (n_samples, n_features) The input samples. Returns ------- C : ndarray of shape (n_samples, n_classes) Returns the joint 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_`. )rr(r$r s r#predict_joint_log_probaz_BaseNB.predict_joint_log_probaBs+(  MM! ))!,,r&ct||j|}|j|}|jt j |dS)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. raxis)rr(r$classes_npargmaxr!r"jlls r#predictz_BaseNB.predictZsD  MM! ((+}}RYYs344r&ct||j|}|j|}t|d}|t j |j z 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_`. rr,)rr(r$rr/ atleast_2dT)r!r"r2 log_prob_xs r#predict_log_probaz_BaseNB.predict_log_probamsP  MM! ((+s+ R]]:.0000r&cJtj|j|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/expr8r s r# predict_probaz_BaseNB.predict_probas vvd,,Q/00r&N) __name__ __module__ __qualname____doc__rr$r(r*r3r8r;rr&r#rr+s?8      -05&1.1r&r) metaclassceZdZUdZddgeedddgdZeed<dd dd Z e d dd Z dZ e ddZe d ddZddZdZy)ra 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 `_. Read more in the :ref:`User Guide `. Parameters ---------- priors : array-like of shape (n_classes,), default=None 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 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] array-likeNrleftclosedpriors var_smoothing_parameter_constraintsg& .>c ||_||_yNrF)r!rGrHs r#__init__zGaussianNB.__init__s *r&Tprefer_skip_nested_validationcnt||}|j||tj|d|S)aFit 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)r _partial_fitr/unique)r!r"rPrSs r#fitzGaussianNB.fits;0 $! $  q"))A,t=!  r&ct||dS)*Validate X, used only in predict* methods.Fresetrr s r#r(zGaussianNB._check_XsT1E22r&c|jddk(r||fS|jt|j}tj|dr||fStj |d|}tj ||z dzd|}n=|jd}tj |d}tj|d}|dk(r||fSt||z}||z||zz|z } ||z} ||z} | | z||z|z ||z dzzz} | |z } | | fS)aCompute 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)r-weightsr,)shapefloatsumr/iscloseaveragevarmean)n_pastmurer"rSn_newnew_munew_varn_totaltotal_muold_ssdnew_ssd total_ssd total_vars r#_update_mean_variancez GaussianNB._update_mean_variances1P 771:?s7N  $-++-.Ezz%%3wZZ=AFjj!f*!2MRGGGAJEffQQ'GWWQQ'F Q;7? "'FNVb[0G; 3,'/g%')Ab6kVWEW(WW ' ""r&c.|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 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. FrQ)rT)r!r"rPclassesrSs r# partial_fitzGaussianNB.partial_fit\s(R  q'%}!  r&c |rd|_t||}t||||\}}| t||}|jt j |djz|_|r]|jd}t|j}t j||f|_ t j||f|_ t j|t j|_|j t j"|j } t| |k7r t%dt j&| j)ds t%d | dkj+r t%d | |_nt jt|jt j|_n|jd|jjdk7r6d } t%| |jd|jjdfz|jddddfxx|jzcc<|j}t j.|} t j0| |} t j2| st%d | | d || D]} |j5| }||| k(ddf}|||| k(}|j)}nd}|jd}|j7|j||j|ddf|j|ddf||\}}||j|ddf<||j|ddf<|j|xx|z cc<|jddddfxx|jz cc<|j ,|j|jj)z |_|S)aActual 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 NrYrr,rdtype.Number of priors must match number of classes.?z"The sum of the priors should be 1.zPriors must be non-negative.z6Number of features %d does not match previous data %d.zThe target label(s) z* in y do not exist in the initial classes )r.rrrrHr/remaxepsilon_r`lenzerostheta_var_float64 class_count_rGasarray ValueErrorrcrbany class_prior_rUisinall searchsortedrr)r!r"rPrtrRrS first_call n_features n_classesrGmsgunique_yunique_y_in_classesy_iiX_isw_iN_i new_theta new_sigmas r#rTzGaussianNB._partial_fitsT:  DM24A T1az:1  $0BM **RVVAA->-B-B-DD JDMM*I((Iz#:;DK)Z!89DI ""** ED {{&DKK0v;)+$%UVVzz&**,4$%IJJQJ##%$%CDD$*!%'HHS-?rzz$R!wwqzT[[..q11N  DKK4E4Ea4H'I!IJJ IIadOt}} ,O--99Q< ggh8vv)*0017<   (C$$S)AAHaK.C($Q#X.hhjiil#'#=#=!!!$dkk!Q$&71a4#t$ Iy!*DKK1 'DIIadO   a C ' # (& !Q$4==( ;;  $ 1 1D4E4E4I4I4K KD  r&c <g}ttj|jD]}tj|j |}dtj tjdtjz|j|ddfzz}|dtj ||j|ddfz dz|j|ddfz dzz}|j||ztj|j}|S)Ngg@g?r_r) ranger/sizer.logrrbpirrappendarrayr6)r!r"joint_log_likelihoodrjointin_ijs r#r$z GaussianNB._joint_log_likelihoods!rwwt}}-. 7AVVD--a01F"&&bee dii1o(E!FGGD C"&&1t{{1a4'8#8Q">499QPQT?!SUVWW WD ' ' 6  7 "xx(<=??##r&rKNN)NFN)r<r=r>r?rrrIdict__annotations__rLr rVr( staticmethodrrrurTr$rr&r#rrsNb &"4D@A$D "&T+5 6 83G#G#R5* 6* Xrh $r&rceZdZUdZeeddddgdgddgdgdZeed <dd Z e d Z e d Z dZ ddZddZdZed ddZed ddZdZfdZxZS)_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 _update_feature_log_prob(alpha) _count(X, Y) rNrCrDrBbooleanalpha fit_prior class_prior force_alpharITc<||_||_||_||_yrKr)r!rrrrs r#rLz_BaseDiscreteNB.__init__s  "&&r&cy)a=Update counts that are used to calculate probabilities. The counts make up a sufficient statistic extracted from the data. Accordingly, this method is called each time `fit` or `partial_fit` update the model. `class_count_` and `feature_count_` must be updated here along with any model specific counts. Parameters ---------- X : {ndarray, sparse matrix} of shape (n_samples, n_features) The input samples. Y : ndarray of shape (n_samples, n_classes) Binarized class labels. Nrr!r"Ys r#_countz_BaseDiscreteNB._count!r%r&cy)a Update feature log probabilities based on counts. This method is called each time `fit` or `partial_fit` update the model. Parameters ---------- alpha : float smoothing parameter. See :meth:`_check_alpha`. Nr)r!rs r#_update_feature_log_probz(_BaseDiscreteNB._update_feature_log_prob2r%r&c t||ddS)rXcsrF accept_sparserZr[r s r#r(z_BaseDiscreteNB._check_X?sT1EGGr&c"t|||d|S)z Validate X and y in fit methods.rrr[r!r"rPrZs r# _check_X_yz_BaseDiscreteNB._check_X_yCsT1auEJJr&c@t|j}|4t||k7r tdtj||_y|j rtj5tjdttj|j}dddtj|jjz |_ytj|tj| |_y#1swYoxYw)zUpdate class log priors. The class log priors are based on `class_prior`, class count or the number of classes. This method is called each time `fit` or `partial_fit` update the model. Nryignore)r}r.rr/rclass_log_prior_rwarningscatch_warnings simplefilterRuntimeWarningrrbfull)r!rrlog_class_counts r#_update_class_log_priorz'_BaseDiscreteNB._update_class_log_priorGs &  ";9, !QRR$&FF;$7D ! ^^((* <%%h?"$&&):):";  <%4bffT=N=N=R=R=T6U$UD !$&GGIy8I7I$JD ! < T%8%88  ;;q>**?@S@S?TTUW 1} !NOO! ( (1A1A MM%c*+  ::e%67 7 r&rMct|d }|j|||\}}|j\}}t||rt |}|j ||t ||j} | jddk(rJt |jdk(rtjd| z | fd} ntj| } |jd| jdk7r,d} t| |jd|jdfz| jtjd } |0t||}tj|}| |j z} |j"} |j%|| |j'} |j)| |j+| |S) aGIncremental 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.rY)rtrr_r,rz1X.shape[0]=%d and y.shape[0]=%d are incompatible.Fcopyr)hasattrrr`rr}_init_countersrr.r/ concatenate ones_likerastyperrr5r6rrrrr) r!r"rPrtrSr_rrrrrrs r#ruz_BaseDiscreteNB.partial_fitwsL!z22 q!:61 : (w 7G I    : 6 1dmm 4 771:?4==!Q&NNAE1:A6LLO 771: #ECSAGGAJ #;;< < HHRZZeH ,  $0BMMM-8M  A&&  Aq !!# %%e, $$$= r&c|j||\}}|j\}}t}|j|}|j|_|jddk(rJt |jdk(rt jd|z |fd}nt j|}|Q|jt jd}t||}t j|}||jz}|j}|jd} |j| ||j!|||j#} |j%| |j'||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. rr_r,Frr)rr`r fit_transformr.r}r/rrrrrr5r6rrrrrr) r!r"rPrSrrlabelbinrrrrs r#rVz_BaseDiscreteNB.fits?*q!$1 :!#  " "1 % )) 771:?4==!Q&NNAE1:A6LLO  $%0A0BMMM-8M  A&& GGAJ  Iz2 Aq!!# %%e, $$$= r&ctj|tj|_tj||ftj|_y)Nrw)r/r~rrfeature_count_)r!rrs r#rz_BaseDiscreteNB._init_counterss5HHYbjjA hh :'>bjjQr&cht|}d|j_d|j_|SNT)super__sklearn_tags__ input_tagssparseclassifier_tags poor_scorer!tags __class__s r#rz _BaseDiscreteNB.__sklearn_tags__s/w')!%*.' r&)rzTNTTrKr)r<r=r>r?rrrIrrrLrrrr(rrrr rurVrr __classcell__rs@r#rr s4D8,G[$d+!{ $D'       HKK005P6Pd5363jRr&rcJeZdZdZdddddfd ZfdZdZd Zd ZxZ S) ra 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 `. Parameters ---------- alpha : float or array-like of shape (n_features,), default=1.0 Additive (Laplace/Lidstone) smoothing parameter (set alpha=0 and force_alpha=True, for no smoothing). force_alpha : bool, default=True If False and alpha is less than 1e-10, it will set alpha to 1e-10. If True, alpha will remain unchanged. This may cause numerical errors if alpha is too close to 0. .. versionadded:: 1.2 .. versionchanged:: 1.4 The default value of `force_alpha` changed to `True`. 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 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)``. 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. 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] rzTNrrrrc,t|||||yNr)rrL)r!rrrrrs r#rLzMultinomialNB.__init__hs# ##  r&cFt|}d|j_|Srrrr positive_onlyrs r#rzMultinomialNB.__sklearn_tags__r!w')(,% r&ct|d|xjt|j|z c_|xj|j dz c_y)%Count and smooth feature occurrences.zMultinomialNB (input X)rr,N)rrrr6rrbrs r#rzMultinomialNB._countwsD178 qssA66 QUUU]*r&c|j|z}|jd}tj|tj|j ddz |_y)=Apply smoothing to raw counts and recompute log probabilitiesrr,N)rrbr/rreshapefeature_log_prob_r!r smoothed_fc smoothed_ccs r#rz&MultinomialNB._update_feature_log_prob}sS))E1 !oo1o- !# !4rvv   A &8 " r&c\t||jj|jzS)8Calculate the posterior log probability of the samples X)rrr6rr s r#r$z#MultinomialNB._joint_log_likelihoods&q$"8"8":":;d>S>SSSr&) r<r=r>r?rLrrrr$rrs@r#rr s/Zz$  +  Tr&rc~eZdZUdZiej ddgiZeed<dddddd fd Zfd Z d Z d Z dZ xZ S)raVThe 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 `. .. versionadded:: 0.20 Parameters ---------- alpha : float or array-like of shape (n_features,), default=1.0 Additive (Laplace/Lidstone) smoothing parameter (set alpha=0 and force_alpha=True, for no smoothing). force_alpha : bool, default=True If False and alpha is less than 1e-10, it will set alpha to 1e-10. If True, alpha will remain unchanged. This may cause numerical errors if alpha is too close to 0. .. versionadded:: 1.2 .. versionchanged:: 1.4 The default value of `force_alpha` changed to `True`. 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 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. 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] normrrIrzTNF)rrrrrc:t|||||||_yNr)rrLr)r!rrrrrrs r#rLzComplementNB.__init__s, ##   r&cFt|}d|j_|Srrrs r#rzComplementNB.__sklearn_tags__rr&ct|d|xjt|j|z c_|xj|j dz c_|jj d|_y)zCount feature occurrences.zComplementNB (input X)rr,N)rrrr6rrb feature_all_rs r#rzComplementNB._count s`167 qssA66 QUUU]* //333;r&c|j|z|jz }tj||j ddz }|j r |j dd}||z }||_y| }||_y)z6Apply smoothing to raw counts and compute the weights.rT)r-keepdimsN)rrr/rrbrr)r!r comp_countloggedsummedfeature_log_probs r#rz%ComplementNB._update_feature_log_probs|&&.1D1DD  Z^^T^%JJK 99ZZQZ6F% "2!'w !1r&ct||jj}t|jdk(r||j z }|S)z0Calculate the class scores for the samples in X.r)rrr6r}r.rr1s r#r$z"ComplementNB._joint_log_likelihoods@a!7!7!9!9: t}}  " 4(( (C r&)r<r=r>r?rrIrrrLrrrr$rrs@r#rrs]bH$  0 0$ $D " < 2r&rc eZdZUdZiej ddeedddgiZee d<dd d d dd fd Z fd Z dfd Z dZ dZdZxZS)raNaive 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 `. Parameters ---------- alpha : float or array-like of shape (n_features,), default=1.0 Additive (Laplace/Lidstone) smoothing parameter (set alpha=0 and force_alpha=True, for no smoothing). force_alpha : bool, default=True If False and alpha is less than 1e-10, it will set alpha to 1e-10. If True, alpha will remain unchanged. This may cause numerical errors if alpha is too close to 0. .. versionadded:: 1.2 .. versionchanged:: 1.4 The default value of `force_alpha` changed to `True`. 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 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). 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] r NrrCrDrIrzTr])rrr rrc:t|||||||_yr)rrLr )r!rrr rrrs r#rLzBernoulliNB.__init__s, ##  ! r&clt||}|jt||j}|S)rX threshold)rr(r )r!r"rs r#r(zBernoulliNB._check_Xs1 G Q  == $dmm4Ar&c|t||||\}}|jt||j}||fS)NrYr)rrr )r!r"rPrZrs r#rzBernoulliNB._check_X_ys@w!!Qe!41 == $dmm4A!t r&c|xjt|j|z c_|xj|j dz c_y)rrr,N)rrr6rrbrs r#rzBernoulliNB._counts9 qssA66 QUUU]*r&c|j|z}|j|dzz}tj|tj|j ddz |_y)rr_rrN)rrr/rrrrs r#rz$BernoulliNB._update_feature_log_probsW))E1 ''%!)3 !# !4rvv   A &8 " r&ct|jjd}|jd}||k7rtd||fztjdtj |jz }t ||j|z j}||j|jdzz }|S)rrz/Expected input with %d features, got %d insteadr,) rr`rr/rr:rr6rrb)r!r"r n_features_Xneg_probr2s r#r$z!BernoulliNB._joint_log_likelihoods++11!4 wwqz : %A|,-  66!bffT%;%;<<=a$"8"88"C!F!FG t$$x|||';;; r&r)r<r=r>r?rrIrrrrrLr(rrrr$rrs@r#rr&spcJ$  0 0$T8D!T&AB$D!" +  r&rc eZdZUdZiej ddeedddgeedddgdZe e d <d d d ddd fd Z dfd Z dfd Z fdZdZddZdZedZdZdZdZxZS)ra4Naive 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 `. Parameters ---------- alpha : float, default=1.0 Additive (Laplace/Lidstone) smoothing parameter (set alpha=0 and force_alpha=True, for no smoothing). force_alpha : bool, default=True If False and alpha is less than 1e-10, it will set alpha to 1e-10. If True, alpha will remain unchanged. This may cause numerical errors if alpha is too close to 0. .. versionadded:: 1.2 .. versionchanged:: 1.4 The default value of `force_alpha` changed to `True`. 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_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] NrBrrCrDr)min_categoriesrrIrzT)rrrrrc:t|||||||_yr)rrLr)r!rrrrrrs r#rLzCategoricalNB.__init__Bs- ##  -r&c(t||||S)aFit 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. rS)rrV)r!r"rPrSrs r#rVzCategoricalNB.fitSs2w{1a}{==r&c*t|||||S)aIncremental 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. r)rru)r!r"rPrtrSrs r#ruzCategoricalNB.partial_fitnsTw"1a "NNr&ct|}d|j_d|j_d|j_|S)NTF)rrr categoricalrrrs r#rzCategoricalNB.__sklearn_tags__s9w')&*#!&(,% r&c@t||dddd}t|d|S)rXintFTrxrensure_all_finiterZCategoricalNB (input X)rrr s r#r(zCategoricalNB._check_Xs0   "   178r&c Lt|||ddd|\}}t|d||fS)Nr#FTr$r&r'rs r#rzCategoricalNB._check_X_ys;  " 1 178!t r&ctj|tj|_t |Dcgc]}tj|dfc}|_ycc}w)Nrwr)r/r~rrrcategory_count_)r!rrrs r#rzCategoricalNB._init_counterssAHHYbjjABG BSTQ)Q 8TTsAc|jddz}tj|}|tj|jtj st d|jdtj||tj}|j|jk7r)t d|jdd|jd|S|S) Nrr,rz0'min_categories' should have integral type. Got z instead.rwz$'min_categories' should have shape (z',) when an array-like is provided. Got ) r{r/r issubdtyperx signedintegerrrint64r`)r"rn_categories_Xmin_categories_ n_categories_s r#_validate_n_categoriesz$CategoricalNB._validate_n_categoriessA*((>2  %==!6!68H8HI F&,,-Y8JJ~bhhWM""n&:&:: :1771:,G'--.i9 ! ! !r&cd}d}|xj|jdz c_|j||j|_t |j D]m}|dd|f}||j||j|dz |j|<||||j||jjdoy)Ncp|dz|jdz }|dkDrtj|dd|fgdS|S)Nrr)rrconstant)r`r/pad) cat_counthighest_featurediffs r#_update_cat_count_dimsz4CategoricalNB._count.._update_cat_count_dimssC"Q&);;Daxvvi&1d))._update_cat_counts9% 9Aw~~d+77<<288+"GajGYt_gF**V,Q/!W*%8% 9r&rr,r) rrbr2rr1rrr*r`)r!r"rr:rErr@s r#rzCategoricalNB._counts  9 QUUU]*!88D)B'D  # 1d2215t7H7H7N7Nq7Q   r&c &g}t|jD]p}|j||z}|jd}|j t j |t j |jddz r||_y)Nrr,r) rrr*rbrr/rrr)r!rr rsmoothed_cat_countsmoothed_class_counts r#rz&CategoricalNB._update_feature_log_probst**+ A!%!5!5a!85!@ #5#9#9q#9#A  # #)*RVV4H4P4PQSUV4W-XX   "2r&cBt||dtj|jd|jjdf}t |j D].}|dd|f}||j|dd|fjz }0||jz}|S)NFrYr) rr/r~r`rrrrr6r)r!r"r2rrDtotal_lls r#r$z#CategoricalNB._joint_log_likelihoods$/hh D$5$5$;$;A$>?@t**+ ;A1gG 4))!,QZ8:: :C ;...r&rKrr)r<r=r>r?rrIrrrrrrLrVrurr(rrrr2rrr$rrs@r#rrseN$  0 0$   Xq$v 6 4D89$D-">6*OX  U""*<2r&r)(r?rabcrrnumbersrrnumpyr/ scipy.specialrbaser r r preprocessingr r rutils._param_validationr utils.extmathrutils.multiclassrutils.validationrrrrr__all__rrrrrrrrr&r#rVs'"# DC-*; i1o}i1Xo$o$d gD}TO}T@X?Xvg/gTtOtr&