`L idZddlZddlmZddlZddlmZddlm Z m Z ddl m Z m Z ddlmZdd lmZdd lmZdd lmZdd lmZmZmZmZd dlmZmZmZmZddZ Gddee eZ!Gddee eZ"y)zNearest Neighbor ClassificationN)Integral)_check_precomputed)ClassifierMixin _fit_context)ArgKminClassModeRadiusNeighborsClassMode) StrOptions)_all_with_any_reduction_axis_1) weighted_mode)_mode) _is_arraylike _num_samplescheck_is_fitted validate_data)KNeighborsMixin NeighborsBaseRadiusNeighborsMixin _get_weightsc8|xsi}|dk(r ||d<|dk(rd}||fS)N minkowskipr euclideanmetric metric_kwargsrs g/mnt/ssd/data/python-lab/Trading/venv/lib/python3.12/site-packages/sklearn/neighbors/_classification.py_adjusted_metricr s5!'RM  c 6 F =  c eZdZUdZiej Zeed<ejdejde ddhe dgi dddd d d ddd fd Z e ddZdZdZdfd ZfdZxZS)KNeighborsClassifiera Classifier implementing the k-nearest neighbors vote. Read more in the :ref:`User Guide `. Parameters ---------- n_neighbors : int, default=5 Number of neighbors to use by default for :meth:`kneighbors` queries. weights : {'uniform', 'distance'}, callable or None, default='uniform' Weight function used in prediction. Possible values: - 'uniform' : uniform weights. All points in each neighborhood are weighted equally. - 'distance' : weight points by the inverse of their distance. in this case, closer neighbors of a query point will have a greater influence than neighbors which are further away. - [callable] : a user-defined function which accepts an array of distances, and returns an array of the same shape containing the weights. Refer to the example entitled :ref:`sphx_glr_auto_examples_neighbors_plot_classification.py` showing the impact of the `weights` parameter on the decision boundary. algorithm : {'auto', 'ball_tree', 'kd_tree', 'brute'}, default='auto' Algorithm used to compute the nearest neighbors: - 'ball_tree' will use :class:`BallTree` - 'kd_tree' will use :class:`KDTree` - 'brute' will use a brute-force search. - 'auto' will attempt to decide the most appropriate algorithm based on the values passed to :meth:`fit` method. Note: fitting on sparse input will override the setting of this parameter, using brute force. leaf_size : int, default=30 Leaf size passed to BallTree or KDTree. This can affect the speed of the construction and query, as well as the memory required to store the tree. The optimal value depends on the nature of the problem. p : float, default=2 Power parameter for the Minkowski metric. When p = 1, this is equivalent to using manhattan_distance (l1), and euclidean_distance (l2) for p = 2. For arbitrary p, minkowski_distance (l_p) is used. This parameter is expected to be positive. metric : str or callable, default='minkowski' Metric to use for distance computation. Default is "minkowski", which results in the standard Euclidean distance when p = 2. See the documentation of `scipy.spatial.distance `_ and the metrics listed in :class:`~sklearn.metrics.pairwise.distance_metrics` for valid metric values. If metric is "precomputed", X is assumed to be a distance matrix and must be square during fit. X may be a :term:`sparse graph`, in which case only "nonzero" elements may be considered neighbors. If metric is a callable function, it takes two arrays representing 1D vectors as inputs and must return one value indicating the distance between those vectors. This works for Scipy's metrics, but is less efficient than passing the metric name as a string. metric_params : dict, default=None Additional keyword arguments for the metric function. n_jobs : int, default=None The number of parallel jobs to run for neighbors search. ``None`` means 1 unless in a :obj:`joblib.parallel_backend` context. ``-1`` means using all processors. See :term:`Glossary ` for more details. Doesn't affect :meth:`fit` method. Attributes ---------- classes_ : array of shape (n_classes,) Class labels known to the classifier effective_metric_ : str or callble The distance metric used. It will be same as the `metric` parameter or a synonym of it, e.g. 'euclidean' if the `metric` parameter set to 'minkowski' and `p` parameter set to 2. effective_metric_params_ : dict Additional keyword arguments for the metric function. For most metrics will be same with `metric_params` parameter, but may also contain the `p` parameter value if the `effective_metric_` attribute is set to 'minkowski'. 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_samples_fit_ : int Number of samples in the fitted data. outputs_2d_ : bool False when `y`'s shape is (n_samples, ) or (n_samples, 1) during fit otherwise True. See Also -------- RadiusNeighborsClassifier: Classifier based on neighbors within a fixed radius. KNeighborsRegressor: Regression based on k-nearest neighbors. RadiusNeighborsRegressor: Regression based on neighbors within a fixed radius. NearestNeighbors: Unsupervised learner for implementing neighbor searches. Notes ----- See :ref:`Nearest Neighbors ` in the online documentation for a discussion of the choice of ``algorithm`` and ``leaf_size``. .. warning:: Regarding the Nearest Neighbors algorithms, if it is found that two neighbors, neighbor `k+1` and `k`, have identical distances but different labels, the results will depend on the ordering of the training data. https://en.wikipedia.org/wiki/K-nearest_neighbor_algorithm Examples -------- >>> X = [[0], [1], [2], [3]] >>> y = [0, 0, 1, 1] >>> from sklearn.neighbors import KNeighborsClassifier >>> neigh = KNeighborsClassifier(n_neighbors=3) >>> neigh.fit(X, y) KNeighborsClassifier(...) >>> print(neigh.predict([[1.1]])) [0] >>> print(neigh.predict_proba([[0.9]])) [[0.666 0.333]] _parameter_constraintsradiusweightsuniformdistanceNautorr)r& algorithm leaf_sizerr metric_paramsn_jobsc @t ||||||||||_y)N) n_neighborsr+r,rrr-r.)super__init__r&) selfr0r&r+r,rrr-r. __class__s rr2zKNeighborsClassifier.__init__s5 #'   r!Fprefer_skip_nested_validationc&|j||S)aFit the k-nearest neighbors classifier from the training dataset. Parameters ---------- X : {array-like, sparse matrix} of shape (n_samples, n_features) or (n_samples, n_samples) if metric='precomputed' Training data. y : {array-like, sparse matrix} of shape (n_samples,) or (n_samples, n_outputs) Target values. Returns ------- self : KNeighborsClassifier The fitted k-nearest neighbors classifier. )_fit)r3Xys rfitzKNeighborsClassifier.fits,yyAr!c t|d|jdk(r|jdk(rtj||j |j r|j|}|jrXtjt|Dcgc],\}}|j|tj|d.c}}dS|jtj|dS|j|d}d}n|j|\}}|j}|j}|js(|jj!d }|jg}t#|} t%| |j n|} t'||j} | t)| d r t+d tj,| | f|d j. } t|D]~\} }| t1||| fd\}}nt3||| f| d\}}tj4|j7tj8 }|j;|| dd| f<|js| j7} | Scc}}w)6Predict the class labels for the provided data. Parameters ---------- X : {array-like, sparse matrix} of shape (n_queries, n_features), or (n_queries, n_indexed) if metric == 'precomputed', or None Test samples. If `None`, predictions for all indexed points are returned; in this case, points are not considered their own neighbors. Returns ------- y : ndarray of shape (n_queries,) or (n_queries, n_outputs) Class labels for each data sample. _fit_methodr'bruteraxisFreturn_distanceNrrvalueAll neighbors of some sample is getting zero weights. Please modify 'weights' to avoid this case if you are using a user-defined function.dtype)rr&r>r is_usable_for_fit_Xr predict_proba outputs_2d_npstack enumerateclasses_argmax kneighbors_yreshapelenrrr ValueErroremptyrJr r asarrayravelintptake)r3r9 probabilitiesidxprobas neigh_ind neigh_distrRrU n_outputs n_queriesr&y_predk classes_kmode_s rpredictzKNeighborsClassifier.predictsC m, <<9 $7*/?/M/M4;; 0!% 2 21 5 ##8809/G +V!MM#.ryya/HI }}RYY}1%EFF5AIJ$(OOA$6 !J == WW)B HM   qA z4<<8  #A'QR#S1  9i0 8I8IJ%h/ 0LAy9a< 0q9a'9a<(8'Ja::djjl"'':D$>>$/F1a4L 0\\^F Ws1J c ft|d|jdk(rt|j|j|j \}}|j dk(rtj||j|r|js}|jdk(r t|}nt||ddd }tj||j|j|j|j|j ||d }|S|j#|d }d }n|j#|\}}|j }|j}|js(|jj%d}|j g}t'| |jn|} t)||j} | t+j,|} nt/| dr t1dt+j2| } g}t5|D]\} } |d d | f|}t+j6| | j8f}t5|j:D]\}}|| |fxx| d d |fz cc<|j=dd d t*j>f}||z}|jA||js|d}|S)aReturn probability estimates for the test data X. Parameters ---------- X : {array-like, sparse matrix} of shape (n_queries, n_features), or (n_queries, n_indexed) if metric == 'precomputed', or None Test samples. If `None`, predictions for all indexed points are returned; in this case, points are not considered their own neighbors. Returns ------- p : ndarray of shape (n_queries, n_classes), or a list of n_outputs of such arrays if n_outputs > 1. The class probabilities of the input samples. Classes are ordered by lexicographic order. r>r'rr? precomputedcsrFC) accept_sparseresetorder parallel_on_X)rfr&Y_labelsunique_Y_labelsrrstrategyrBNrDrrFrHrr@)!rr&r rr-rr>rrKrLrNrrcomputer0rUrRrTrVrrrO ones_liker rXarangerQzerossizeTsumnewaxisappend)r3r9rrr^rarbrRrUrdr&all_rowsrfrg pred_labelsproba_kir_ normalizers rrMz"KNeighborsClassifier.predict_proba6s$ m, <<9 $%5{{$2D2D% !FM  G+$221dkk6J((;;-/*1-A%auEA!1 8 8KK&& LL!WW$(MM!"/-#! &%$5AIJ$(OOA$6 !J == WW)B H  qA z4<<8 ?ll9-G +G1 =1  99Y' %h/ *LAyQT(9-Khh 9>>:;G$KMM2 83# &'!Q$-7& 8!!,Q ];J z !G   ) *)!,Mr!c&t||||SaH Return the mean accuracy on the given test data and labels. In multi-label classification, this is the subset accuracy which is a harsh metric since you require for each sample that each label set be correctly predicted. Parameters ---------- X : array-like of shape (n_samples, n_features), or None Test samples. If `None`, predictions for all indexed points are used; in this case, points are not considered their own neighbors. This means that `knn.fit(X, y).score(None, y)` implicitly performs a leave-one-out cross-validation procedure and is equivalent to `cross_val_score(knn, X, y, cv=LeaveOneOut())` but typically much faster. y : array-like of shape (n_samples,) or (n_samples, n_outputs) True labels for `X`. sample_weight : array-like of shape (n_samples,), default=None Sample weights. Returns ------- score : float Mean accuracy of ``self.predict(X)`` w.r.t. `y`. r1scorer3r9r: sample_weightr4s rrzKNeighborsClassifier.score:w}Q=11r!ct|}d|j_|jdk(|j _|S)NTrl)r1__sklearn_tags__classifier_tags multi_labelr input_tagspairwiser3tagsr4s rrz%KNeighborsClassifier.__sklearn_tags__s8w')+/(#';;-#?  r!)N)__name__ __module__ __qualname____doc__rr$dict__annotations__popupdater callabler2rr;rjrMrr __classcell__r4s@rr#r#(sQf$Lm&J&J#KDKx(!! ZJ 78(DIJ  .&+ (CJgV2>r!r#c eZdZUdZiej eddhedgee ddgdZe e d<ejd ddd d d d dddd fd Z eddZdZdZdfd ZfdZxZS)RadiusNeighborsClassifieraClassifier implementing a vote among neighbors within a given radius. Read more in the :ref:`User Guide `. Parameters ---------- radius : float, default=1.0 Range of parameter space to use by default for :meth:`radius_neighbors` queries. weights : {'uniform', 'distance'}, callable or None, default='uniform' Weight function used in prediction. Possible values: - 'uniform' : uniform weights. All points in each neighborhood are weighted equally. - 'distance' : weight points by the inverse of their distance. in this case, closer neighbors of a query point will have a greater influence than neighbors which are further away. - [callable] : a user-defined function which accepts an array of distances, and returns an array of the same shape containing the weights. Uniform weights are used by default. algorithm : {'auto', 'ball_tree', 'kd_tree', 'brute'}, default='auto' Algorithm used to compute the nearest neighbors: - 'ball_tree' will use :class:`BallTree` - 'kd_tree' will use :class:`KDTree` - 'brute' will use a brute-force search. - 'auto' will attempt to decide the most appropriate algorithm based on the values passed to :meth:`fit` method. Note: fitting on sparse input will override the setting of this parameter, using brute force. leaf_size : int, default=30 Leaf size passed to BallTree or KDTree. This can affect the speed of the construction and query, as well as the memory required to store the tree. The optimal value depends on the nature of the problem. p : float, default=2 Power parameter for the Minkowski metric. When p = 1, this is equivalent to using manhattan_distance (l1), and euclidean_distance (l2) for p = 2. For arbitrary p, minkowski_distance (l_p) is used. This parameter is expected to be positive. metric : str or callable, default='minkowski' Metric to use for distance computation. Default is "minkowski", which results in the standard Euclidean distance when p = 2. See the documentation of `scipy.spatial.distance `_ and the metrics listed in :class:`~sklearn.metrics.pairwise.distance_metrics` for valid metric values. If metric is "precomputed", X is assumed to be a distance matrix and must be square during fit. X may be a :term:`sparse graph`, in which case only "nonzero" elements may be considered neighbors. If metric is a callable function, it takes two arrays representing 1D vectors as inputs and must return one value indicating the distance between those vectors. This works for Scipy's metrics, but is less efficient than passing the metric name as a string. outlier_label : {manual label, 'most_frequent'}, default=None Label for outlier samples (samples with no neighbors in given radius). - manual label: str or int label (should be the same type as y) or list of manual labels if multi-output is used. - 'most_frequent' : assign the most frequent label of y to outliers. - None : when any outlier is detected, ValueError will be raised. The outlier label should be selected from among the unique 'Y' labels. If it is specified with a different value a warning will be raised and all class probabilities of outliers will be assigned to be 0. metric_params : dict, default=None Additional keyword arguments for the metric function. n_jobs : int, default=None The number of parallel jobs to run for neighbors search. ``None`` means 1 unless in a :obj:`joblib.parallel_backend` context. ``-1`` means using all processors. See :term:`Glossary ` for more details. Attributes ---------- classes_ : ndarray of shape (n_classes,) Class labels known to the classifier. effective_metric_ : str or callable The distance metric used. It will be same as the `metric` parameter or a synonym of it, e.g. 'euclidean' if the `metric` parameter set to 'minkowski' and `p` parameter set to 2. effective_metric_params_ : dict Additional keyword arguments for the metric function. For most metrics will be same with `metric_params` parameter, but may also contain the `p` parameter value if the `effective_metric_` attribute is set to 'minkowski'. 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_samples_fit_ : int Number of samples in the fitted data. outlier_label_ : int or array-like of shape (n_class,) Label which is given for outlier samples (samples with no neighbors on given radius). outputs_2d_ : bool False when `y`'s shape is (n_samples, ) or (n_samples, 1) during fit otherwise True. See Also -------- KNeighborsClassifier : Classifier implementing the k-nearest neighbors vote. RadiusNeighborsRegressor : Regression based on neighbors within a fixed radius. KNeighborsRegressor : Regression based on k-nearest neighbors. NearestNeighbors : Unsupervised learner for implementing neighbor searches. Notes ----- See :ref:`Nearest Neighbors ` in the online documentation for a discussion of the choice of ``algorithm`` and ``leaf_size``. https://en.wikipedia.org/wiki/K-nearest_neighbor_algorithm Examples -------- >>> X = [[0], [1], [2], [3]] >>> y = [0, 0, 1, 1] >>> from sklearn.neighbors import RadiusNeighborsClassifier >>> neigh = RadiusNeighborsClassifier(radius=1.0) >>> neigh.fit(X, y) RadiusNeighborsClassifier(...) >>> print(neigh.predict([[1.5]])) [0] >>> print(neigh.predict_proba([[1.0]])) [[0.66666667 0.33333333]] r'r(Nz array-like)r& outlier_labelr$r0r)r*rr)r&r+r,rrrr-r.c Nt |||||||| ||_||_y)N)r%r+r,rrr-r.)r1r2r&r) r3r%r&r+r,rrrr-r.r4s rr2z"RadiusNeighborsClassifier.__init__ks= '   *r!Fr5c$|j|||j}|j}|js(|jj d}|jg}|j d}n|j dk(rUg}t |D]C\}}tj|dd|f}|j||jEn6t|j rvt|j ts\t|j t|k7r.tdj!|j t||j }n|j gt|z}t#||D]\} } t| r+t| tst%dj!| | tj| | j&| j&k7sjt%dj!| | ||_|S)aFit the radius neighbors classifier from the training dataset. Parameters ---------- X : {array-like, sparse matrix} of shape (n_samples, n_features) or (n_samples, n_samples) if metric='precomputed' Training data. y : {array-like, sparse matrix} of shape (n_samples,) or (n_samples, n_outputs) Target values. Returns ------- self : RadiusNeighborsClassifier The fitted radius neighbors classifier. rDN most_frequentzJThe length of outlier_label: {} is inconsistent with the output length: {}zCThe outlier_label of classes {} is supposed to be a scalar, got {}.zCThe dtype of outlier_label {} is inconsistent with classes {} in y.)r8rRrUrNrVrrQrObincountr~rSr isinstancestrrWrXformatzip TypeErrorrJoutlier_label_) r3r9r:rRrUrrfrg label_countclasseslabels rr;zRadiusNeighborsClassifier.fits, !Q== WW)B H    %!N   ? 2N!*( 3 G 9 kk"QT(3 %%i 0B0B0D&EF G T//0""C:t))*c(m;$%%+VD,>,>H %N "&!3!3"&"4"4!5H !E"%h"?  ' 5#0F#$fWe4 99We,22gmmC##VE73  - r!cT|j|}|j}|js|g}|jg}t|}|djd}t j ||f|dj}t|D]\}}|jd} ||j| |dd|f<|dk(jd} | jsYt j| } |j||| |f<|js|j}|S)r=rrIrr@N)rMrRrNrWshaperOrYrJrQrSr]allany flatnonzerorr[) r3r9probsrRrcrdrerfprobmax_prob_indexoutlier_zero_probszero_prob_indexs rrjz!RadiusNeighborsClassifier.predicts"""1%==GE HM !HNN1% 9i0 8I8IJ ' DGAt"[[a[0N#A;++N;F1a4L"&!)a!8 !%%'"$..1C"D-1-@-@-C)* D\\^F r!c *t|dt| |jn|}t|j|j |j \}}|jdk(r|jdk(r|js~tj||j|r]tj||j|j|j|j|j|j ||d }|S|j#|\}}t%j&|t(}|D cgc]} t+| d k(c} |ddt%j,|} t%j,|} |j} |j} |js(|jj/d } |jg} |j0| j2d kDrt5d | zt7||j}||| }g}t9| D]\}}t%j&t+|t:}|Dcgc] }| ||f c}|ddt%j&||j2f}t%j&t+| |j2f}|?t9|| D]-\}}t%j<||j2 ||ddf</nBt9|| D]1\}}t%j<||||j2 ||ddf<3||| ddf<| j2d kDrr|j0|}t%j,||k(}|j2d k(r d|| |d f<n1t?j@djC|j0||jEd ddt$jFf}d||dk(<||z}|jI||js|d }|Scc} wcc}w)aReturn probability estimates for the test data X. Parameters ---------- X : {array-like, sparse matrix} of shape (n_queries, n_features), or (n_queries, n_indexed) if metric == 'precomputed', or None Test samples. If `None`, predictions for all indexed points are returned; in this case, points are not considered their own neighbors. Returns ------- p : ndarray of shape (n_queries, n_classes), or a list of n_outputs of such arrays if n_outputs > 1. The class probabilities of the input samples. Classes are ordered by lexicographic order. r>Nrr'r?rr) r9Yr%r&rsrtrrrrurIrrDzNo neighbors found for test samples %r, you can try using larger radius, giving a label for outliers, or considering removing them from your dataset.) minlengthr?ziOutlier label {} is not in training classes. All class probabilities of outliers will be assigned with 0.r@g)%rrrLr rr-rr&r>rNr rKrvr%rUrRrradius_neighborsrOryboolrWrrVrrzrXrrQobjectrwarningswarnrr|r}r~)r3r9rdrrr^rbra outlier_masknindoutliersinliersrRrUr&rfrgrindr proba_inlrr__outlier_label label_indexrs rrMz'RadiusNeighborsClassifier.predict_probas$ m,  qA 0;;d.@.@DFF!  LLI %  G+$$(66q$++vN4<<++{{  $ "00+(M$! $ 5 5a 8 Ixx 6 6?@d3t9>@ Q>>,/..,/== WW)B H    &8==1+<BEMM z4<<8  g&G %h/$ *LAy((3y>@K4=>Sbaj>KNhh 9>>:;G#g, !?@I' G(<=QFAs&(kk#&PIadOQ( G(<=FAs&(kkWQZ9>>'IadO#,GGQJ }}q !%!4!4Q!7 nnY.-HI ##q(8;GHk!n45MM"6$"5"5a"89 !!,Q ];J,/JzS( ) z !G   )I$ *L)!,MCA4?s 0P Pc&t||||Srrrs rrzRadiusNeighborsClassifier.scoreurr!cFt|}d|j_|S)NT)r1rrrrs rrz*RadiusNeighborsClassifier.__sklearn_tags__s#w')+/( r!)rr)rrrrrr$r rrrrrrr2rr;rjrMrrrrs@rrrsZx$  . .$ :674H"Ct<$D }-+ +2&+E EN*Xvt2>r!rr)#rrnumbersrnumpyrOsklearn.neighbors._baserbaserr%metrics._pairwise_distances_reductionrr utils._param_validationr utils.arrayfuncsr utils.extmathr utils.fixesr utils.validationrrrr_baserrrrr r#rrr!rrsj% 601=) VU!\?O]\~ P 4o}Pr!