Python Isolation Forest 异常值检测 - 可视化示例

本示例展示如何使用 Python 的 IsolationForest 模型进行异常值检测,并通过可视化图表展示异常值识别过程。

代码:

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.ensemble import IsolationForest

# 加载数据集
df = pd.read_csv('1.csv')

# 可视化初始数据分布
plt.scatter(df['x'], df['y'], c='b', s=10, alpha=0.5)
plt.show()

# 训练 Isolation Forest 模型
clf = IsolationForest(n_estimators=100, max_samples='auto', contamination=0.1, random_state=0)
clf.fit(df)
y_pred = clf.predict(df)

# 可视化离群点
plt.scatter(df[y_pred == -1]['x'], df[y_pred == -1]['y'], c='r', s=30, alpha=0.7)
plt.scatter(df[y_pred == 1]['x'], df[y_pred == 1]['y'], c='b', s=10, alpha=0.5)
plt.show()

解释:

  1. 导入库: 导入 pandasnumpymatplotlib.pyplotIsolationForest 库,分别用于数据处理、数值计算、可视化和异常值检测。
  2. 加载数据集: 使用 pandasread_csv 函数加载名为 '1.csv' 的数据集。
  3. 可视化初始数据分布: 使用 matplotlib.pyplotscatter 函数将数据以散点图的形式可视化。
  4. 训练 Isolation Forest 模型: 创建一个 IsolationForest 模型,设置参数并使用 fit 函数进行训练。
    • n_estimators: 决策树数量
    • max_samples: 每个决策树使用的样本数量
    • contamination: 异常值的比例
    • random_state: 随机数种子
  5. 预测异常值: 使用 predict 函数对每个样本进行预测,预测结果为 -1 表示异常值,1 表示正常值。
  6. 可视化离群点: 将预测为异常值的样本用红色标记,正常值样本用蓝色标记,并使用 matplotlib.pyplotscatter 函数展示可视化结果。

总结:

本示例展示了如何使用 IsolationForest 模型进行异常值检测,并通过可视化图表展示了检测结果。该示例简单易懂,并提供了基本的操作流程,可以帮助您更好地理解异常值检测的概念和应用。

Python Isolation Forest 异常值检测 - 可视化示例

原文地址: https://www.cveoy.top/t/topic/fVIv 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录