Python 孤立森林异常检测算法

Python 孤立森林异常检测算法孤立森林 Isolation Forest 是一种高效的异常检测算法 特别适用于高维数据 它的核心思想是 异常点通常更容易被 孤立 即用较少的随机分割就能将异常点与其他数据分开 与基于密度或距离的方法相比 孤立森林在处理大规模数据时具有显

大家好,欢迎来到IT知识分享网。

Python 孤立森林异常检测算法

孤立森林(Isolation Forest)是一种高效的异常检测算法,特别适用于高维数据。它的核心思想是:异常点通常更容易被“孤立”,即用较少的随机分割就能将异常点与其他数据分开。与基于密度或距离的方法相比,孤立森林在处理大规模数据时具有显著的速度优势。

基本原理

核心思想

  • 随机分割: 通过随机选择特征和分割值,递归地将数据空间划分为子空间。
  • 异常点的孤立性: 异常点由于分布稀疏,通常需要较少的分割就能被孤立。
  • 路径长度: 正常点需要更多的分割才能被孤立,路径长度较长;异常点的路径长度较短。

算法步骤

  1. 构建孤立树:随机选择一个特征和一个分割值,将数据分为两部分。递归地对每个子集重复上述过程,直到达到树的深度限制或子集中只有一个样本。
  2. 计算异常得分:对于每个样本,计算其在所有孤立树中的平均路径长度。路径长度越短,样本越可能是异常点。
  3. 异常得分公式

Python 孤立森林异常检测算法

其中:

  • Python 孤立森林异常检测算法是样本Python 孤立森林异常检测算法的路径长度。
  • Python 孤立森林异常检测算法是二叉搜索树的平均路径长度,用于归一化。
  • Python 孤立森林异常检测算法是异常得分,范围在 [0, 1] 之间。得分接近 1 表示异常,接近 0 表示正常。

优点

  • 高效:时间复杂度接近线性。
  • 适用于高维数据。
  • 无需假设数据的分布。

示例数据

以下是一个使用 Python 实现孤立森林进行异常检测的示例。

import numpy as np import matplotlib.pyplot as plt from sklearn.ensemble import IsolationForest from sklearn.datasets import make_blobs # 生成模拟数据 np.random.seed(42) n_samples = 300 outliers_fraction = 0.1 # 异常点比例 n_outliers = int(outliers_fraction * n_samples) n_inliers = n_samples - n_outliers # 生成正常点 X, _ = make_blobs(n_samples=n_inliers, centers=2, cluster_std=0.5, random_state=42) # 添加异常点 X_outliers = np.random.uniform(low=-6, high=6, size=(n_outliers, 2)) X = np.concatenate([X, X_outliers], axis=0) # 训练孤立森林模型 model = IsolationForest(contamination=outliers_fraction, random_state=42) model.fit(X) # 预测异常点 y_pred = model.predict(X) y_pred[y_pred == 1] = 0 # 正常点标记为0 y_pred[y_pred == -1] = 1 # 异常点标记为1 # 可视化结果 plt.figure(figsize=(10, 6)) plt.scatter(X[:, 0], X[:, 1], c=y_pred, cmap="coolwarm", edgecolors="k", s=50) plt.title("Isolation Forest Anomaly Detection") plt.xlabel("Feature 1") plt.ylabel("Feature 2") plt.show() # 输出异常点数量 print(f"Detected anomalies: {np.sum(y_pred)}")

输出结果:

Detected anomalies: 30
Python 孤立森林异常检测算法

应用案例

金融欺诈检测: 检测异常交易行为

以下是使用 孤立森林(Isolation Forest) 进行金融欺诈检测的案例。该示例模拟了一个包含正常交易和异常交易的场景,并使用孤立森林算法检测异常交易。

