孤立森林理论+例子

前言

孤立森林(Isolation Forest)简称iForest,是无监督的模型,常用于异常检测。在一大堆数据中,找出与其它数据的规律不太符合的数据

孤立森林将异常识别为树上平均路径较短的观测结果。每个孤立树都应用了一个过程:

  • 随机选择特征
  • 通过在所选特征的最大值和最小值之间随机选择一个值来分割数据点。

程序

  • 简单例子
import numpy as np
import matplotlib.pyplot as plt
from sklearn.ensemble import IsolationForest

# 伪随机数生成器
# 伪随机数是用确定性的算法计算出来的似来自[0,1]均匀分布的随机数序列
rng = np.random.RandomState(42)

# Generate train data
X = 0.3 * rng.randn(100, 2)
X_train = np.r_[X + 2, X - 2]   # np.r_:按列连接两个矩阵,就是把两矩阵上下相加,要求列数相等
print(X_train.shape)
# Generate some regular novel observations
X = 0.3 * rng.randn(20, 2)
X_test = np.r_[X + 2, X - 2]
# Generate some abnormal novel observations
X_outliers = rng.uniform(low=-4, high=4, size=(20, 2)) # 从一个均匀分布[low,high)中随机采样,注意定义域是左闭右开

# fit the model
clf = IsolationForest(max_samples=100, random_state=rng)
clf.fit(X_train)
y_pred_train = clf.predict(X_train)
y_pred_test = clf.predict(X_test)
y_pred_outliers = clf.predict(X_outliers)

# plot the line, the samples, and the nearest vectors to the plane
# np.meshgrid: 坐标向量中返回坐标矩阵
xx, yy = np.meshgrid(np.linspace(-5, 5, 50), np.linspace(-5, 5, 50))
print(xx.shape)
# ravel(): 多维转一维
# decision_function: 用样本到分隔超平面的有符号距离来度量预测结果的置信度
Z = clf.decision_function(np.c_[xx.ravel(), yy.ravel()])

Z = Z.reshape(xx.shape)

plt.title("IsolationForest")
plt.contourf(xx, yy, Z, cmap=plt.cm.Blues_r) # 绘制等高线,填充轮廓

b1 = plt.scatter(X_train[:, 0], X_train[:, 1], c="white", s=20, edgecolor="k")
b2 = plt.scatter(X_test[:, 0], X_test[:, 1], c="green", s=20, edgecolor="k")
c = plt.scatter(X_outliers[:, 0], X_outliers[:, 1], c="red", s=20, edgecolor="k")
plt.axis("tight")
plt.xlim((-5, 5))
plt.ylim((-5, 5))
plt.legend(
    [b1, b2, c],
    ["training observations", "new regular observations", "new abnormal observations"],
    loc="upper left",
)
plt.show()

结果展示
(200, 2)
(50, 50)
在这里插入图片描述

  • 读取文件数据操作
import pandas as pd
from sklearn.ensemble import IsolationForest

df = pd.read_csv("Datasets/df.csv",usecols = [2,10,11])


df_list = df_csv.values.tolist()


# 拟合模型
# contamination是数据集中异常的比例。
# max_samples是从特征矩阵x中考虑的最大样本数。我们将使用所有样本。
# max_features是模型训练过程中可以考虑的最大特征数。我们将使用所有这四个特性。
# n_estimators是所考虑的孤立树的数量。

model=IsolationForest(n_estimators=100, max_samples='auto',max_features=4)

model.fit(df_list)

# 添加分数和异常列
df['scores'] = model.decision_function(df_list)
df['anomaly'] = model.predict(df_list)

# 打印异常值

anomaly = df.loc[df['anomaly']==-1]
anomaly_index=list(anomaly.index)
print(anomaly)


# 为了突出异常分数与通过预测得到的标签之间的这种关系,我们可以显示直方图。在创建直方图之前,我添加了一个表示异常状态的列:
# 明显的是,负分数的点是异常值
import plotly.express as px


df['anomaly_label'] = df['anomaly'].apply(lambda x: 'outlier' if x==-1  else 'inlier')

fig = px.histogram(df,x='scores',color='anomaly_label')
fig.show()

# 异常值的另一种有用表示是3D散点图,它拥有两个以上特征的视图
fig = px.scatter_3d(df,
                       x='traffic_7',
                       y='traffic0',
                       z='traffic_n',
                       color='anomaly_label')
fig.show()


# 评估模型,定义阈值,判定为异常

outliers_counter = len(df[df[' '] > 6 ]) # 选择判断的依据,根据判断的个数,分析预测情况
outliers_counter


# 预测为异常
print("Accuracy percentage:", 100*list(df['anomaly']).count(-1)/(outliers_counter))

结果展示:
后续补上,代码思路是正确的

总结

  • np.random.RandomState(seed),同一个seed下的分布是一样的
  • contamination超参数,异常值的比例
  • 算法对内存要求很低,且处理速度很快,其时间复杂度也是线性的
  • 0
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

nsq_ai

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值