Skip to content

Commit 0309099

Browse files
Merge pull request #213625 from mrbullwinkle/mrb_10_04_2022_univariate_javascript
[Cognitive Services] [Anomaly Detector] univariate javascript quickstart updates
2 parents 48a521f + e13c9f7 commit 0309099

File tree

1 file changed

+148
-62
lines changed

1 file changed

+148
-62
lines changed

articles/cognitive-services/Anomaly-Detector/includes/quickstarts/anomaly-detector-client-library-javascript.md

Lines changed: 148 additions & 62 deletions
Original file line numberDiff line numberDiff line change
@@ -6,119 +6,176 @@ author: mrbullwinkle
66
manager: nitinme
77
ms.service: cognitive-services
88
ms.topic: include
9-
ms.date: 09/22/2020
9+
ms.date: 10/10/2022
1010
ms.author: mbullwin
1111
ms.custom: devx-track-js
1212
---
1313

14-
Get started with the Anomaly Detector client library for JavaScript. Follow these steps to install the package start using the algorithms provided by the service. The Anomaly Detector service enables you to find abnormalities in your time series data by automatically using the best-fitting models on it, regardless of industry, scenario, or data volume.
14+
<a href="https://go.microsoft.com/fwlink/?linkid=2090788" target="_blank">Library reference documentation</a> |<a href="https://github.com/Azure/azure-sdk-for-net/tree/main/sdk/anomalydetector" target="_blank">Library source code</a> | <a href="https://www.npmjs.com/package/%40azure/ai-anomaly-detector" target="_blank">Package (npm)</a> |<a href="https://github.com/Azure-Samples/cognitive-services-quickstart-code/tree/master/javascript/AnomalyDetector" target="_blank">Find the sample code on GitHub</a>
15+
16+
Get started with the Anomaly Detector client library for JavaScript. Follow these steps to install the package, and start using the algorithms provided by the service. The Anomaly Detector service enables you to find abnormalities in your time series data by automatically using the best-fitting model on it, regardless of industry, scenario, or data volume.
1517

1618
Use the Anomaly Detector client library for JavaScript to:
1719

1820
* Detect anomalies throughout your time series data set, as a batch request
1921
* Detect the anomaly status of the latest data point in your time series
2022
* Detect trend change points in your data set.
2123

