本 Notebook 探讨了通过改进检测过程来提升异常检测的方法。TimeGPT 利用其预测能力,根据预测误差来识别异常。通过优化预测参数和准确性,您可以使异常检测更贴合特定用例并提高其准确性。

import pandas as pd
from nixtla import NixtlaClient
import matplotlib.pyplot as plt
# Utility function to plot anomalies
def plot_anomaly(df, anomaly_df, time_col = 'ts', target_col = 'y'):
    merged_df = pd.merge(df.tail(300), anomaly_df[[time_col, 'anomaly', 'TimeGPT']], on=time_col, how='left')
    plt.figure(figsize=(12, 2))
    plt.plot(merged_df[time_col], merged_df[target_col], label='y', color='navy', alpha=0.8)
    plt.plot(merged_df[time_col], merged_df['TimeGPT'], label='TimeGPT', color='orchid', alpha=0.7)
    plt.scatter(merged_df.loc[merged_df['anomaly'] == True, time_col], merged_df.loc[merged_df['anomaly'] == True, target_col], color='orchid', label='Anomalies Detected')
    plt.legend()
    plt.tight_layout()
    plt.show()
nixtla_client = NixtlaClient(
    # defaults to os.environ.get("NIXTLA_API_KEY")
    api_key = 'my_api_key_provided_by_nixtla'
)

👍 使用 Azure AI 端点

要使用 Azure AI 端点,请设置 base_url 参数

nixtla_client = NixtlaClient(base_url="you azure ai endpoint", api_key="your api_key")

1. 执行异常检测

初始化 NixtlaClient 实例后,我们来看一个使用 Peyton Manning 数据集的示例。

df = pd.read_csv('https://datasets-nixtla.s3.amazonaws.com/peyton-manning.csv',parse_dates = ['ds']).tail(200)
df.head()
unique_iddsy
276402015-07-056.499787
276502015-07-066.859615
276602015-07-076.881411
276702015-07-086.997596
276802015-07-097.152269

首先,我们仅使用方法的默认参数来设置基线。

# Base case for anomaly detection using detect_anomaly_online
anomaly_df = nixtla_client.detect_anomalies_online(
    df,
    freq='D',
    h=14,
    level=80,
    detection_size=150
)
INFO:nixtla.nixtla_client:Validating inputs...
INFO:nixtla.nixtla_client:Preprocessing dataframes...
WARNING:nixtla.nixtla_client:Detection size is large. Using the entire series to compute the anomaly threshold...
INFO:nixtla.nixtla_client:Calling Online Anomaly Detector Endpoint...
plot_anomaly(df, anomaly_df, time_col = 'ds', target_col = 'y')

2. 调整异常检测流程

本节探讨了增强异常检测的两个关键方法

  1. 微调模型以提升预测准确性
  2. 调整预测范围和步长以优化时间序列分割和分析。

这些策略可以实现更具针对性且更有效的异常检测流程。

2.1 微调 TimeGPT

TimeGPT 使用预测误差进行异常检测,因此提高预测准确性可以减少误差中的噪声,从而带来更好的异常检测效果。您可以使用以下参数来微调模型

  • finetune_steps:在新数据上微调 TimeGPT 的步数。
  • finetune_depth:控制微调参数数量的微调级别(请参阅我们的深度教程
  • finetune_loss:微调过程中使用的损失函数。
anomaly_online_ft = nixtla_client.detect_anomalies_online(
    df,
    freq='D',
    h=14,
    level=80,
    detection_size=150,
    finetune_steps = 10,    # Number of steps for fine-tuning TimeGPT on new data
    finetune_depth = 2,     # Intensity of finetuning
    finetune_loss = 'mae'   # Loss function used during the finetuning process
)
INFO:nixtla.nixtla_client:Validating inputs...
INFO:nixtla.nixtla_client:Preprocessing dataframes...
WARNING:nixtla.nixtla_client:Detection size is large. Using the entire series to compute the anomaly threshold...
INFO:nixtla.nixtla_client:Calling Online Anomaly Detector Endpoint...
plot_anomaly(df, anomaly_online_ft, time_col = 'ds', target_col = 'y')

从上面的图中可以看出,模型检测到的异常较少,因为微调过程有助于 TimeGPT 更好地预测序列。

2.2 更改预测范围和步长

与交叉验证类似,异常检测方法通过将时间序列分割成多个窗口来生成历史数据的预测。这些窗口的定义方式会影响异常检测结果。以下两个关键参数控制此过程

  • h:指定每个窗口的未来预测步数。
  • step_size:确定连续窗口起始点之间的间隔。

请注意,当 step_size 小于 h 时,我们会得到重叠的窗口。这可以使检测过程更健壮,因为 TimeGPT 将多次看到相同的时间步长。然而,这会带来计算成本,因为相同的时间步长将被预测多次。

anomaly_df_horizon = nixtla_client.detect_anomalies_online(
    df,
    time_col='ds',
    target_col='y',
    freq='D',
    h=2,                 # Forecast horizon
    step_size = 1,       # Step size for moving through the time series data
    level=80,            
    detection_size=150
)
INFO:nixtla.nixtla_client:Validating inputs...
INFO:nixtla.nixtla_client:Preprocessing dataframes...
WARNING:nixtla.nixtla_client:Detection size is large. Using the entire series to compute the anomaly threshold...
INFO:nixtla.nixtla_client:Calling Online Anomaly Detector Endpoint...
plot_anomaly(df, anomaly_df_horizon, time_col = 'ds', target_col = 'y')

📘 平衡 h 和 step_size 取决于您的数据: 对于频繁、短暂的异常,使用较小的 h 关注短期预测,并使用较小的 step_size 增加重叠和敏感性。对于平滑趋势或长期模式,使用较大的 h 捕获更广泛的异常,并使用较大的 step_size 减少噪声和计算成本。