azure-ai-anomalydetector-java
microsoft/skills
使用 Azure AI 异常检测器 Java SDK 检测时间序列数据中的异常,该 SDK 支持单变量和多变量分析、模型训练以及推理。
...展开全部Azure AI 异常检测器 Java SDK
使用 Azure AI 异常检测器 Java SDK 构建异常检测应用程序。
安装
com.azure
azure-ai-anomalydetector
3.0.0-beta.6
客户端创建
同步和异步客户端
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.core.credential.TokenCredential;
import com.azure.identity.AzureIdentityEnvVars;
import com.azure.identity.DefaultAzureCredentialBuilder;
import com.azure.identity.ManagedIdentityCredentialBuilder;
TokenCredential credential = new DefaultAzureCredentialBuilder()
.requireEnvVars(AzureIdentityEnvVars.AZURE_TOKEN_CREDENTIALS)
.build();
// 或者在生产环境中直接使用特定的凭据:
// 参见 https://learn.microsoft.com/java/api/overview/azure/identity-readme?view=azure-java-stable#credential-classes
// TokenCredential credential = new ManagedIdentityCredentialBuilder().build();
MultivariateClient client = new AnomalyDetectorClientBuilder()
.credential(credential)
.endpoint(endpoint)
.buildMultivariateClient();
关键概念
单变量异常检测
- 批量检测:一次性分析整个时间序列
- 流式检测:对最新数据点进行实时检测
- 变点检测:检测时间序列中的趋势变化
多变量异常检测
- 在300多个相关信号中检测异常
- 采用图注意力网络处理信号间的相互相关性
- 三步流程:训练 → 推理 → 结果
核心模式
单变量批量检测
import com.azure.ai.anomalydetector.models.*;
import java.time.OffsetDateTime;
import java.util.List;
List 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("索引 %d 处的变点,置信度 %.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("模型 ID: " + modelId);
// 检查训练状态
AnomalyDetectionModel model = multivariateClient.getMultivariateModel(modelId);
System.out.println("状态: " + 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("在 %s 处检测到异常,严重程度:%.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("检测到异常!");
// 检查贡献变量
for (AnomalyContributor contributor : lastResult.getValue().getInterpretation()) {
System.out.printf("变量:%s,贡献度:%.2f%n",
contributor.getVariable(),
contributor.getContributionScore());
}
}
模型管理
// 列出所有模型
PagedIterable models = multivariateClient.listMultivariateModels();
for (AnomalyDetectionModel m : models) {
System.out.printf("模型: %s, 状态: %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://.cognitiveservices.azure.com/ # 所有身份验证方法均需此项
AZURE_ANOMALY_DETECTOR_API_KEY= # 仅在 AzureKeyCredential 身份验证方式下需要
AZURE_TOKEN_CREDENTIALS=prod # 仅当在生产环境中使用 DefaultAzureCredential 时才需要
最佳实践
- 最小数据点数:单变量分析至少需要 12 个数据点;数据越多,准确性越高
- 粒度对齐:将
TimeGranularity与实际数据频率保持一致 - 灵敏度调整:数值越高(0-99),检测到的异常越多
- 多变量训练:根据模式复杂度使用 200-1000 的滑动窗口
- 错误处理:遇到API错误时,务必处理
HttpResponseException
触发短语
- “异常检测 Java”
- “检测时间序列异常”
- “Java 多变量异常检测”
- “单变量异常检测”
- “流式异常检测”
- "变点检测"
- “Azure AI 异常检测器”
---
name: azure-ai-anomalydetector-java
description: Detect anomalies in time-series data using the Azure AI Anomaly Detector SDK for Java, with support for univariate and multivariate analysis, model training, and inference.
license: MIT
---
# Azure AI Anomaly Detector SDK for Java
Build anomaly detection applications using the Azure AI Anomaly Detector SDK for Java.
## Installation
```xml
<dependency>
<groupId>com.azure</groupId>
<artifactId>azure-ai-anomalydetector</artifactId>
<version>3.0.0-beta.6</version>
</dependency>
```
## Client Creation
### Sync and Async Clients
```java
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");
// Multivariate client for multiple correlated signals
MultivariateClient multivariateClient = new AnomalyDetectorClientBuilder()
.credential(new AzureKeyCredential(key))
.endpoint(endpoint)
.buildMultivariateClient();
// Univariate client for single variable analysis
UnivariateClient univariateClient = new AnomalyDetectorClientBuilder()
.credential(new AzureKeyCredential(key))
.endpoint(endpoint)
.buildUnivariateClient();
```
### With DefaultAzureCredential
```java
import com.azure.core.credential.TokenCredential;
import com.azure.identity.AzureIdentityEnvVars;
import com.azure.identity.DefaultAzureCredentialBuilder;
import com.azure.identity.ManagedIdentityCredentialBuilder;
TokenCredential credential = new DefaultAzureCredentialBuilder()
.requireEnvVars(AzureIdentityEnvVars.AZURE_TOKEN_CREDENTIALS)
.build();
// Or use a specific credential directly in production:
// See https://learn.microsoft.com/java/api/overview/azure/identity-readme?view=azure-java-stable#credential-classes
// TokenCredential credential = new ManagedIdentityCredentialBuilder().build();
MultivariateClient client = new AnomalyDetectorClientBuilder()
.credential(credential)
.endpoint(endpoint)
.buildMultivariateClient();
```
## Key Concepts
### Univariate Anomaly Detection
- **Batch Detection**: Analyze entire time series at once
- **Streaming Detection**: Real-time detection on latest data point
- **Change Point Detection**: Detect trend changes in time series
### Multivariate Anomaly Detection
- Detect anomalies across 300+ correlated signals
- Uses Graph Attention Network for inter-correlations
- Three-step process: Train → Inference → Results
## Core Patterns
### Univariate Batch Detection
```java
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),
// ... more data points (minimum 12 points required)
);
UnivariateDetectionOptions options = new UnivariateDetectionOptions(series)
.setGranularity(TimeGranularity.DAILY)
.setSensitivity(95);
UnivariateEntireDetectionResult result = univariateClient.detectUnivariateEntireSeries(options);
// Check for anomalies
for (int i = 0; i < result.getIsAnomaly().size(); i++) {
if (result.getIsAnomaly().get(i)) {
System.out.printf("Anomaly detected at index %d with value %.2f%n",
i, series.get(i).getValue());
}
}
```
### Univariate Last Point Detection (Streaming)
```java
UnivariateLastDetectionResult lastResult = univariateClient.detectUnivariateLastPoint(options);
if (lastResult.isAnomaly()) {
System.out.println("Latest point is an anomaly!");
System.out.printf("Expected: %.2f, Upper: %.2f, Lower: %.2f%n",
lastResult.getExpectedValue(),
lastResult.getUpperMargin(),
lastResult.getLowerMargin());
}
```
### Change Point Detection
```java
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));
}
}
```
### Multivariate Model Training
```java
import com.azure.ai.anomalydetector.models.*;
import com.azure.core.util.polling.SyncPoller;
// Prepare training request with blob storage data
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");
// Train model (long-running operation)
AnomalyDetectionModel trainedModel = multivariateClient.trainMultivariateModel(modelInfo);
String modelId = trainedModel.getModelId();
System.out.println("Model ID: " + modelId);
// Check training status
AnomalyDetectionModel model = multivariateClient.getMultivariateModel(modelId);
System.out.println("Status: " + model.getModelInfo().getStatus());
```
### Multivariate Batch Inference
```java
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();
// Poll for results
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());
}
}
```
### Multivariate Last Point Detection
```java
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!");
// Check contributing variables
for (AnomalyContributor contributor : lastResult.getValue().getInterpretation()) {
System.out.printf("Variable: %s, Contribution: %.2f%n",
contributor.getVariable(),
contributor.getContributionScore());
}
}
```
### Model Management
```java
// List all models
PagedIterable<AnomalyDetectionModel> models = multivariateClient.listMultivariateModels();
for (AnomalyDetectionModel m : models) {
System.out.printf("Model: %s, Status: %s%n",
m.getModelId(),
m.getModelInfo().getStatus());
}
// Delete a model
multivariateClient.deleteMultivariateModel(modelId);
```
## Error Handling
```java
import com.azure.core.exception.HttpResponseException;
try {
univariateClient.detectUnivariateEntireSeries(options);
} catch (HttpResponseException e) {
System.out.println("Status code: " + e.getResponse().getStatusCode());
System.out.println("Error: " + e.getMessage());
}
```
## Environment Variables
```bash
AZURE_ANOMALY_DETECTOR_ENDPOINT=https://<resource>.cognitiveservices.azure.com/ # Required for all auth methods
AZURE_ANOMALY_DETECTOR_API_KEY=<your-api-key> # Only required for AzureKeyCredential auth
AZURE_TOKEN_CREDENTIALS=prod # Required only if DefaultAzureCredential is used in production
```
## Best Practices
1. **Minimum Data Points**: Univariate requires at least 12 points; more data improves accuracy
2. **Granularity Alignment**: Match `TimeGranularity` to your actual data frequency
3. **Sensitivity Tuning**: Higher values (0-99) detect more anomalies
4. **Multivariate Training**: Use 200-1000 sliding window based on pattern complexity
5. **Error Handling**: Always handle `HttpResponseException` for API errors
## Trigger Phrases
- "anomaly detection Java"
- "detect anomalies time series"
- "multivariate anomaly Java"
- "univariate anomaly detection"
- "streaming anomaly detection"
- "change point detection"
- "Azure AI Anomaly Detector"
所有文件
0 个文件安装 azure-ai-anomalydetector-java
下载技能文件并将其解压到 .claude/skills/ 目录下。
下载ZIP克隆仓库并复制技能文件到您的项目中。
git clone https://github.com/microsoft/skills/tree/main/.github/plugins/azure-sdk-java/skills/azure-ai-anomalydetector-java # Copy SKILL.md to your .claude/skills/ directory
复制





首页
