我想为时间序列生成一个非常简单的异常检测示例。所以我用一个非常明显的异常值创建了样本数据。这是数据的图片:
问题是,到目前为止,我还没有任何方法可以可靠地检测异常值。我尝试了局部异常因子、隔离森林、k 最近邻和 DBSCAN。根据我的阅读,至少其中一种方法应该是合适的。我也尝试调整参数,但这并没有真正帮助。
我在这里犯了什么错误?方法不合适吗?
下面是一个代码示例。
提前致谢!
import numpy as np
import matplotlib.pyplot as plt
np.random.seed(1)
t=np.linspace(0,10,101).reshape(-1,1)
y_test=0.5+t+t**2+2*np.random.randn(len(t),1)
y_test[10]=y_test[10]*7
plt.figure(1)
plt.plot(t,y_test)
plt.show;
from sklearn.neighbors import LocalOutlierFactor
clf=LocalOutlierFactor(contamination=0.1)
pred=clf.fit_predict(y_test)
plt.figure(3)
plt.plot(t[pred==1],y_test[pred==1],'bx')
plt.plot(t[pred==-1],y_test[pred==-1],'ro')
plt.show
from sklearn.ensemble import IsolationForest
clf=IsolationForest(behaviour='new',contamination='auto')
pred=clf.fit_predict(y_test)
plt.figure(4)
plt.plot(t[pred==1],y_test[pred==1],'bx')
plt.plot(t[pred==-1],y_test[pred==-1],'ro')
plt.show
from pyod.models.knn import KNN
clf = KNN()
clf.fit(y_test)
pred=clf.predict(y_test)
plt.figure(5)
plt.plot(t[pred==0],y_test[pred==0],'bx')
plt.plot(t[pred==1],y_test[pred==1],'ro')
plt.show
from sklearn.cluster import DBSCAN
clf = DBSCAN(min_samples=10,eps=3)
pred=clf.fit_predict(y_test)
plt.figure(5)
plt.plot(t[pred==0],y_test[pred==0],'bx')
plt.plot(t[pred==1],y_test[pred==1],'ro')
plt.show