import numpy as np import pandas as pd import matplotlib.pyplot as plt from sklearn.ensemble import IsolationForest from sklearn.preprocessing import StandardScaler # 模拟交易数据 np.random.seed(42) n_samples = 1000 # 总交易数量 fraud_fraction = 0.05 # 异常交易比例 n_frauds = int(fraud_fraction * n_samples) n_normal = n_samples - n_frauds # 生成正常交易数据 normal_amounts = np.random.normal(loc=100, scale=20, size=n_normal) # 交易金额 normal_times = np.random.normal(loc=12, scale=3, size=n_normal) # 交易时间(小时) # 生成异常交易数据 fraud_amounts = np.random.normal(loc=300, scale=50, size=n_frauds) # 异常交易金额 fraud_times = np.random.normal(loc=3, scale=1, size=n_frauds) # 异常交易时间(小时) # 合并数据 amounts = np.concatenate([normal_amounts, fraud_amounts]) times = np.concatenate([normal_times, fraud_times]) transactions = pd.DataFrame({"Amount": amounts, "Time": times}) # 标准化数据 scaler = StandardScaler() transactions_scaled = scaler.fit_transform(transactions) # 训练孤立森林模型 model = IsolationForest(contamination=fraud_fraction, random_state=42) model.fit(transactions_scaled) # 预测异常交易 transactions["Anomaly"] = model.predict(transactions_scaled) transactions["Anomaly"] = transactions["Anomaly"].map({1: 0, -1: 1}) # 将结果映射为0(正常)和1(异常) # 输出检测结果 print("Detected anomalies:") print(transactions[transactions["Anomaly"] == 1]) # 可视化结果 plt.figure(figsize=(10, 6)) plt.scatter(transactions["Amount"], transactions["Time"], c=transactions["Anomaly"], cmap="coolwarm", edgecolors="k", s=50) plt.title("Financial Fraud Detection using Isolation Forest") plt.xlabel("Transaction Amount") plt.ylabel("Transaction Time (Hour)") plt.colorbar(label="Anomaly (1=Fraud, 0=Normal)") plt.show() # 输出异常交易数量 print(f"Total detected frauds: {transactions['Anomaly'].sum()}")

输出结果:

Detected anomalies: Amount Time Anomaly 74 47. 17. 1 283 75. 19. 1 396 65. 4. 1 541 77. 19. 1 589 82. 3. 1 665 102. 21. 1 950 334. 1. 1 951 283. 4. 1 952 358. 2.094268 1 953 318. 2. 1 954 294. 2. 1 955 322. 4. 1 956 221. 0. 1 957 243. 6. 1 958 240. 4.056057 1 959 307. 3. 1 960 386. 2. 1 961 411. 3. 1 962 331. 3. 1 963 325.042224 3. 1 964 209. 3. 1 965 272. 3.089581 1 966 260. 2. 1 967 268. 2. 1 968 291. 2. 1 969 276. 4. 1 970 201.035009 3. 1 971 337. 0.059611 1 972 246. 3. 1 973 311. 3. 1 974 403. 2. 1 975 254.030770 2. 1 976 173. 4. 1 978 355.047982 2. 1 979 397. 3. 1 980 238. 2.028343 1 981 324. 1. 1 982 276. 2. 1 984 432. 3. 1 985 224. 3. 1 987 323. 3. 1 988 354. 2. 1 990 315. 3. 1 992 313. 4. 1 994 331.078594 3. 1 995 281. 4.070150 1 996 318. 2. 1 997 298. 2. 1 998 356. 2. 1 999 297. 2. 1 Total detected frauds: 50
Python 孤立森林异常检测算法

网络入侵检测: 识别异常的网络流量

以下是使用 孤立森林(Isolation Forest) 进行网络入侵检测的案例。该示例模拟了一个包含正常流量和异常流量的场景,并使用孤立森林算法检测异常流量。

