1、简介
孤立森林(Isolation Forest)是另外一种高效的异常检测算法,它和随机森林类似,但每次选择划分属性和划分点(值)时都是随机的,而不是根据信息增益或者基尼指数来选择。
在建树过程中,如果一些样本很快就到达了叶子节点(即叶子到根的距离d很短),那么就被认为很有可能是异常点。
因为那些路径d比较短的样本,都是因为距离主要的样本点分布中心比较远的。也就是说,可以通过计算样本在所有树中的平均路径长度来寻找异常点。
sklearn提供了ensemble.IsolationForest模块可用于Isolation Forest算法。
2、主要参数和函数介绍
class sklearn.ensemble.IsolationForest(n_estimators=100, max_samples=’auto’, contamination=0.1, max_features=1.0, bootstrap=False, n_jobs=1, random_state=None, verbose=0)
n_estimators : 森林中树的颗数, int, optional (default=100)
max_samples : 对每棵树,样本个数或比例,int or float, optional (default=”auto”)
contamination : 用户设置样本中异常点的比例,float in (0., 0.5), optional (default=0.1)
max_features : 对每棵树,特征个数或比例函数:int or float, optional (default=1.0)
fit(X): Fit estimator.(无监督)
predict(X): 返回值:+1 表示正常样本, -1表示异常样本。
decision_function(X): 返回样本的异常评分。 值越小表示越有可能是异常样本。
from sklearn.ensemble import IsolationForest
iforest=IsolationForest(n_estimators=100,random_state=1)
iforest.fit(df)
index_list=[]
ipredict=iforest.predict(df)
for i,j in enumerate(ipredict):
if j==1:
index_list.append(i)
df=df.ix[index_list,:]
print(df)