22-
[Library reference documentation](https://go.microsoft.com/fwlink/?linkid=2090788) | [Library source code](https://github.com/Azure/azure-sdk-for-net/tree/main/sdk/anomalydetector) | [Package (npm)](https://www.npmjs.com/package/%40azure/ai-anomaly-detector) | [Find the code on GitHub](https://github.com/Azure-Samples/cognitive-services-quickstart-code/tree/master/javascript/AnomalyDetector)
23-
2424
## Prerequisites
2525

26-
* Azure subscription - [Create one for free](https://azure.microsoft.com/free/cognitive-services)
27-
* The current version of [Node.js](https://nodejs.org/)
28-
* Once you have your Azure subscription, <a href="https://portal.azure.com/#create/Microsoft.CognitiveServicesAnomalyDetector" title="Create an Anomaly Detector resource" target="_blank">create an Anomaly Detector resource </a> in the Azure portal to get your key and endpoint. Wait for it to deploy and click the **Go to resource** button.
29-
* You will need the key and endpoint from the resource you create to connect your application to the Anomaly Detector API. You'll paste your key and endpoint into the code below later in the quickstart.
26+
* An Azure subscription - <a href="https://azure.microsoft.com/free/cognitive-services" target="_blank">Create one for free</a>
27+
* The current version of <a href="https://nodejs.org/" target="_blank">Node.js</a>
28+
* Once you have your Azure subscription, <a href="https://portal.azure.com/#create/Microsoft.CognitiveServicesAnomalyDetector" title="Create an Anomaly Detector resource" target="_blank">create an Anomaly Detector resource </a> in the Azure portal to get your key and endpoint. Wait for it to deploy and select the **Go to resource** button.
29+
* You'll need the key and endpoint from the resource you create to connect your application to the Anomaly Detector API. You'll use the key and endpoint to create environment variables.
3030
You can use the free pricing tier (`F0`) to try the service, and upgrade later to a paid tier for production.
3131

32-
## Setting up
33-
34-
[!INCLUDE [anomaly-detector-environment-variables](../environment-variables.md)]
32+
## Set up
3533

3634
### Create a new Node.js application
3735

38-
In a console window (such as cmd, PowerShell, or Bash), create a new directory for your app, and navigate to it.
36+
In a console window (such as cmd, PowerShell, or Bash), create a new directory for your app, and navigate to it.
3937

4038
```console
4139
mkdir myapp && cd myapp
4240
```
4341

44-
Run the `npm init` command to create a node application with a `package.json` file.
42+
Create a `package.json` file with the following contents:
4543

46-
```console
47-
npm init
44+
```json
45+
{
46+
"dependencies": {
47+
"@azure/ai-anomaly-detector": "next",
48+
"@azure/core-auth": "^1.3.0",
49+
"csv-parse": "^4.4.0"
50+
}
51+
}
4852
```
4953

50-
Create a file named `index.js` and import the following libraries:
51-
52-
[!code-javascript[Import statements](~/cognitive-services-quickstart-code/javascript/AnomalyDetector/anomaly_detector_quickstart.js?name=imports)]
53-
54-
Create variables your resource's Azure endpoint and key. If you created the environment variable after you launched the application, you will need to close and reopen the editor, IDE, or shell running it to access the variable. Create another variable for the example data file you will download in a later step, and an empty list for the data points. Then create a `ApiKeyCredentials` object to contain the key.
55-
56-
[!code-javascript[Initial endpoint and key variables](~/cognitive-services-quickstart-code/javascript/AnomalyDetector/anomaly_detector_quickstart.js?name=vars)]
57-
5854
### Install the client library
5955

60-
Install the `ms-rest-azure` and `azure-cognitiveservices-anomalydetector` NPM packages. The csv-parse library is also used in this quickstart:
56+
Install the required npm packages by running the following from the same directory as your package.json file:
6157

6258
```console
63-
npm install @azure/ai-anomaly-detector @azure/ms-rest-js csv-parse
59+
npm install
6460
```
6561

66-
Your app's `package.json` file will be updated with the dependencies.
62+
## Retrieve key and endpoint
6763

68-
## Object model
64+
To successfully make a call against the Anomaly Detector service, you'll need the following values:
6965

70-
The Anomaly Detector client is an [AnomalyDetectorClient](/javascript/api/@azure/cognitiveservices-anomalydetector/anomalydetectorclient) object that authenticates to Azure using your key. The client can do anomaly detection on an entire dataset using [entireDetect()](/javascript/api/@azure/cognitiveservices-anomalydetector/anomalydetectorclient#entiredetect-request--servicecallback-entiredetectresponse--), or on the latest data point using [LastDetect()](/javascript/api/@azure/cognitiveservices-anomalydetector/anomalydetectorclient#lastdetect-request--msrest-requestoptionsbase-). The [ChangePointDetectAsync](https://go.microsoft.com/fwlink/?linkid=2090788) method detects points that mark changes in a trend.
66+
|Variable name | Value |
67+
|--------------------------|-------------|
68+
| `ANOMALY_DETECTOR_ENDPOINT` | This value can be found in the **Keys & Endpoint** section when examining your resource from the Azure portal. Example endpoint: `https://YOUR_RESOURCE_NAME.cognitiveservices.azure.com/`|
69+
| `ANOMALY_DETECTOR_API_KEY` | The API key value can be found in the **Keys & Endpoint** section when examining your resource from the Azure portal. You can use either `KEY1` or `KEY2`.|
70+
|`datapath` | This quickstart uses the `request-data.csv` file that can be downloaded from our [GitHub sample data](https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/anomalydetector/azure-ai-anomalydetector/samples/sample_data/request-data.csv).
7171

72-
Time series data is sent as series of [Points](/javascript/api/@azure/cognitiveservices-anomalydetector/point) in a [Request](/javascript/api/@azure/cognitiveservices-anomalydetector/request) object. The `Request` object contains properties to describe the data ([Granularity](/javascript/api/@azure/cognitiveservices-anomalydetector/request#granularity) for example), and parameters for the anomaly detection.
72+
Go to your resource in the Azure portal. The **Endpoint and Keys** can be found in the **Resource Management** section. Copy your endpoint and access key as you'll need both for authenticating your API calls. You can use either `KEY1` or `KEY2`. Always having two keys allows you to securely rotate and regenerate keys without causing a service disruption.
7373

74-
The Anomaly Detector response is a [LastDetectResponse](/javascript/api/@azure/cognitiveservices-anomalydetector/lastdetectresponse), [EntireDetectResponse](/javascript/api/@azure/cognitiveservices-anomalydetector/entiredetectresponse), or [ChangePointDetectResponse](https://go.microsoft.com/fwlink/?linkid=2090788) object depending on the method used.
74+
### Create environment variables
7575

76-
## Code examples
76+
Create and assign persistent environment variables for your key and endpoint.
7777

78-
These code snippets show you how to do the following with the Anomaly Detector client library for Node.js:
78+
# [Command Line](#tab/command-line)
7979

80-
* [Authenticate the client](#authenticate-the-client)
81-
* [Load a time series data set from a file](#load-time-series-data-from-a-file)
82-
* [Detect anomalies in the entire data set](#detect-anomalies-in-the-entire-data-set)
83-
* [Detect the anomaly status of the latest data point](#detect-the-anomaly-status-of-the-latest-data-point)
84-
* [Detect the change points in the data set](#detect-change-points-in-the-data-set)
85-
86-
## Authenticate the client
87-
88-
Instantiate a [AnomalyDetectorClient](/javascript/api/@azure/cognitiveservices-anomalydetector/anomalydetectorclient) object with your endpoint and credentials.
89-
90-
[!code-javascript[Authentication](~/cognitive-services-quickstart-code/javascript/AnomalyDetector/anomaly_detector_quickstart.js?name=authentication)]
91-
92-
## Load time series data from a file
80+
```CMD
81+
setx ANOMALY_DETECTOR_API_KEY "REPLACE_WITH_YOUR_KEY_VALUE_HERE"
82+
```
9383

94-
Download the example data for this quickstart from [GitHub](https://github.com/Azure-Samples/cognitive-services-quickstart-code/blob/master/javascript/AnomalyDetector/request-data.csv):
95-
1. In your browser, right-click **Raw**.
96-
2. Click **Save link as**.
97-
3. Save the file to your application directory, as a .csv file.
84+
```CMD
85+
setx ANOMALY_DETECTOR_ENDPOINT "REPLACE_WITH_YOUR_ENDPOINT_HERE"
86+
```
9887

99-
This time series data is formatted as a .csv file, and will be sent to the Anomaly Detector API.
88+
# [PowerShell](#tab/powershell)
10089

101-
Read your data file with the csv-parse library's `readFileSync()` method, and parse the file with `parse()`. For each line, push a [Point](/javascript/api/@azure/cognitiveservices-anomalydetector/point) object containing the timestamp, and the numeric value.
90+
```powershell
91+
[System.Environment]::SetEnvironmentVariable('ANOMALY_DETECTOR_API_KEY', 'REPLACE_WITH_YOUR_KEY_VALUE_HERE', 'User')
92+
```
10293

103-
[!code-javascript[Read the data file](~/cognitive-services-quickstart-code/javascript/AnomalyDetector/anomaly_detector_quickstart.js?name=readFile)]
94+
```powershell
95+
[System.Environment]::SetEnvironmentVariable('ANOMALY_DETECTOR_ENDPOINT', 'REPLACE_WITH_YOUR_ENDPOINT_HERE', 'User')
96+
```
10497

105-
## Detect anomalies in the entire data set
98+
# [Bash](#tab/bash)
10699

107-
Call the API to detect anomalies through the entire time series as a batch with the client's [entireDetect()](/javascript/api/@azure/cognitiveservices-anomalydetector/anomalydetectorclient#entiredetect-request--msrest-requestoptionsbase-) method. Store the returned [EntireDetectResponse](/javascript/api/@azure/cognitiveservices-anomalydetector/entiredetectresponse) object. Iterate through the response's `isAnomaly` list, and print the index of any `true` values. These values correspond to the index of anomalous data points, if any were found.
100+
```Bash
101+
echo export ANOMALY_DETECTOR_API_KEY="REPLACE_WITH_YOUR_KEY_VALUE_HERE" >> /etc/environment && source /etc/environment
102+
```
108103

109-
[!code-javascript[Batch detection function](~/cognitive-services-quickstart-code/javascript/AnomalyDetector/anomaly_detector_quickstart.js?name=batchCall)]
104+
```Bash
105+
echo export ANOMALY_DETECTOR_ENDPOINT="REPLACE_WITH_YOUR_ENDPOINT_HERE" >> /etc/environment && source /etc/environment
106+
```
110107

111-
## Detect the anomaly status of the latest data point
108+
---
112109

113-
Call the Anomaly Detector API to determine if your latest data point is an anomaly using the client's [lastDetect()](/javascript/api/@azure/cognitiveservices-anomalydetector/anomalydetectorclient#lastdetect-request--msrest-requestoptionsbase-) method, and store the returned [LastDetectResponse](/javascript/api/@azure/cognitiveservices-anomalydetector/lastdetectresponse) object. The response's `isAnomaly` value is a boolean that specifies that point's anomaly status.
110+
### Download sample data
114111

115-
[!code-javascript[Last point detection function](~/cognitive-services-quickstart-code/javascript/AnomalyDetector/anomaly_detector_quickstart.js?name=lastDetection)]
112+
This quickstart uses the `request-data.csv` file that can be downloaded from our [GitHub sample data](https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/anomalydetector/azure-ai-anomalydetector/samples/sample_data/request-data.csv)
116113

117-
## Detect change points in the data set
114+
You can also download the sample data by running:
118115

119-
Call the API to detect change points in the time series with the client's [detectChangePoint()](https://go.microsoft.com/fwlink/?linkid=2090788) method. Store the returned [ChangePointDetectResponse](https://go.microsoft.com/fwlink/?linkid=2090788) object. Iterate through the response's `isChangePoint` list, and print the index of any `true` values. These values correspond to the indices of trend change points, if any were found.
116+
```cmd
117+
curl "https://raw.githubusercontent.com/Azure/azure-sdk-for-python/main/sdk/anomalydetector/azure-ai-anomalydetector/samples/sample_data/request-data.csv" --output request-data.csv
118+
```
120119

121-
[!code-javascript[detect change points](~/cognitive-services-quickstart-code/javascript/AnomalyDetector/anomaly_detector_quickstart.js?name=changePointDetection)]
120+
## Detect anomalies
121+
122+
Create a file named `index.js` and replace with the following code:
123+
124+
```javascript
125+
/const { AnomalyDetectorClient, KnownTimeGranularity } = require("@azure/ai-anomaly-detector");
126+
const { AzureKeyCredential } = require("@azure/core-auth");
127+
128+
const fs = require("fs");
129+
const parse = require("csv-parse/lib/sync");
130+
131+
// You will need to set this environment variables or edit the following values
132+
const apiKey = process.env["ANOMALY_DETECTOR_API_KEY"] || "";
133+
const endpoint = process.env["ANOMALY_DETECTOR_ENDPOINT"] || "";
134+
const datapath = "./request-data.csv";
135+
136+
function read_series_from_file(path) {
137+
let result = Array();
138+
let input = fs.readFileSync(path).toString();
139+
let parsed = parse(input, { skip_empty_lines: true });
140+
parsed.forEach(function(e) {
141+
result.push({ timestamp: new Date(e[0]), value: Number(e[1]) });
142+
});
143+
return result;
144+
}
145+
146+
async function main() {
147+
// create client
148+
const client = new AnomalyDetectorClient(endpoint, new AzureKeyCredential(apiKey));
149+
150+
// construct request
151+
const request = {
152+
series: read_series_from_file(datapath),
153+
granularity: KnownTimeGranularity.daily
154+
};
155+
156+
// get entire detect result
157+
const result = await client.detectEntireSeries(request);
158+
159+
if (
160+
result.isAnomaly.some(function(anomaly) {
161+
return anomaly === true;
162+
})
163+
) {
164+
console.log("Anomalies were detected from the series at index:");
165+
result.isAnomaly.forEach(function(anomaly, index) {
166+
if (anomaly === true) {
167+
console.log(index);
168+
}
169+
});
170+
} else {
171+
console.log("There is no anomaly detected from the series.");
172+
}
173+
}
174+
175+
main().catch((err) => {
176+
console.error("The sample encountered an error:", err);
177+
});
178+
```
122179

123180
## Run the application
124181

@@ -128,4 +185,33 @@ Run the application with the `node` command on your quickstart file.
128185
node index.js
129186
```
130187

131-
[!INCLUDE [anomaly-detector-next-steps](../quickstart-cleanup-next-steps.md)]
188+
### Output
189+
190+
```console
191+
Anomalies were detected from the series at index:
192+
3
193+
18
194+
21
195+
22
196+
23
197+
24
198+
25
199+
28
200+
29
201+
30
202+
31
203+
32
204+
35
205+
44
206+
```
207+
208+
### Understanding your results
209+
210+
In the code above, we call the Anomaly Detector API to detect anomalies through the entire time series as a batch with the client's [detectEntireSeries()](/javascript/api/@azure/ai-anomaly-detector/anomalydetectorclient?view=azure-node-preview#@azure-ai-anomaly-detector-anomalydetectorclient-detectentireseries&preserve-view=true) method. We store the returned [AnomalyDetectorDetectEntireSeriesResponse](/javascript/api/@azure/ai-anomaly-detector/anomalydetectordetectentireseriesresponse?view=azure-node-preview&preserve-view=true) object. Then we iterate through the response's `isAnomaly` list, and print the index of any `true` values. These values correspond to the index of anomalous data points, if any were found.
211+
212+
## Clean up resources
213+
214+
If you want to clean up and remove an Anomaly Detector resource, you can delete the resource or resource group. Deleting the resource group also deletes any other resources associated with it. You also may want to consider [deleting the environment variables](/powershell/module/microsoft.powershell.core/about/about_environment_variables?view=powershell-7.2#using-the-environment-provider-and-item-cmdlets&preserve-view=true) you created if you no longer intend to use them.
215+
216+
* [Portal](../../../cognitive-services-apis-create-account.md#clean-up-resources)
217+
* [Azure CLI](../../../cognitive-services-apis-create-account-cli.md#clean-up-resources)

0 commit comments

Comments
 (0)