def local_outlier_factor_cluster(err, data, k=20, k_lof=5): ''' :param clusters: cluster centroids 2D tensor :param data: data 2D tensor :param k: number of nearest neighbours to consider as LOF dataset :param k_lof: number of neigh to consider when computing LOF statistics :return: ''' # err = pairwise_distances(clusters, data) nearest_vals = torch.min(err, dim=0, keepdim=True) nearest_units = nearest_vals.indices.numpy().flatten() lof_score = [] i = 0 for index in nearest_units: # for each data point append their k-nearest point of the same cluster k_nearest_points = torch.topk(err[index, :], k=k, largest=False).indices.cpu().numpy() lof = LocalOutlierFactor(n_neighbors=k_lof, contamination='auto') pre_lof = -lof.fit(data[k_nearest_points]).negative_outlier_factor_ post_lof = -lof.fit( torch.cat((data[k_nearest_points], data[i].view( 1, -1)))).negative_outlier_factor_ lof_score.append(abs(post_lof[-1] / np.max(pre_lof))) i += 1 return np.array(lof_score)
class LOFNoveltyFilter (StaticFilter, _InputsStatBasedInitializable): def __init__(self, name = 'LOF-based novelty', sample_size = 3000, metric = 'cosine', lof_kwds = {}, **kwds): assert (isinstance (sample_size, int) and 1 <= sample_size) self.name = name self.sample_size = sample_size self.lof_threshold = 0.0 self.lof = LocalOutlierFactor (**lof_kwds, metric = metric, novelty = True) super().__init__(**kwds) def inputs_stat_initialize (self, train_data: raw_datat = None, test_data: raw_datat = None): sample_size = min (self.sample_size, train_data.data.shape[0]) np1 ('Initializing LOF-based novelty estimator with {} training samples... ' .format (sample_size)) # TODO: random sampling (& shuffle)?. self.lof.fit (train_data.data[:sample_size]) c1 ('done') p1 ('{} offset is {}'.format (self.name, self.lof.offset_)) def close_enough (self, i: Input): lof = self.lof.decision_function (i.reshape (1, -1)) # p1 ('{}: {}'.format (self.name, lof)) return lof > self.lof_threshold
def _localoutlierfactor(*, train, test, x_predict=None, metrics, n_neighbors=20, algorithm='auto', leaf_size=30, metric='minkowski', p=2, metric_params=None, contamination='auto', novelty=False, n_jobs=None): """ For more info visit : https://scikit-learn.org/stable/modules/generated/sklearn.neighbors.LocalOutlierFactor.html#sklearn.neighbors.LocalOutlierFactor """ model = LocalOutlierFactor(n_neighbors=n_neighbors, algorithm=algorithm, leaf_size=leaf_size, metric=metric, p=p, metric_params=metric_params, contamination=contamination, novelty=novelty, n_jobs=n_jobs) model.fit(train[0], train[1]) model_name = 'Local Outlier Factor' y_hat = model.predict(test[0]) if metrics == 'accuracy': accuracy = accuracy_score(test[1], y_hat) if metrics == 'f1': accuracy = f1_score(test[1], y_hat) if metrics == 'jaccard': accuracy = jaccard_score(test[1], y_hat) if x_predict is None: return (model_name, accuracy, None) y_predict = model.predict(x_predict) return (model_name, accuracy, y_predict)
def LOF(dataset): data = get_table_content(dataset) model = LocalOutlierFactor(n_neighbors=4, contamination=0.1, novelty=True) model.fit(numpy.array(data)[:, 0:2]) y = model._predict(numpy.array(data)[:, 0:2]) # 若样本点正常,返回1,不正常,返回-1 print(y) pass
class LOFNovelty: def __init__(self): self.clf = LocalOutlierFactor(novelty=True, contamination=0.1) self.scaler = StandardScaler() def train(self, train): #train = self.scaler.fit_transform(train) self.clf.fit(train) def predict(self, valid, anomaly): #valid = self.scaler.fit_transform(valid) #anomaly = self.scaler.fit_transform(anomaly) y_pred_valid = self.clf.predict(valid) y_pred_outliers = self.clf.predict(anomaly) score_valid = self.clf.decision_function(valid) score_anomaly = self.clf.decision_function(anomaly) print("LOF Novelty result") print(confusion_matrix([1] * len(y_pred_valid), y_pred_valid).ravel()) print( confusion_matrix([-1] * len(y_pred_outliers), y_pred_outliers).ravel()) print(" Validation data:", list(y_pred_valid).count(1) / y_pred_valid.shape[0]) #print("Score", score_valid.mean(), score_valid.std()) print(" Outlier data:", list(y_pred_outliers).count(-1) / y_pred_outliers.shape[0])
def get_novelties(train_data, something_else, pos, neg): """ :param train_data: vector embeddings of text train data :param something_else: vector embeddings of "something else" user utterances :param pos: vector embeddings of user utterances resulting in positive feedback :param neg: vector embeddings of user utterances resulting in negative feedback :return: novelty scores of all data passed in """ clf = LocalOutlierFactor(n_neighbors=20, novelty=True, contamination='auto') clf.fit(train_data) y_train_scores = clf.negative_outlier_factor_ y_train_scores = pd.DataFrame(y_train_scores, columns=['score']) y_train_scores['dataset'] = 'train' something_else_scores = clf.score_samples(something_else) # outlier scores something_else_scores = pd.Series(something_else_scores, name='score') something_else_scores = something_else_scores.to_frame() something_else_scores['dataset'] = 'something else' pos_scores = clf.score_samples(pos) # outlier scores pos_scores = pd.Series(pos_scores, name='score') pos_scores = pos_scores.to_frame() pos_scores['dataset'] = 'positive feedback' neg_scores = clf.score_samples(neg) # outlier scores neg_scores = pd.Series(neg_scores, name='score') neg_scores = neg_scores.to_frame() neg_scores['dataset'] = 'negative feedback' scores = pd.concat( [y_train_scores, something_else_scores, pos_scores, neg_scores]).reset_index(drop=True) return scores
class LocalOutlierFactorAD(ADModel): def __init__(self): super().__init__() self.clf = None self.scaler = None # Model Hyperparams thresholds = np.arange(-0.5, 0.5, 0.25) contamination = [0.05] nn = [20] self.params = [(c, n, t) for n in nn for c in contamination for t in thresholds] self.contamination = None self.n_neighbors = None self.threshold = None def config(self, hyperparam_tuple): contamination, nearest_n, thresh = hyperparam_tuple self.contamination = contamination self.n_neighbors = nearest_n self.threshold = thresh def train(self, X, y, verbose = False): # Scale features self.scaler = StandardScaler() self.scaler.fit(X) self.clf = LocalOutlierFactor(contamination = self.contamination, n_neighbors = self.n_neighbors) X_scaled = self.scaler.transform(X) self.clf.fit(X_scaled) def predict(self, X, **kwargs): preds = self.clf._decision_function(self.scaler.transform(X)) print(preds) preds = (preds < self.threshold).astype(np.int32).reshape(-1, 1) print(preds) return preds
def perform_outlier_detection(self, X): # LOF on all features clf = LocalOutlierFactor(n_neighbors=20) clf.fit(X) lof_scores = clf._decision_function(X) lof_scores = clf._decision_function(X) # Isolation forest on all features clf = IsolationForest() clf.fit(X) forest_scores = clf.decision_function(X) ''' clf = DBOD() clf.fit(X) distance_scores = clf.decision_function_distance(X) #abod_scores = ABOD(X, self.seed_user) abod_scores = clf.decision_function_angle(X) scores = self.combine([lof_scores, forest_scores, distance_scores, abod_scores]) ''' # scores = forest_scores scores = self.combine([lof_scores, forest_scores]) ''' with open('clique_expansion/' + self.seed_user + '_unnormalized_scores.csv', 'w') as f: for score in scores: f.write(str(score) + '\n') ''' new_scores = scores[self.len_priors:] user_scores = sorted(zip(self.current_level_users, new_scores), key=lambda x: x[1], reverse=True) threshold = np.percentile(new_scores, 8) outliers = [u[0] for u in user_scores if u[1] <= threshold] return outliers
def trian_out_of_date(format_dir, model_dir): """ 聚类去除参考文献时间与文献发表时间差的时间的异常点 参考文献 http://scikit-learn.org/stable/auto_examples/neighbors/plot_lof.html#sphx-glr-auto-examples-neighbors-plot-lof-py https://zhuanlan.zhihu.com/p/37753692 """ print("[START] train out of date") origin_dates = [] for paper in os.listdir(format_dir): with open(format_dir + paper, 'r', encoding="utf-8") as format_data: _format_data = format_data.read() _format_data = json.loads(_format_data) origin_dates += _format_data["out_of_date"] # 一维数据转二维 origin_dates = list(zip(origin_dates, np.zeros_like(origin_dates))) clf = LocalOutlierFactor(n_neighbors=20) # fit非监督训练 clf.fit(origin_dates) # 离群系数 outlier = clf.kneighbors(origin_dates)[0].max(axis=1) # 参考文献发表日期 与 文献发表日期的时间差中 最后一个非离群点 out_of_date = 0 for i, _d in enumerate(origin_dates): if outlier[i] == 0 and _d[0] > out_of_date: out_of_date = _d[0] with open(model_dir + 'outlier.txt', 'w') as data: data.write(str(out_of_date)) print("[DONE] train out of date")
def fingerprint_outlier_detector(res_dir, res_dim, outlier_model_path, data_exist=False, train_feat_path=''): ''' :param res_dir: :param outlier_model_path: :param data_exist: :param train_feat_path: :return: ''' if not data_exist: logging.info("Creating Training Feature set") train_feat = texture_feat_extract(res_dir, res_dim) else: assert os.path.isfile(train_feat_path) logging.info("[STATUS] Loading Training Feature set") with open(train_feat_path, 'rb') as f: train_feat = pickle.load(f) # create the classifier logging.info("[STATUS] Creating the classifier..") clf = LocalOutlierFactor(n_neighbors=30, novelty=True, contamination=0.0001) # fit the training data and labels logging.info("[STATUS] Fitting data/label to model..") clf.fit(train_feat) joblib.dump(clf, outlier_model_path) return
def do_LOF(data: pd.DataFrame, column_name: str, base_path: str, neighbors: int = 100, plot: bool = False): """ This function performs a LOF computation for given data. :param data: features :param column_name: feature name :param base_path: path to folder, to save plots :param neighbors: number of neighbors to consider :param plot: whether to visualize the LOF or not """ # select column data[column_name + '_' + 'outlier'] = [None] * len(data) # configure algorithm algorithm = LocalOutlierFactor(n_neighbors=neighbors, contamination=0.2) # prepare data X = np.array(data[column_name]).reshape(-1, 1) # fit LOF and assign classes to the observations algorithm.fit(X) y_pred = algorithm.fit_predict(X) for idx, y in enumerate(y_pred): data.at[idx, column_name + '_' + 'outlier'] = y == -1 if plot: histo_scatter(data, X, y_pred, column_name, base_path)
def perform_outlier_detection(self, X, len_priors): # LOF on all features clf = LocalOutlierFactor(n_neighbors=20) clf.fit(X) check_is_fitted(clf, ["threshold_", "negative_outlier_factor_", "n_neighbors_", "_distances_fit_X_"]) if X is not None: X = check_array(X, accept_sparse='csr') y_pred = clf._decision_function(X) else: y_pred = clf.negative_outlier_factor_ #lof_scores = y_pred[len_priors:] #lof_scores = zip(self.current_level_users, y_pred_new) lof_scores = y_pred # Isolation forest on all features clf = IsolationForest() clf.fit(X) y_pred = clf.decision_function(X) #forest_scores = y_pred[len_priors:] #forest_scores = zip(self.current_level_users, y_pred_new) forest_scores = y_pred scores = self.combine(lof_scores, forest_scores) new_scores = scores[len_priors:] user_scores = sorted(zip(self.current_level_users, new_scores), key=lambda x: x[1], reverse=True) threshold = np.percentile(new_scores, 95) outliers = [u[0] for u in user_scores if u[1] >= threshold] return outliers
def predict_LocalOutlierFactor(X, fraction_outlier): xx, yy = get_meshgrid(X) x1, x2 = xx.min(), xx.max() y1, y2 = yy.min(), yy.max() d = (x2 - x2) * 0.1 A = LocalOutlierFactor(contamination=fraction_outlier, novelty=True) A.fit(X) Y = A.predict(X) confidence_mat = numpy.array([(A.predict(x.reshape(-1, 2))).astype(int) for x in numpy.c_[xx.flatten(), yy.flatten()]]) grid_confidence = (confidence_mat).reshape((100, 100)) P.plot_contourf(X[Y > 0], X[Y <= 0], xx, yy, grid_confidence, x_range=[x1 - d, x2 + d], y_range=[y1 - d, y2 + d], filename_out='5_pred_LocalOutlierFactor_density.png') P.plot_2D_features_multi_Y(X, -Y, x_range=[x1 - d, x2 + d], y_range=[y1 - d, y2 + d], filename_out='5_pred_LocalOutlierFactor.png') return
class LOF(BaseDetector): """Wrapper of scikit-learn LOF Class with more functionalities. Unsupervised Outlier Detection using Local Outlier Factor (LOF). The anomaly score of each sample is called Local Outlier Factor. It measures the local deviation of density of a given sample with respect to its neighbors. It is local in that the anomaly score depends on how isolated the object is with respect to the surrounding neighborhood. More precisely, locality is given by k-nearest neighbors, whose distance is used to estimate the local density. By comparing the local density of a sample to the local densities of its neighbors, one can identify samples that have a substantially lower density than their neighbors. These are considered outliers. See :cite:`breunig2000lof` for details. Parameters ---------- n_neighbors : int, optional (default=20) Number of neighbors to use by default for `kneighbors` queries. If n_neighbors is larger than the number of samples provided, all samples will be used. algorithm : {'auto', 'ball_tree', 'kd_tree', 'brute'}, optional Algorithm used to compute the nearest neighbors: - 'ball_tree' will use BallTree - 'kd_tree' will use 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, optional (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. metric : string or callable, default 'minkowski' metric used for the distance computation. Any metric from scikit-learn or scipy.spatial.distance can be used. If 'precomputed', the training input X is expected to be a distance matrix. If metric is a callable function, it is called on each pair of instances (rows) and the resulting value recorded. The callable should take two arrays as input and return one value indicating the distance between them. This works for Scipy's metrics, but is less efficient than passing the metric name as a string. Valid values for metric are: - from scikit-learn: ['cityblock', 'cosine', 'euclidean', 'l1', 'l2', 'manhattan'] - from scipy.spatial.distance: ['braycurtis', 'canberra', 'chebyshev', 'correlation', 'dice', 'hamming', 'jaccard', 'kulsinski', 'mahalanobis', 'matching', 'minkowski', 'rogerstanimoto', 'russellrao', 'seuclidean', 'sokalmichener', 'sokalsneath', 'sqeuclidean', 'yule'] See the documentation for scipy.spatial.distance for details on these metrics: http://docs.scipy.org/doc/scipy/reference/spatial.distance.html p : integer, optional (default = 2) Parameter for the Minkowski metric from sklearn.metrics.pairwise.pairwise_distances. 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. See http://scikit-learn.org/stable/modules/generated/sklearn.metrics.pairwise.pairwise_distances metric_params : dict, optional (default = None) Additional keyword arguments for the metric function. contamination : float in (0., 0.5), optional (default=0.1) The amount of contamination of the data set, i.e. the proportion of outliers in the data set. When fitting this is used to define the threshold on the decision function. n_jobs : int, optional (default = 1) The number of parallel jobs to run for neighbors search. If ``-1``, then the number of jobs is set to the number of CPU cores. Affects only kneighbors and kneighbors_graph methods. Attributes ---------- n_neighbors_ : int The actual number of neighbors used for `kneighbors` queries. decision_scores_ : numpy array of shape (n_samples,) The outlier scores of the training data. The higher, the more abnormal. Outliers tend to have higher scores. This value is available once the detector is fitted. threshold_ : float The threshold is based on ``contamination``. It is the ``n_samples * contamination`` most abnormal samples in ``decision_scores_``. The threshold is calculated for generating binary outlier labels. labels_ : int, either 0 or 1 The binary labels of the training data. 0 stands for inliers and 1 for outliers/anomalies. It is generated by applying ``threshold_`` on ``decision_scores_``. """ def __init__(self, n_neighbors=20, algorithm='auto', leaf_size=30, metric='minkowski', p=2, metric_params=None, contamination=0.1, n_jobs=1): super(LOF, self).__init__(contamination=contamination) self.n_neighbors = n_neighbors self.algorithm = algorithm self.leaf_size = leaf_size self.metric = metric self.p = p self.metric_params = metric_params self.n_jobs = n_jobs # noinspection PyIncorrectDocstring def fit(self, X, y=None): """Fit detector. y is optional for unsupervised methods. Parameters ---------- X : numpy array of shape (n_samples, n_features) The input samples. y : numpy array of shape (n_samples,), optional (default=None) The ground truth of the input samples (labels). """ # validate inputs X and y (optional) X = check_array(X) self._set_n_classes(y) self.detector_ = LocalOutlierFactor(n_neighbors=self.n_neighbors, algorithm=self.algorithm, leaf_size=self.leaf_size, metric=self.metric, p=self.p, metric_params=self.metric_params, contamination=self.contamination, n_jobs=self.n_jobs) self.detector_.fit(X=X, y=y) # Invert decision_scores_. Outliers comes with higher outlier scores self.decision_scores_ = invert_order( self.detector_.negative_outlier_factor_) self._process_decision_scores() return self def decision_function(self, X): """Predict raw anomaly score of X using the fitted detector. The anomaly score of an input sample is computed based on different detector algorithms. For consistency, outliers are assigned with larger anomaly scores. Parameters ---------- X : numpy array of shape (n_samples, n_features) The training input samples. Sparse matrices are accepted only if they are supported by the base estimator. Returns ------- anomaly_scores : numpy array of shape (n_samples,) The anomaly score of the input samples. """ check_is_fitted(self, ['decision_scores_', 'threshold_', 'labels_']) # Invert outlier scores. Outliers comes with higher outlier scores # noinspection PyProtectedMember if _sklearn_version_20(): return invert_order(self.detector_._score_samples(X)) else: return invert_order(self.detector_._decision_function(X)) @property def n_neighbors_(self): """The actual number of neighbors used for kneighbors queries. Decorator for scikit-learn LOF attributes. """ return self.detector_.n_neighbors_
print 'exp num:', ne X, y = sh(X, y) X_train = X[:n_samples_train, :] X_test = X[n_samples_train:, :] y_train = y[:n_samples_train] y_test = y[n_samples_train:] # # training only on normal data: # X_train = X_train[y_train == 0] # y_train = y_train[y_train == 0] print('LocalOutlierFactor processing...') model = LocalOutlierFactor(n_neighbors=20) tstart = time() model.fit(X_train) fit_time += time() - tstart tstart = time() scoring = -model.decision_function(X_test) # the lower,the more normal predict_time += time() - tstart fpr_, tpr_, thresholds_ = roc_curve(y_test, scoring) if fit_time + predict_time > max_time: raise TimeoutError f = interp1d(fpr_, tpr_) tpr += f(x_axis) tpr[0] = 0. precision_, recall_ = precision_recall_curve(y_test, scoring)[:2]
lb = LabelBinarizer() x1 = lb.fit_transform(X[:, 1].astype(str)) x2 = lb.fit_transform(X[:, 2].astype(str)) x3 = lb.fit_transform(X[:, 3].astype(str)) X = np.c_[X[:, :1], x1, x2, x3, X[:, 4:]] y = (y != b'normal.').astype(int) if dataset_name == 'http' or dataset_name == 'smtp': y = (y != b'normal.').astype(int) X = X.astype(float) print('LocalOutlierFactor processing...') model = LocalOutlierFactor(n_neighbors=20) tstart = time() model.fit(X) fit_time = time() - tstart scoring = -model.negative_outlier_factor_ # the lower, the more normal fpr, tpr, thresholds = roc_curve(y, scoring) AUC = auc(fpr, tpr) plt.plot(fpr, tpr, lw=1, label=('ROC for %s (area = %0.3f, train-time: %0.2fs)' % (dataset_name, AUC, fit_time))) plt.xlim([-0.05, 1.05]) plt.ylim([-0.05, 1.05]) plt.xlabel('False Positive Rate') plt.ylabel('True Positive Rate') plt.title('Receiver operating characteristic') plt.legend(loc="lower right") plt.show()
lim_inf = X.min(axis=0) lim_sup = X.max(axis=0) volume_support = (lim_sup - lim_inf).prod() t = np.arange(0, 100 / volume_support, 0.01 / volume_support) axis_alpha = np.arange(alpha_min, alpha_max, 0.0001) unif = np.random.uniform(lim_inf, lim_sup, size=(n_generated, n_features)) # fit: print('IsolationForest processing...') iforest = IsolationForest() iforest.fit(X_train) s_X_iforest = iforest.decision_function(X_test) print('LocalOutlierFactor processing...') lof = LocalOutlierFactor(n_neighbors=20) lof.fit(X_train) s_X_lof = lof.decision_function(X_test) print('OneClassSVM processing...') ocsvm = OneClassSVM() ocsvm.fit(X_train[:min(ocsvm_max_train, n_samples_train - 1)]) s_X_ocsvm = ocsvm.decision_function(X_test).reshape(1, -1)[0] s_unif_iforest = iforest.decision_function(unif) s_unif_lof = lof.decision_function(unif) s_unif_ocsvm = ocsvm.decision_function(unif).reshape(1, -1)[0] plt.subplot(121) auc_iforest, em_iforest, amax_iforest = em(t, t_max, volume_support, s_unif_iforest, s_X_iforest, n_generated) auc_lof, em_lof, amax_lof = em(t, t_max, volume_support,
np.random.seed(42) xx, yy = np.meshgrid(np.linspace(-5, 5, 500), np.linspace(-5, 5, 500)) # Generate normal (not abnormal) training observations X = 0.3 * np.random.randn(100, 2) X_train = np.r_[X + 2, X - 2] # Generate new normal (not abnormal) observations X = 0.3 * np.random.randn(20, 2) X_test = np.r_[X + 2, X - 2] # Generate some abnormal novel observations X_outliers = np.random.uniform(low=-4, high=4, size=(20, 2)) # fit the model for novelty detection (novelty=True) clf = LocalOutlierFactor(n_neighbors=20, novelty=True, contamination=0.1) clf.fit(X_train) # DO NOT use predict, decision_function and score_samples on X_train as this # would give wrong results but only on new unseen data (not used in X_train), # e.g. X_test, X_outliers or the meshgrid y_pred_test = clf.predict(X_test) y_pred_outliers = clf.predict(X_outliers) n_error_test = y_pred_test[y_pred_test == -1].size n_error_outliers = y_pred_outliers[y_pred_outliers == 1].size # plot the learned frontier, the points, and the nearest vectors to the plane Z = clf.decision_function(np.c_[xx.ravel(), yy.ravel()]) Z = Z.reshape(xx.shape) plt.title("Novelty Detection with LOF") plt.contourf(xx, yy, Z, levels=np.linspace(Z.min(), 0, 7), cmap=plt.cm.PuBu) a = plt.contour(xx, yy, Z, levels=[0], linewidths=2, colors='darkred')