Python Isolation Forest 异常值检测 - 可视化示例
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()
解释:
- 导入库: 导入
pandas、numpy、matplotlib.pyplot和IsolationForest库,分别用于数据处理、数值计算、可视化和异常值检测。 - 加载数据集: 使用
pandas的read_csv函数加载名为 '1.csv' 的数据集。 - 可视化初始数据分布: 使用
matplotlib.pyplot的scatter函数将数据以散点图的形式可视化。 - 训练 Isolation Forest 模型: 创建一个
IsolationForest模型,设置参数并使用fit函数进行训练。n_estimators: 决策树数量max_samples: 每个决策树使用的样本数量contamination: 异常值的比例random_state: 随机数种子
- 预测异常值: 使用
predict函数对每个样本进行预测,预测结果为 -1 表示异常值,1 表示正常值。 - 可视化离群点: 将预测为异常值的样本用红色标记,正常值样本用蓝色标记,并使用
matplotlib.pyplot的scatter函数展示可视化结果。
总结:
本示例展示了如何使用 IsolationForest 模型进行异常值检测,并通过可视化图表展示了检测结果。该示例简单易懂,并提供了基本的操作流程,可以帮助您更好地理解异常值检测的概念和应用。
原文地址: https://www.cveoy.top/t/topic/fVIv 著作权归作者所有。请勿转载和采集!