import numpy as np import pandas as pd import matplotlib.pyplot as plt from sklearn.ensemble import IsolationForest from sklearn.preprocessing import StandardScaler # 模拟网络流量数据 np.random.seed(42) n_samples = 1000 # 总流量数量 anomaly_fraction = 0.05 # 异常流量比例 n_anomalies = int(anomaly_fraction * n_samples) n_normal = n_samples - n_anomalies # 生成正常流量数据 normal_packets = np.random.normal(loc=100, scale=10, size=n_normal) # 数据包数量 normal_duration = np.random.normal(loc=5, scale=1, size=n_normal) # 流量持续时间(秒) # 生成异常流量数据 anomaly_packets = np.random.normal(loc=500, scale=50, size=n_anomalies) # 异常数据包数量 anomaly_duration = np.random.normal(loc=20, scale=5, size=n_anomalies) # 异常流量持续时间(秒) # 合并数据 packets = np.concatenate([normal_packets, anomaly_packets]) duration = np.concatenate([normal_duration, anomaly_duration]) traffic = pd.DataFrame({"Packets": packets, "Duration": duration}) # 标准化数据 scaler = StandardScaler() traffic_scaled = scaler.fit_transform(traffic) # 训练孤立森林模型 model = IsolationForest(contamination=anomaly_fraction, random_state=42) model.fit(traffic_scaled) # 预测异常流量 traffic["Anomaly"] = model.predict(traffic_scaled) traffic["Anomaly"] = traffic["Anomaly"].map({1: 0, -1: 1}) # 将结果映射为0(正常)和1(异常) # 输出检测结果 print("Detected anomalies:") print(traffic[traffic["Anomaly"] == 1]) # 可视化结果 plt.figure(figsize=(10, 6)) plt.scatter(traffic["Packets"], traffic["Duration"], c=traffic["Anomaly"], cmap="coolwarm", edgecolors="k", s=50) plt.title("Network Intrusion Detection using Isolation Forest") plt.xlabel("Number of Packets") plt.ylabel("Duration (Seconds)") plt.colorbar(label="Anomaly (1=Anomaly, 0=Normal)") plt.show() # 输出异常流量数量 print(f"Total detected anomalies: {traffic['Anomaly'].sum()}")

输出结果:

Detected anomalies: Packets Duration Anomaly 950 534. 11. 1 951 483. 26. 1 952 558. 15. 1 953 518. 16. 1 954 494. 17.021694 1 955 522. 26. 1 956 421. 9. 1 957 443. 35. 1 958 440. 25. 1 959 507. 21. 1 960 586. 19. 1 961 611. 21. 1 962 531. 22. 1 963 525.042224 23. 1 964 409. 22. 1 965 472. 20. 1 966 460. 19.013308 1 967 468. 19. 1 968 491. 19.025459 1 969 476. 25. 1 970 401.035009 22. 1 971 537. 5. 1 972 446. 23. 1 973 511. 20. 1 974 603. 19. 1 975 454.030770 18.057408 1 976 373. 25. 1 977 485. 24. 1 978 555.047982 16. 1 979 597. 22.035261 1 980 438. 15. 1 981 524. 13. 1 982 476. 16. 1 983 494. 24. 1 984 632. 24. 1 985 424. 22. 1 986 512. 23. 1 987 523. 22. 1 988 554. 16. 1 989 504. 22. 1 990 515. 24.002048 1 991 480. 23. 1 992 513. 25. 1 993 482. 23. 1 994 531.078594 21. 1 995 481. 25. 1 996 518. 19. 1 997 498. 15. 1 998 556. 19. 1 999 497. 16. 1 Total detected anomalies: 50
Python 孤立森林异常检测算法

电商欺诈检测: 检测异常的订单或支付行为

以下是使用 孤立森林(Isolation Forest) 进行电商欺诈检测的案例。该示例模拟了一个包含正常订单和异常订单的场景,并使用孤立森林算法检测异常订单。

