Azure AI 异常检测 Java SDK
Azure AI Anomaly Detector Java SDK
使用 Azure AI Anomaly Detector Java SDK 构建异常检测应用程序。
安装
<dependency>
<groupId>com.azure</groupId>
<artifactId>azure-ai-anomalydetector</artifactId>
<version>3.0.0-beta.6</version>
</dependency>客户端创建
同步与异步客户端
import com.azure.ai.anomalydetector.AnomalyDetectorClientBuilder;
import com.azure.ai.anomalydetector.MultivariateClient;
import com.azure.ai.anomalydetector.UnivariateClient;
import com.azure.core.credential.AzureKeyCredential;
String endpoint = System.getenv("AZURE_ANOMALY_DETECTOR_ENDPOINT");
String key = System.getenv("AZURE_ANOMALY_DETECTOR_API_KEY");
// 用于多个相关信号的多变量客户端
MultivariateClient multivariateClient = new AnomalyDetectorClientBuilder()
.credential(new AzureKeyCredential(key))
.endpoint(endpoint)
.buildMultivariateClient();
// 用于单变量分析的单变量客户端
UnivariateClient univariateClient = new AnomalyDetectorClientBuilder()
.credential(new AzureKeyCredential(key))
.endpoint(endpoint)
.buildUnivariateClient();
使用 DefaultAzureCredential
import com.azure.identity.DefaultAzureCredentialBuilder;
MultivariateClient client = new AnomalyDetectorClientBuilder()
.credential(new DefaultAzureCredentialBuilder().build())
.endpoint(endpoint)
.buildMultivariateClient();
核心概念
单变量异常检测 (Univariate Anomaly Detection)
- 批量检测 (Batch Detection):一次性分析整个时间序列
- 流式检测 (Streaming Detection):对最新数据点进行实时检测
- 变化点检测 (Change Point Detection):检测时间序列中的趋势变化
多变量异常检测 (Multivariate Anomaly Detection)
- 检测 300 多个相关信号中的异常
- 使用图注意力网络 (Graph Attention Network) 处理相互关联性
- 三步流程:训练 $\rightarrow$ 推理 $\rightarrow$ 结果
核心模式
单变量批量检测
import com.azure.ai.anomalydetector.models.*;
import java.time.OffsetDateTime;
import java.util.List;
List<TimeSeriesPoint> series = List.of(
new TimeSeriesPoint(OffsetDateTime.parse("2023-01-01T00:00:00Z"), 1.0),
new TimeSeriesPoint(OffsetDateTime.parse("2023-01-02T00:00:00Z"), 2.5),
// ... 更多数据点(至少需要 12 个点)
);
UnivariateDetectionOptions options = new UnivariateDetectionOptions(series)
.setGranularity(TimeGranularity.DAILY)
.setSensitivity(95);
UnivariateEntireDetectionResult result = univariateClient.detectUnivariateEntireSeries(options);
// 检查异常
for (int i = 0; i < result.getIsAnomaly().size(); i++) {
if (result.getIsAnomaly().get(i)) {
System.out.printf("在索引 %d 处检测到异常,值为 %.2f%n",
i, series.get(i).getValue());
}
}
单变量最后一点检测(流式)
UnivariateLastDetectionResult lastResult = univariateClient.detectUnivariateLastPoint(options);
if (lastResult.isAnomaly()) {
System.out.println("最新点是异常值!");
System.out.printf("预期值: %.2f, 上限: %.2f, 下限: %.2f%n",
lastResult.getExpectedValue(),
lastResult.getUpperMargin(),
lastResult.getLowerMargin());
}
### 变更点检测UnivariateChangePointDetectionOptions changeOptions =
new UnivariateChangePointDetectionOptions(series, TimeGranularity.DAILY);
UnivariateChangePointDetectionResult changeResult =
univariateClient.detectUnivariateChangePoint(changeOptions);
for (int i = 0; i < changeResult.getIsChangePoint().size(); i++) {
if (changeResult.getIsChangePoint().get(i)) {
System.out.printf("Change point at index %d with confidence %.2f%n",
i, changeResult.getConfidenceScores().get(i));
}
}
### 多变量模型训练import com.azure.ai.anomalydetector.models.*;
import com.azure.core.util.polling.SyncPoller;
// 使用 Blob 存储数据准备训练请求
ModelInfo modelInfo = new ModelInfo()
.setDataSource("https://storage.blob.core.windows.net/container/data.zip?sasToken")
.setStartTime(OffsetDateTime.parse("2023-01-01T00:00:00Z"))
.setEndTime(OffsetDateTime.parse("2023-06-01T00:00:00Z"))
.setSlidingWindow(200)
.setDisplayName("MyMultivariateModel");
// 训练模型(长时间运行操作)
AnomalyDetectionModel trainedModel = multivariateClient.trainMultivariateModel(modelInfo);
String modelId = trainedModel.getModelId();
System.out.println("Model ID: " + modelId);
// 检查训练状态
AnomalyDetectionModel model = multivariateClient.getMultivariateModel(modelId);
System.out.println("Status: " + model.getModelInfo().getStatus());
### 多变量批量推理MultivariateBatchDetectionOptions detectionOptions = new MultivariateBatchDetectionOptions()
.setDataSource("https://storage.blob.core.windows.net/container/inference-data.zip?sasToken")
.setStartTime(OffsetDateTime.parse("2023-07-01T00:00:00Z"))
.setEndTime(OffsetDateTime.parse("2023-07-31T00:00:00Z"))
.setTopContributorCount(10);
MultivariateDetectionResult detectionResult =
multivariateClient.detectMultivariateBatchAnomaly(modelId, detectionOptions);
String resultId = detectionResult.getResultId();
// 轮询结果
MultivariateDetectionResult result = multivariateClient.getBatchDetectionResult(resultId);
for (AnomalyState state : result.getResults()) {
if (state.getValue().isAnomaly()) {
System.out.printf("Anomaly at %s, severity: %.2f%n",
state.getTimestamp(),
state.getValue().getSeverity());
}
}
### 多变量最后一点检测MultivariateLastDetectionOptions lastOptions = new MultivariateLastDetectionOptions()
.setVariables(List.of(
new VariableValues("variable1", List.of("timestamp1"), List.of(1.0f)),
new VariableValues("variable2", List.of("timestamp1"), List.of(2.5f))
))
.setTopContributorCount(5);
MultivariateLastDetectionResult lastResult =
multivariateClient.detectMultivariateLastAnomaly(modelId, lastOptions);
if (lastResult.getValue().isAnomaly()) {
System.out.println("Anomaly detected!");
// 检查贡献变量
for (AnomalyContributor contributor : lastResult.getValue().getInterpretation()) {
System.out.printf("Variable: %s, Contribution: %.2f%n",
contributor.getVariable(),
contributor.getContributionScore());
}
}
### 模型管理// 列出所有模型
PagedIterable<AnomalyDetectionModel> models = multivariateClient.listMultivariateModels();
for (AnomalyDetectionModel m : models) {
System.out.printf("Model: %s,
Status: %s%n",
m.getModelId(),
m.getModelInfo().getStatus());
}
// 删除模型
multivariateClient.deleteMultivariateModel(modelId);
错误处理
import com.azure.core.exception.HttpResponseException;
try {
univariateClient.detectUnivariateEntireSeries(options);
} catch (HttpResponseException e) {
System.out.println("状态码: " + e.getResponse().getStatusCode());
System.out.println("错误: " + e.getMessage());
}
环境变量
AZURE_ANOMALY_DETECTOR_ENDPOINT=https://<resource>.cognitiveservices.azure.com/
AZURE_ANOMALY_DETECTOR_API_KEY=<your-api-key>最佳实践
1. 最小数据点:单变量检测至少需要 12 个点;数据越多,准确度越高。
2. 粒度对齐:确保 TimeGranularity 与实际数据的频率一致。
3. 灵敏度调优:较高的值(0-99)会检测到更多异常。
4. 多变量训练:根据模式复杂度,使用 200-1000 的滑动窗口。
5. 错误处理:始终处理 HttpResponseException 以应对 API 错误。
触发词
- "anomaly detection Java"
- "detect anomalies time series"
- "multivariate anomaly Java"
- "univariate anomaly detection"
- "streaming anomaly detection"
- "change point detection"
- "Azure AI Anomaly Detector"
使用场景
本技能适用于执行概览中所描述的工作流或操作。局限性
- 仅在任务明确符合上述范围时使用此技能。
- 不要将输出视为针对特定环境的验证、测试或专家评审的替代方案。
- 如果缺失必要的输入、权限、安全边界或成功标准,请停止并请求澄清。