from sklearn.neighbors import LocalOutlierFactor
import numpy as np
# Example dataset with 2 features
X = [[-1.1, -1.1], [-2, -1.9], [-1.1, -1.2], [-1.3, -1.3], [15, 15], [14, 13], [1, 1], [10, 3]]
# Instantiate the LOF
lof = LocalOutlierFactor(n_neighbors=2)
# Fit the model to the data (unsupervised so no y value)
lof.fit(X)
# Retrieve the anomaly score of each sample
# The lower, the more normal;
# The higher, the more abnormal.
lof_scores = -lof.negative_outlier_factor_
# Finding some threshold, say 1.5, for marking the outliers
threshold = 1.5
outliers = lof_scores > threshold
# Print the computed LOF scores and outliers
for i, score in enumerate(lof_scores):
print(f"Data point {i}: LOF score {score:.2f}, Outlier: {outliers[i]}")
# If you want to predict whether or not a new data point is an outlier,
# you can use the _predict_ method.
# For instance, for a new data point X_new
X_new = [[-1, -1], [0, 0], [12, 14]]
new_scores = -lof.fit_predict(X_new)
print(f"New data point predictions (1:normal, -1:outlier): {new_scores}")
Remember that the n_neighbors parameter affects the LOF calculations. It should be set based on your specific dataset and how tightly you expect your points to cluster. In practice, you might want to iterate over a range of n_neighbors values to determine what works best for your data.
The negative outlier factor values are negated here because the scikit-learn implementation returns negative values where smaller numbers represent more normal points and larger numbers (closer to zero) represent outliers. We negate these to follow the traditional LOF interpretation, where higher values indicate outliers.
This is a basic example, but in real-world scenarios, you might have to pre-process your data (handle missing values, standardize features, etc.) before applying LOF or any other anomaly detection algorithm. Also, the choice of n_neighbors and the threshold for determining outliers may require some experimentation and domain knowledge.