import numpy as np import pandas as pd import matplotlib.pyplot as plt from sklearn.ensemble import IsolationForest from sklearn.preprocessing import StandardScaler # 模拟电商订单数据 np.random.seed(42) n_samples = 1000 # 总订单数量 fraud_fraction = 0.05 # 异常订单比例 n_frauds = int(fraud_fraction * n_samples) n_normal = n_samples - n_frauds # 生成正常订单数据 normal_amounts = np.random.normal(loc=100, scale=20, size=n_normal) # 订单金额 normal_items = np.random.normal(loc=5, scale=2, size=n_normal) # 订单商品数量 # 生成异常订单数据 fraud_amounts = np.random.normal(loc=500, scale=50, size=n_frauds) # 异常订单金额 fraud_items = np.random.normal(loc=20, scale=5, size=n_frauds) # 异常订单商品数量 # 合并数据 amounts = np.concatenate([normal_amounts, fraud_amounts]) items = np.concatenate([normal_items, fraud_items]) orders = pd.DataFrame({"Amount": amounts, "Items": items}) # 标准化数据 scaler = StandardScaler() orders_scaled = scaler.fit_transform(orders) # 训练孤立森林模型 model = IsolationForest(contamination=fraud_fraction, random_state=42) model.fit(orders_scaled) # 预测异常订单 orders["Anomaly"] = model.predict(orders_scaled) orders["Anomaly"] = orders["Anomaly"].map({1: 0, -1: 1}) # 将结果映射为0(正常)和1(异常) # 输出检测结果 print("Detected anomalies:") print(orders[orders["Anomaly"] == 1]) # 可视化结果 plt.figure(figsize=(10, 6)) plt.scatter(orders["Amount"], orders["Items"], c=orders["Anomaly"], cmap="coolwarm", edgecolors="k", s=50) plt.title("E-commerce Fraud Detection using Isolation Forest") plt.xlabel("Order Amount") plt.ylabel("Number of Items") plt.colorbar(label="Anomaly (1=Fraud, 0=Normal)") plt.show() # 输出异常订单数量 print(f"Total detected frauds: {orders['Anomaly'].sum()}")

输出结果:

Detected anomalies: Amount Items Anomaly 950 534. 11. 1 951 483. 26. 1 952 558. 15. 1 953 518. 16. 1 954 494. 17.021694 1 955 522. 26. 1 956 421. 9. 1 957 443. 35. 1 958 440. 25. 1 959 507. 21. 1 960 586. 19. 1 961 611. 21. 1 962 531. 22. 1 963 525.042224 23. 1 964 409. 22. 1 965 472. 20. 1 966 460. 19.013308 1 967 468. 19. 1 968 491. 19.025459 1 969 476. 25. 1 970 401.035009 22. 1 971 537. 5. 1 972 446. 23. 1 973 511. 20. 1 974 603. 19. 1 975 454.030770 18.057408 1 976 373. 25. 1 977 485. 24. 1 978 555.047982 16. 1 979 597. 22.035261 1 980 438. 15. 1 981 524. 13. 1 982 476. 16. 1 983 494. 24. 1 984 632. 24. 1 985 424. 22. 1 986 512. 23. 1 987 523. 22. 1 988 554. 16. 1 989 504. 22. 1 990 515. 24.002048 1 991 480. 23. 1 992 513. 25. 1 993 482. 23. 1 994 531.078594 21. 1 995 481. 25. 1 996 518. 19. 1 997 498. 15. 1 998 556. 19. 1 999 497. 16. 1 Total detected frauds: 50
Python 孤立森林异常检测算法

总结

孤立森林是一种高效、灵活的异常检测算法,特别适合处理大规模和高维数据。通过合理设置树的数量和深度,可以进一步提高算法的性能和稳定性。虽然孤立森林在某些场景下存在局限性,但其在速度、可扩展性和适用性方面的优势使其成为异常检测领域的重要工具。

免责声明:本站所有文章内容,图片,视频等均是来源于用户投稿和互联网及文摘转载整编而成,不代表本站观点,不承担相关法律责任。其著作权各归其原作者或其出版社所有。如发现本站有涉嫌抄袭侵权/违法违规的内容,侵犯到您的权益,请在线联系站长,一经查实,本站将立刻删除。 本文来自网络,若有侵权,请联系删除,如若转载,请注明出处:https://haidsoft.com/185157.html

(0)
上一篇 2025-08-06 10:10
下一篇 2025-08-06 10:15

相关推荐

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注微信