使用孤立森林進行多變數異常偵測

本文說明如何在 Apache Spark 上使用 SynapseML 進行多變量異常偵測。 多變量異常偵測能偵測多個變數或時間序列間的異常,並考量不同變數間的所有相互關聯與依賴關係。 在此情境中,你使用 SynapseML 訓練一個用於多變量異常偵測的隔離森林模型,然後利用訓練好的模型在包含三個物聯網感測器合成測量的資料集中推斷多變量異常。

欲進一步了解隔離森林模型,請參閱 Liu 等人的原始論文。

必要條件

  1. 取得 Microsoft Fabric 訂用帳戶。 或註冊免費的 Microsoft Fabric 試用版。
  2. 將筆記本連結至 Lakehouse。 在左側,選取新增來新增現有的 Lakehouse 或創建新的 Lakehouse。
  3. SynapseML 預裝在 Fabric PySpark 執行環境中。 使用 Runtime 2.0,這是最新正式推出(GA)且為預設的執行環境。 若要使用特定 SynapseML 版本,請參見「在 Fabric 上安裝不同版本的 SynapseML」。

程式庫匯入

from pyspark.sql import functions as F
from pyspark.ml.feature import VectorAssembler
from pyspark.sql.types import DoubleType
from pyspark.ml import Pipeline

from synapse.ml.isolationforest import IsolationForest
from pyspark.sql import SparkSession

# Bootstrap Spark Session
spark = SparkSession.builder.getOrCreate()

輸入資料

# Table inputs
timestampColumn = "timestamp"  # str: the name of the timestamp column in the table
inputCols = [
    "sensor_1",
    "sensor_2",
    "sensor_3",
]  # list(str): the names of the input variables

# Training Start time, and number of days to use for training:
trainingStartTime = (
    "2022-02-24T06:00:00Z"  # datetime: datetime for when to start the training
)
trainingEndTime = (
    "2022-03-08T23:55:00Z"  # datetime: datetime for when to end the training
)
inferenceStartTime = (
    "2022-03-09T09:30:00Z"  # datetime: datetime for when to start the inference
)
inferenceEndTime = (
    "2022-03-20T23:55:00Z"  # datetime: datetime for when to end the inference
)

# Isolation Forest parameters
contamination = 0.021
num_estimators = 100
max_samples = 256
max_features = 1.0

讀取資料

df = (
    spark.read.format("csv")
    .option("header", "true")
    .load(
        "wasbs://publicwasb@mmlspark.blob.core.windows.net/generated_sample_mvad_data.csv"
    )
)

將欄位轉換為適當的資料類型。

df = (
    df.orderBy(timestampColumn)
    .withColumn("timestamp", F.date_format(timestampColumn, "yyyy-MM-dd'T'HH:mm:ss'Z'"))
    .withColumn("sensor_1", F.col("sensor_1").cast(DoubleType()))
    .withColumn("sensor_2", F.col("sensor_2").cast(DoubleType()))
    .withColumn("sensor_3", F.col("sensor_3").cast(DoubleType()))
    .drop("_c5")  # drop the extra unlabeled column present in the source CSV
)

display(df)

訓練資料準備

# filter to data with timestamps within the training window
df_train = df.filter(
    (F.col(timestampColumn) >= trainingStartTime)
    & (F.col(timestampColumn) <= trainingEndTime)
)
display(df_train)

測試資料準備

# filter to data with timestamps within the inference window
df_test = df.filter(
    (F.col(timestampColumn) >= inferenceStartTime)
    & (F.col(timestampColumn) <= inferenceEndTime)
)
display(df_test)

訓練隔離樹系模型

isolationForest = (
    IsolationForest()
    .setNumEstimators(num_estimators)
    .setBootstrap(False)
    .setMaxSamples(max_samples)
    .setMaxFeatures(max_features)
    .setFeaturesCol("features")
    .setPredictionCol("predictedLabel")
    .setScoreCol("outlierScore")
    .setContamination(contamination)
    .setContaminationError(0.01 * contamination)
    .setRandomSeed(1)
)

接著,建立一個機器學習管線來訓練隔離森林模型。

對於在同一本筆記本中訓練模型並執行推理,模型物件已足夠。 若要在多個會話間持續使用並重複使用該模型,請在 Microsoft Fabric 中使用 MLflow 註冊。

va = VectorAssembler(inputCols=inputCols, outputCol="features")
pipeline = Pipeline(stages=[va, isolationForest])
model = pipeline.fit(df_train)

執行推斷

將訓練好的模型套用到測試資料:

df_test_pred = model.transform(df_test)
display(df_test_pred)

預製異常偵測器

這很重要

Microsoft 將於 2026 年 10 月 1 日退休 Azure AI 異常偵測程式 服務。 自 2023 年 9 月 20 日起,您無法創建新的資源。 如需支援的替代方案,請參閱 Microsoft Fabric 即時智慧中的異常偵測。

Azure AI 異常偵測程式

  • 最新點的異常狀態:利用前一個點產生模型,判斷該點是否異常。 請參閱 SynapseML GitHub 倉庫以獲取最新的 API 參考。
  • 尋找異常:利用整個級數生成模型,並在級數中尋找異常。 請參閱 SynapseML GitHub 倉庫以獲取最新的 API 參考。