freeEDU/Log-Decoder
0
1"""2The implementation of IsolationForest model for anomaly detection.3 4Authors: 5 LogPAI Team6 7Reference: 8 [1] Fei Tony Liu, Kai Ming Ting, Zhi-Hua Zhou. Isolation Forest. International9 Conference on Data Mining (ICDM), 2008.10 11"""12 13 14 15 16 17import numpy as np18from sklearn.ensemble import IsolationForest as iForest19from ..utils import metrics20 21class IsolationForest(iForest):22 23 def __init__(self, n_estimators=100, max_samples='auto', contamination=0.03, **kwargs):24 """ The IsolationForest model for anomaly detection25 26 Arguments27 ---------28 n_estimators : int, optional (default=100). The number of base estimators in the ensemble.29 max_samples : int or float, optional (default="auto")30 The number of samples to draw from X to train each base estimator.31 - If int, then draw max_samples samples.32 - If float, then draw max_samples * X.shape[0] samples.33 - If "auto", then max_samples=min(256, n_samples).34 If max_samples is larger than the number of samples provided, all samples will be used 35 for all trees (no sampling).36 contamination : float in (0., 0.5), optional (default='auto')37 The amount of contamination of the data set, i.e. the proportion of outliers in the data 38 set. Used when fitting to define the threshold on the decision function. If 'auto', the 39 decision function threshold is determined as in the original paper.40 max_features : int or float, optional (default=1.0)41 The number of features to draw from X to train each base estimator.42 - If int, then draw max_features features.43 - If float, then draw max_features * X.shape[1] features.44 bootstrap : boolean, optional (default=False)45 If True, individual trees are fit on random subsets of the training data sampled with replacement. 46 If False, sampling without replacement is performed.47 n_jobs : int or None, optional (default=None)48 The number of jobs to run in parallel for both fit and predict. None means 1 unless in a 49 joblib.parallel_backend context. -1 means using all processors. 50 random_state : int, RandomState instance or None, optional (default=None)51 If int, random_state is the seed used by the random number generator; 52 If RandomState instance, random_state is the random number generator; 53 If None, the random number generator is the RandomState instance used by np.random.54 55 Reference56 ---------57 For more information, please visit https://scikit-learn.org/stable/modules/generated/sklearn.ensemble.IsolationForest.html58 """59 60 super(IsolationForest, self).__init__(n_estimators=n_estimators, max_samples=max_samples, 61 contamination=contamination, **kwargs)62 63 64 def fit(self, X):65 """66 Auguments67 ---------68 X: ndarray, the event count matrix of shape num_instances-by-num_events69 """70 71 print('====== Model summary ======')72 super(IsolationForest, self).fit(X)73 74 def predict(self, X):75 """ Predict anomalies with mined invariants76 77 Arguments78 ---------79 X: the input event count matrix80 81 Returns82 -------83 y_pred: ndarray, the predicted label vector of shape (num_instances,)84 """85 86 y_pred = super(IsolationForest, self).predict(X)87 y_pred = np.where(y_pred > 0, 0, 1)88 return y_pred89 90 def evaluate(self, X, y_true):91 print('====== Evaluation summary ======')92 y_pred = self.predict(X)93 precision, recall, f1 = metrics(y_pred, y_true)94 print('Precision: {:.3f}, recall: {:.3f}, F1-measure: {:.3f}\n'.format(precision, recall, f1))95 return precision, recall, f196 97 