`L i^ddlZddlZddlmZmZddlmZddlZddlm Z ddl m Z m Z ddl mZddlmZdd lmZmZmZdd lmZdd lmZmZmZdd lmZmZdd lm Z m!Z!m"Z"ddl#m$Z$dgZ%dZ&Gdde e$Z'dZ(y)N)IntegralReal)warn)issparse) OutlierMixin _fit_context)ExtraTreeRegressor)DTYPE) check_arraycheck_random_state gen_batches)get_chunk_n_rows)Interval RealNotInt StrOptions)Paralleldelayed) _num_samplescheck_is_fitted validate_data) BaseBaggingIsolationForestc||}n |dd|f}|j|d}|5|||||zdz z }dddy#1swYyxYw)z-Parallel computation of isolation tree depth.NF) check_input?)apply) treeXfeaturestree_decision_path_lengthstree_avg_path_lengthsdepthslockX_subset leaves_indexs _/mnt/ssd/data/python-lab/Trading/venv/lib/python3.12/site-packages/sklearn/ensemble/_iforest.py_parallel_compute_tree_depthsr)smQ[>::hE::L   &| 4#L1 2     s ?Ac \eZdZUdZeedddgedheedddeedddgedheedd dgeeedddgd gedgd gd gd gd Z e e d<dddddddddd fd Z dZ dZdZedd fd ZdZdZdZdZdZdZfdZxZS)!ra Isolation Forest Algorithm. Return the anomaly score of each sample using the IsolationForest algorithm The IsolationForest 'isolates' observations by randomly selecting a feature and then randomly selecting a split value between the maximum and minimum values of the selected feature. Since recursive partitioning can be represented by a tree structure, the number of splittings required to isolate a sample is equivalent to the path length from the root node to the terminating node. This path length, averaged over a forest of such random trees, is a measure of normality and our decision function. Random partitioning produces noticeably shorter paths for anomalies. Hence, when a forest of random trees collectively produce shorter path lengths for particular samples, they are highly likely to be anomalies. Read more in the :ref:`User Guide `. .. versionadded:: 0.18 Parameters ---------- n_estimators : int, default=100 The number of base estimators in the ensemble. max_samples : "auto", int or float, default="auto" The number of samples to draw from X to train each base estimator. - If int, then draw `max_samples` samples. - If float, then draw `max_samples * X.shape[0]` samples. - If "auto", then `max_samples=min(256, n_samples)`. If max_samples is larger than the number of samples provided, all samples will be used for all trees (no sampling). contamination : 'auto' or float, default='auto' The amount of contamination of the data set, i.e. the proportion of outliers in the data set. Used when fitting to define the threshold on the scores of the samples. - If 'auto', the threshold is determined as in the original paper. - If float, the contamination should be in the range (0, 0.5]. .. versionchanged:: 0.22 The default value of ``contamination`` changed from 0.1 to ``'auto'``. max_features : int or float, default=1.0 The number of features to draw from X to train each base estimator. - If int, then draw `max_features` features. - If float, then draw `max(1, int(max_features * n_features_in_))` features. Note: using a float number less than 1.0 or integer less than number of features will enable feature subsampling and leads to a longer runtime. bootstrap : bool, default=False If True, individual trees are fit on random subsets of the training data sampled with replacement. If False, sampling without replacement is performed. n_jobs : int, default=None The number of jobs to run in parallel for :meth:`fit`. ``None`` means 1 unless in a :obj:`joblib.parallel_backend` context. ``-1`` means using all processors. See :term:`Glossary ` for more details. random_state : int, RandomState instance or None, default=None Controls the pseudo-randomness of the selection of the feature and split values for each branching step and each tree in the forest. Pass an int for reproducible results across multiple function calls. See :term:`Glossary `. verbose : int, default=0 Controls the verbosity of the tree building process. warm_start : bool, default=False When set to ``True``, reuse the solution of the previous call to fit and add more estimators to the ensemble, otherwise, just fit a whole new forest. See :term:`the Glossary `. .. versionadded:: 0.21 Attributes ---------- estimator_ : :class:`~sklearn.tree.ExtraTreeRegressor` instance The child estimator template used to create the collection of fitted sub-estimators. .. versionadded:: 1.2 `base_estimator_` was renamed to `estimator_`. estimators_ : list of ExtraTreeRegressor instances The collection of fitted sub-estimators. estimators_features_ : list of ndarray The subset of drawn features for each base estimator. estimators_samples_ : list of ndarray The subset of drawn samples (i.e., the in-bag samples) for each base estimator. max_samples_ : int The actual number of samples. offset_ : float Offset used to define the decision function from the raw scores. We have the relation: ``decision_function = score_samples - offset_``. ``offset_`` is defined as follows. When the contamination parameter is set to "auto", the offset is equal to -0.5 as the scores of inliers are close to 0 and the scores of outliers are close to -1. When a contamination parameter different than "auto" is provided, the offset is defined in such a way we obtain the expected number of outliers (samples with decision function < 0) in training. .. versionadded:: 0.20 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 -------- sklearn.covariance.EllipticEnvelope : An object for detecting outliers in a Gaussian distributed dataset. sklearn.svm.OneClassSVM : Unsupervised Outlier Detection. Estimate the support of a high-dimensional distribution. The implementation is based on libsvm. sklearn.neighbors.LocalOutlierFactor : Unsupervised Outlier Detection using Local Outlier Factor (LOF). Notes ----- The implementation is based on an ensemble of ExtraTreeRegressor. The maximum depth of each tree is set to ``ceil(log_2(n))`` where :math:`n` is the number of samples used to build the tree (see (Liu et al., 2008) for more details). References ---------- .. [1] Liu, Fei Tony, Ting, Kai Ming and Zhou, Zhi-Hua. "Isolation forest." Data Mining, 2008. ICDM'08. Eighth IEEE International Conference on. .. [2] Liu, Fei Tony, Ting, Kai Ming and Zhou, Zhi-Hua. "Isolation-based anomaly detection." ACM Transactions on Knowledge Discovery from Data (TKDD) 6.1 (2012): 3. Examples -------- >>> from sklearn.ensemble import IsolationForest >>> X = [[-1.1], [0.3], [0.5], [100]] >>> clf = IsolationForest(random_state=0).fit(X) >>> clf.predict([[0.1], [0], [90]]) array([ 1, 1, -1]) For an example of using isolation forest for anomaly detection see :ref:`sphx_glr_auto_examples_ensemble_plot_isolation_forest.py`. rNleft)closedautorrightg?boolean random_stateverbose) n_estimators max_samples contamination max_features bootstrapn_jobsr0r1 warm_start_parameter_constraintsdrFc Ft |d|d|||| ||| ||_y)NF) estimatorr6bootstrap_featuresr2r3r5r8r7r0r1)super__init__r4) selfr2r3r4r5r6r7r0r1r8 __class__s r(r?zIsolationForest.__init__s? $%#%!%  +c2tdd|jS)Nrrandom)r5splitterr0)r r0r@s r(_get_estimatorzIsolationForest._get_estimators!**   rBctd)Nz"OOB score not supported by iforest)NotImplementedError)r@r ys r(_set_oob_scorezIsolationForest._set_oob_scores!"FGGrBc ddiS)NpreferthreadsrFs r(_parallel_argszIsolationForest._parallel_argss )$$rBT)prefer_skip_nested_validationc t||dgtd}t|r|jt |j }|j |jd}|jd}t|jtr|jdk(r td|}nt|jtjr;|j|kDrtd|jd |d |}n2|j}n%t|j|jdz}||_tt#j$t#j&t)|d }t* |Y|||||d t/|j0Dcgc];}t3|j4j6|j4j9f=c}\|_|_|j>dk(r d |_ |St|r|jC}t#jD|jG|d|j>z|_ |Scc}w)a Fit estimator. Parameters ---------- X : {array-like, sparse matrix} of shape (n_samples, n_features) The input samples. Use ``dtype=np.float32`` for maximum efficiency. Sparse matrices are also supported, use sparse ``csc_matrix`` for maximum efficiency. y : Ignored Not used, present for API consistency by convention. sample_weight : array-like of shape (n_samples,), default=None Sample weights. If None, then samples are equally weighted. Returns ------- self : object Fitted estimator. cscF) accept_sparsedtypeensure_all_finiter)sizer-z max_samples (z/) is greater than the total number of samples (z7). max_samples will be set to n_samples for estimation.r) max_depth sample_weightrggY@)$r tree_dtyper sort_indicesr r0uniformshape isinstancer3strminnumbersrrint max_samples_npceillog2maxr>_fitzip estimators__average_path_lengthtree_n_node_samplescompute_node_depths_average_path_length_per_tree_decision_path_lengthsr4offset_tocsr percentile_score_samples) r@r rJrZrnd n_samplesr3rYrrAs r(fitzIsolationForest.fit&s.  !E7*PU  A; NN  !2!23 KKQWWQZK (GGAJ d&& ,1A1AV1Kc9-K (('*:*: ;)+''4 ( ".. d..;   '  KN !,,  ))B)BCJJ224K G*D,G    ' DLK A; A}}T%8%8%;UTEWEW=WX  /sAIct||j|}tj|t}d||dk<|S)a3 Predict if a particular sample is an outlier or not. Parameters ---------- X : {array-like, sparse matrix} of shape (n_samples, n_features) The input samples. Internally, it will be converted to ``dtype=np.float32`` and if a sparse matrix is provided to a sparse ``csr_matrix``. Returns ------- is_inlier : ndarray of shape (n_samples,) For each observation, tells whether or not (+1 or -1) it should be considered as an inlier according to the fitted model. Notes ----- The predict method can be parallelized by setting a joblib context. This inherently does NOT use the ``n_jobs`` parameter initialized in the class, which is used during ``fit``. This is because, predict may actually be faster without parallelization for a small number of samples, such as for 1000 samples or less. The user can set the number of jobs in the joblib context to control the number of parallel jobs. .. code-block:: python from joblib import parallel_backend # Note, we use threading here as the predict method is not CPU bound. with parallel_backend("threading", n_jobs=4): model.predict(X) )rUr)rdecision_functionre ones_likerc)r@r decision_func is_inliers r(predictzIsolationForest.predictsBD ..q1 LLc: ') -!#$rBc>|j||jz S)ah Average anomaly score of X of the base classifiers. The anomaly score of an input sample is computed as the mean anomaly score of the trees in the forest. The measure of normality of an observation given a tree is the depth of the leaf containing this observation, which is equivalent to the number of splittings required to isolate this point. In case of several observations n_left in the leaf, the average path length of a n_left samples isolation tree is added. Parameters ---------- X : {array-like, sparse matrix} of shape (n_samples, n_features) The input samples. Internally, it will be converted to ``dtype=np.float32`` and if a sparse matrix is provided to a sparse ``csr_matrix``. Returns ------- scores : ndarray of shape (n_samples,) The anomaly score of the input samples. The lower, the more abnormal. Negative scores represent outliers, positive scores represent inliers. Notes ----- The decision_function method can be parallelized by setting a joblib context. This inherently does NOT use the ``n_jobs`` parameter initialized in the class, which is used during ``fit``. This is because, calculating the score may actually be faster without parallelization for a small number of samples, such as for 1000 samples or less. The user can set the number of jobs in the joblib context to control the number of parallel jobs. .. code-block:: python from joblib import parallel_backend # Note, we use threading here as the decision_function method is # not CPU bound. with parallel_backend("threading", n_jobs=4): model.decision_function(X) ) score_samplesrrr@r s r(r{z!IsolationForest.decision_functionsb!!!$t||33rBcNt||dtdd}|j|S)am Opposite of the anomaly score defined in the original paper. The anomaly score of an input sample is computed as the mean anomaly score of the trees in the forest. The measure of normality of an observation given a tree is the depth of the leaf containing this observation, which is equivalent to the number of splittings required to isolate this point. In case of several observations n_left in the leaf, the average path length of a n_left samples isolation tree is added. Parameters ---------- X : {array-like, sparse matrix} of shape (n_samples, n_features) The input samples. Returns ------- scores : ndarray of shape (n_samples,) The anomaly score of the input samples. The lower, the more abnormal. Notes ----- The score function method can be parallelized by setting a joblib context. This inherently does NOT use the ``n_jobs`` parameter initialized in the class, which is used during ``fit``. This is because, calculating the score may actually be faster without parallelization for a small number of samples, such as for 1000 samples or less. The user can set the number of jobs in the joblib context to control the number of parallel jobs. .. code-block:: python from joblib import parallel_backend # Note, we use threading here as the score_samples method is not CPU bound. with parallel_backend("threading", n_jobs=4): model.score(X) csrF)rTrUresetrV)rr[rurs r(rzIsolationForest.score_sampless4V   #  ""1%%rBc<t||j| S)zPrivate version of score_samples without input validation. Input validation would remove feature names, so we disable it. )r_compute_chunked_score_samplesrs r(ruzIsolationForest._score_sampless" 33A666rBct|}|j|jdk(rd}nd}td|jz|}t ||}t j |d}|D]}|j|||||<|S)NrFT) row_bytes max_n_rowsforder)r _max_featuresr^rrrezeros_compute_score_samples)r@r rwsubsample_features chunk_n_rowsslicesscoressls r(rz.IsolationForest._compute_chunked_score_sampless O    +!& !% (4---) Y 5)3/ PB44QrUz9IsolationForest._compute_score_samples..as` +*4 3G1 2.D++H5228<  sA A r)outwhere)r^rerrl _max_samples threadingLockrr1 enumeraterjrkestimators_features_lendivider|) r@r rrwaverage_path_length_max_samples denominatorrr$r%s ``` @@r(rz&IsolationForest._compute_score_samples>s"GGAJ )3/*>@Q@Q?R*S'~~ LL  /8D$$d&?&?@/  $$**+.MM YY f)=[TUEU   rBcFt|}d|j_|S)NT)r>__sklearn_tags__ input_tags allow_nan)r@tagsrAs r(rz IsolationForest.__sklearn_tags__zs!w')$(! rB)NN)__name__ __module__ __qualname____doc__rrrrrr9dict__annotations__r?rGrKrPr rxrr{rrurrr __classcell__)rAs@r(rr6s(hV"(AtFCD x Xq$v 6 ZAg 6 x T1c' 2  T1a 0  [T"'(; k'$D2+: H%5X6Xt&P14f4&l 7@:xrBct|d}|j}|jd}tj|j}|dk}|dk(}tj ||}d||<d||<dtj ||dz tjzzd||dz z||z z ||<|j|S) a The average path length in a n_samples iTree, which is equal to the average path length of an unsuccessful BST search since the latter has the same structure as an isolation tree. Parameters ---------- n_samples_leaf : array-like of shape (n_samples,) The number of training samples in each test sample leaf, for each estimators. Returns ------- average_path_length : ndarray of shape (n_samples,) F) ensure_2d)rrzrrgrg@)r r^reshaperer logical_orlog euler_gamma)n_samples_leafn_samples_leaf_shapeaverage_path_lengthmask_1mask_2not_masks r(rlrls !5AN)//#++G4N((>#7#78 q F q F ff--H"%"% rvvnX.45FG )C/ 0>(3K K L!  & &'; <rsf"!-%, /FF.KK!   2G lKG T!=rB