

Amazon Fraud Detector is no longer open to new customers as of November 7, 2025. For capabilities similar to Amazon Fraud Detector, explore Amazon SageMaker, AutoGluon, and AWS WAF.

# Get started with Amazon Fraud Detector
<a name="get-started"></a>

Before you get started, make sure that you have read [Detecting fraud with Amazon Fraud Detector](frauddetector-workflow.md) and completed steps in [Set up for Amazon Fraud Detector](set-up.md).

Use the hands-on tutorials in this section to learn how you can use Amazon Fraud Detector to build, train, and deploy a fraud detection model. For this tutorial, you assume the role of a fraud analyst using machine learning model to predict whether a new account registration is fraudulent. The model must be trained using data from account registrations. Amazon Fraud Detector provides an example account registration dataset for this tutorial. The example dataset must be uploaded before you get started with the tutorial.

You can get started with Amazon Fraud Detector using one of the following interfaces. Before getting started with the tutorial, make sure that you follow instructions to [Get and upload example dataset](step-1-get-s3-data.md)
+ [Tutorial: Get started using the Amazon Fraud Detector console](get-started-console.md)
+ [Tutorial: Get started using the AWS SDK for Python (Boto3)](getting-started-python.md)

# Get and upload example dataset
<a name="step-1-get-s3-data"></a>

The example dataset you use in this tutorial provides details of online account registrations. The dataset is in a text file that uses comma-separated value (CSV) in the UTF-8 format. The first row of the CSV dataset file contains the headers. The header row is followed by multiple rows of data. Each of these rows consists of data elements from a single account registration. The data is labeled for your convenience. A column in the dataset identifies whether the account registration is fraudulent.

**To get and upload example dataset**

1. Go to [Samples](https://github.com/aws-samples/aws-fraud-detector-samples/tree/master/data).

    There are two data files that has online account registration data - *registration\$1data\$120K\$1minimum.csv* and *registration\$1data\$120K\$1full.csv*. The file `registration_data_20K_minimum` contains only two variables: *ip\$1address* and *email\$1address*. The file `registration_data_20K_full` contains other variables. These variables are for each event and they include *billing\$1address*, *phone\$1number*, and *user\$1agent*. Both data files also contain two mandatory fields: 
   + EVENT\$1TIMESTAMP – Defines when the event occurred
   + EVENT\$1LABEL – Classifies the event as fraudulent or legitimate

   You can use either one of the two files for this tutorial. Download the data file you want to use.

1. Create an Amazon Simple Storage Service (Amazon S3) bucket.

   In this step, you create an external storage to store the dataset. This external storage is Amazon S3 bucket. For more information about Amazon S3, see [What is Amazon S3?](https://docs.aws.amazon.com/AmazonS3/latest/userguide/Welcome.html)

   1. Sign in to the AWS Management Console and open the Amazon S3 console at [https://console.aws.amazon.com/s3/](https://console.aws.amazon.com/s3/).

   1. In **Buckets**, choose **Create bucket**.

   1. For **Bucket name**, enter a bucket name. Make sure that you follow the bucket naming rules in the console, and provide a globally unique name. We recommend you use a name that describes the bucket's purpose.

   1. For **AWS Region**, choose the AWS Region where you want to create your bucket. The Region that you choose must support Amazon Fraud Detector. To reduce latency, choose the AWS Region that's closest to your geographic location. For a list of Regions that support Amazon Fraud Detector, see the [Region Table](https://aws.amazon.com/about-aws/global-infrastructure/regional-product-services/) in the *Global Infrastructure Guide*.

   1. Leave the default settings for **Object Ownership**, **Bucket settings for Block Public Access**, **Bucket Versioning**, and **Tags** for this tutorial.

   1. For **Default encryption**, choose **Disable** for this tutorial.

   1. Review your bucket configuration, and then choose **Create bucket**.

1. Upload example data file to Amazon S3 bucket.

   Now that you have a bucket, upload one of the example files that you downloaded previously to the Amazon S3 bucket that you just created.

   1. In the **Buckets**, your bucket name is listed. Choose your bucket.

   1. Choose **Upload**.

   1. In **Files and folders**, choose **Add files**.

   1. Choose one of the example data files that you downloaded on your computer, and then choose **Open**.

   1. Leave the default settings for **Destination**, **Permissions**, and **Properties**.

   1. Review configurations, and then choose **Upload**.

   1. The example data file is uploaded to Amazon S3 bucket. Make a note of the bucket location. In the **Objects**, choose the example data file that you just uploaded.

   1. In the **Object overview**, copy the location under **S3 URI**. This is the Amazon S3 location of your example data file. You use it later. You can additionally copy the **Amazon Resource Name (ARN)** of your S3 bucket and save it.

# Tutorial: Get started using the Amazon Fraud Detector console
<a name="get-started-console"></a>

This tutorial consists of two parts. The first part describes how to build, train, and deploy a fraud detection model. The second part covers how to use the model to generate fraud predictions in real time. The model is trained using the example data file that you upload to an S3 bucket. By the end of this tutorial, you complete the following actions:
+ Build and train an Amazon Fraud Detector model
+ Generate real-time fraud predictions

**Important**  
Before you proceed, make sure that you have followed instructions to [Get and upload example dataset](step-1-get-s3-data.md)

# Part A: Build, train, and deploy an Amazon Fraud Detector model
<a name="part-a"></a>

In part A, you define your business use case, define your event, build a model, train the model, evaluate model's performance, and deploy the model.

## Step 1: Choose your business use case
<a name="choose-business-use-case"></a>
+ In this step, you use the **data models explorer** to match your business use case with the fraud detection model types supported by Amazon Fraud Detector. Data models explorer is a tool integrated with the Amazon Fraud Detector console that recommends a model type to use for creating and training a fraud detection model for your business use case. Data models explorer also provides insights into the mandatory, recommended, and optional data elements you will require to include in your dataset. The dataset will be used to create and train your fraud detection model.

  For the purpose of this tutorial, your business use case is new account registrations. After you specify your business use case, the data models explorer will recommend a model type for creating a fraud detection model and will also provide you with a list of data elements you will need to create your dataset. Since you have already uploaded a sample dataset containing data from new account registrations, you do not need to create a new dataset.

  1. Open the [AWS Management Console](https://console.aws.amazon.com) and sign in to your account. Navigate to Amazon Fraud Detector.

  1. In the left navigation pane, choose **Data models explorer**.

  1. In the **Data models explorer** page, under **Business use case**, select **New account fraud**.

  1. Amazon Fraud Detector displays the recommended model type to use to create a fraud detection model for the selected business use case. The model type defines the algorithms, enrichments, and transformations Amazon Fraud Detector will use to train your fraud detection model.

     Make a note of the recommended model type. You will need this later when you create your model.

  1. The **Data model insights** pane provides insight into the mandatory and recommended data elements required to create and train a fraud detection model. 

     Take a look at the sample dataset you downloaded and make sure that it has all the mandatory and some recommended data elements listed in the table. 

     Later when you create a model for your specific business use case, you will use the insights provided to create your dataset.

## Step 2: Create event type
<a name="define-event"></a>
+ In this step, you define the business activity (event) to evaluate for fraud. Defining the event involves setting the variables that are in your dataset, the entity initiating event, and the labels that classify the event. For this tutorial, you define the account registration event.

  1. Open the [AWS Management Console](https://console.aws.amazon.com) and sign in to your account. Navigate to Amazon Fraud Detector.

  1. In the left navigation pane, choose **Events**.

  1. In the **Events type** page, choose **Create**.

  1. Under **Event type details**, enter `sample_registration` as the event type name and, optionally, enter a description of the event.

  1. For **Entity**, choose **Create entity**.

  1. In the **Create entity** page, enter `sample_customer` as the entity type name. Optionally, enter a description of the entity type.

  1. Choose **Create entity**.

  1. Under **Event variables**, for **Choose how to define this event's variables**, choose **Select variables from a training dataset**.

  1. For **IAM role**, choose **Create IAM role**.

  1. In the **Create IAM role** page, enter the name of the S3 bucket that you uploaded your example data to and choose **Create role**.

  1. In **Data location**, enter the path to your example data. This is the `S3 URI` path that you saved after uploading the example data. The path is similar to this: `S3://your-bucket-name/example dataset filename.csv`. 

  1. Choose **Upload**.

     Amazon Fraud Detector extracts the headers from your example data file and maps them with a variable type. The mapping is displayed in the console.

  1. Under **Labels - optional**, for **Labels**, choose **Create new labels**.

  1. In **Create label** page, enter `fraud` as the name. This label corresponds to the value that represents the fraudulent account registration in the example dataset. 

  1. Choose **Create label**.

  1. Create a second label, then enter `legit` as the name. This label corresponds to the value that represents the legitimate account registration in the example dataset.

  1. Choose **Create event type**.

## Step 3: Create model
<a name="step-3-create-new-ml-model"></a>

1. On the **Models** page, choose **Add model**, and then choose **Create model**.

1. For **Step 1 – Define model details**, enter `sample_fraud_detection_model` as the model name. Optionally, add a description of the model.

1. For **Model Type**, choose the **Online Fraud Insights** model. 

1. For **Event type**, choose **sample\$1registration**. This is the event type that you created in Step 1.

1. In **Historical event data**, 

   1. In **Event data source**, choose **Event data stored in S3**.

   1. For **IAM role**, select the role that you created in Step 1.

   1. In **Training data location**, enter the S3 URI path to your example data file.

1. Choose **Next**.

## Step 4: Train model
<a name="step-4-training-data-assign-perms"></a>

1. In **Model inputs**, leave all checkboxes checked. By default, Amazon Fraud Detector uses all variables from your historical event dataset as model inputs.

1. In **Label classification**, for **Fraud labels** choose **fraud** as this label corresponds to the value that represents fraudulent events in the example dataset. For **Legitimate labels**, choose **legit** as this label corresponds to the value that represents legitimate events in the example dataset. 

1. For the **Unlabeled events treatment**, keep the default selection **Ignore unlabeled events** for this example dataset.

1. Choose **Next**.

1. After reviewing, choose **Create and train model**. Amazon Fraud Detector creates a model and begins to train a new version of the model.

   In **Model versions** the **Status** column indicates the status of model training. Model training that uses the example dataset takes approximately 45 minutes to complete. The status changes to **Ready to deploy** after model training is complete.

# Step 5: Review model performance
<a name="step-6-review-trained-model-performance"></a>

An important step in using Amazon Fraud Detector is to assess the accuracy of your model using model scores and performance metrics. After model training is complete, Amazon Fraud Detector validates model performance using the 15% of your data that wasn't used to train the model and generates a model performance score and other performance metrics.

1. To view model's performance,

   1. In the left navigation pane of the Amazon Fraud Detector console, choose **Models**.

   1. In the **Models** page, choose the model that you just trained (**sample\$1fraud\$1detection\$1model**), and then choose **1.0**. This is the version Amazon Fraud Detector created of your model.

1. Look at the **Model performance** overall score and all other metrics that Amazon Fraud Detector generated for this model.

   To learn more about the model performance score and performance metrics on this page, see [Model scores](model-scores.md) and [Model performance metrics](training-performance-metrics.md).

   You can expect all your trained Amazon Fraud Detector models to have real-world fraud detection performance metrics that are similar to the performance metrics that you see for the model in this tutorial.

# Step 6: Deploy model
<a name="get-started-deploy-model"></a>

After you reviewed the performance metrics of your trained model and are ready to use it generate fraud predictions, you can deploy the model.

1. In left navigation pane of the Amazon Fraud Detector console, choose **Models**.

1. In the **Models** page, choose **sample\$1fraud\$1detection\$1model**, and then choose the specific model version that you want to deploy. For this tutorial, choose **1.0**.

1. On the **Model version** page, choose **Actions** and then choose **Deploy model version**.

1. In the **Model versions**, the **Status** shows the status of the deployment. The status changes to **Active** after the deployment completes. This indicates that the model version is activated and available to generate fraud predictions. Continue with [Part B: Generate fraud predictions](part-b.md) to complete steps for generating fraud predictions.

# Part B: Generate fraud predictions
<a name="part-b"></a>

Fraud prediction is an evaluation of fraud for a business activity (event). Amazon Fraud Detector uses detectors to generate fraud prediction. A detector contains detection logic, such as models and rules, for a specific event that you want to evaluate for fraud. Detection logic uses rules to tell Amazon Fraud Detector how to interpret the data associated with the model. In this tutorial, you evaluate the account registration event using the account registration example dataset that you uploaded earlier. 

In Part A, you created, trained, and deployed your model. In Part B, you build a detector for the `sample_registration` event type, add the deployed model, create rules and a rule execution order, and then create and activate a version of the detector that you use to generate fraud predictions.

## Step 1: Build detector
<a name="step-1-create-app"></a>

**To create detector**

1. In the left navigation pane of the Amazon Fraud Detector console, choose **Detectors**.

1. Choose **Create detector**.

1. In the **Define detector details** page, enter `sample_detector` for detector name. Optionally, enter a description for the detector, such as `my sample fraud detector`.

1. For **Event Type**, select **sample\$1registration**. This is the event that you created in Part A of this tutorial. 

1. Choose **Next**. 

## Step 2: Add model
<a name="add-model-detector"></a>

If you completed Part A of this tutorial, then you likely already have an Amazon Fraud Detector model that's available to add to your detector. If you didn't already create a model, go to Part A and complete the steps to create, train, and deploy a model and then continue with Part B. 

1. In the **Add model - optional**, choose **Add Model**.

1. In the **Add model** page, for **Select model**, choose the Amazon Fraud Detector model name that you deployed earlier. For **Select version**, choose the model version of the deployed model.

1. Choose **Add model**.

1. Choose **Next**.

## Step 3: Add rules
<a name="add-rules-to-detector"></a>

A rule is a condition that tells Amazon Fraud Detector how to interpret model performance score when evaluating for fraud prediction. For this tutorial, you create three rules: `high_fraud_risk`, `medium_fraud_risk`, and `low_fraud_risk`.

1. In the **Add rules** page, under **Define a rule**, enter `high_fraud_risk` for the rule name and under **Description - optional**, enter **This rule captures events with a high ML model score** as the description for the rule.

1. In **Expression**, enter the following rule expression using the Amazon Fraud Detector simpliﬁed rule expression language:

   `$sample_fraud_detection_model_insightscore > 900`

1. In **Outcomes**, choose **Create a new outcome**. An outcome is the result from a fraud prediction and is returned if the rule matches during an evaluation. 

1. In **Create a new outcome**, enter `verify_customer` as the outcome name. Optionally, enter a description.

1. Choose **Save outcome**. 

1. Choose **Add rule** to run the rule validation checker and save the rule. After it's created, Amazon Fraud Detector makes the rule available for use in your detector.

1. Choose **Add another rule**, and then choose the **Create rule** tab. 

1. Repeat this process twice more to create your `medium_fraud_risk` and `low_fraud_risk` rules using the following rule details: 
   + medium\$1fraud\$1risk

     Rule name: `medium_fraud_risk`

     Outcome: `review`

     Expression:

     `$sample_fraud_detection_model_insightscore <= 900 and`

     `$sample_fraud_detection_model_insightscore > 700`
   + low\$1fraud\$1risk

     Rule name: `low_fraud_risk`

     Outcome: `approve`

     Expression:

     `$sample_fraud_detection_model_insightscore <= 700`

   These values are examples used for this tutorial. When you create rules for your own detector, use values that are appropriate for your model and your use case,

1. After you have created all three rules, choose **Next**. 

   For more information about creating and writing rules, see [Rules](rules.md) and [Rule language reference](rule-language-reference.md).

## Step 4: Configure rule execution and rule order
<a name="get-start-define-rule-order"></a>

The rule execution mode for the rules that are included in the detector determines if all the rules you define are evaluated, or if rule evaluation stops at the first matched rule. And the rule order determines the order that you want the rule to be run in. 

The default rule execution mode is `FIRST_MATCHED`. 

**First matched**  
First matched rule execution mode returns the outcomes for the first matching rule based on defined rule order. If you specify `FIRST_MATCHED`, Amazon Fraud Detector evaluates rules sequentially, first to last, stopping at the first matched rule. Amazon Fraud Detector then provides the outcomes for that single rule.   
The order that you run rules in can affect the resulting fraud prediction outcome. After you have created your rules, re-order the rules to run them in the desired order by following these steps:   
If your `high_fraud_risk` rule isn't already on the top of your rule list, choose **Order**, and then choose **1**. This moves `high_fraud_risk` to the first position.  
Repeat this process so that your `medium_fraud_risk` rule is in the second position and your `low_fraud_risk` rule is in the third position.

**All matched**  
All matched rule execution mode returns outcomes for all matched rules, regardless of rule order. If you specify `ALL_MATCHED`, Amazon Fraud Detector evaluates all rules and returns the outcomes for all matched rules.

Select `FIRST_MATCHED` for this tutorial and then choose **Next**.

# Step 5: Review and create detector version
<a name="get-start-review-and-create-detector-version"></a>

A detector version defines the specific models and rules that are used for generating fraud predictions.

1. In the **Review and create** page, review the detector details, models, and rules that you configured. If you need to make any changes, choose **Edit** next to the corresponding section.

1. Choose **Create detector**. After it's created, the ﬁrst version of your detector appears in the Detector versions table with `Draft` status.

   You use the **Draft** version to test your Detector.

# Step 6: Test and activate detector version
<a name="step-6-eval-event-get-outcome"></a>

In the Amazon Fraud Detector console, you can test the logic of your detector using a mock data with the **Run test** feature. For this tutorial, you can use account registration data from the example dataset.

1. Scroll to **Run test** at the bottom of the **Detector version details** page.

1. For **Event metadata**, enter a timestamp of when the event occurred and enter a unique identifier for the entity performing the event. For this tutorial, select a date from the date picker for timestamp, and enter “1234” for the Entity ID. 

1. For **Event variable**, enter the variable values that you want to test. For this tutorial, you only need the `ip_address` and `email_address` fields. This is because they are the inputs that are used to train your Amazon Fraud Detector model. You can use the following example values. This assumes that you used the suggested variable names:
   + ip\$1address: `205.251.233.178`
   + email\$1address: `johndoe@exampledomain.com`

1. Choose **Run test**.

1. Amazon Fraud Detector returns the fraud prediction outcome based on the rule execution mode. If the rule execution mode is `FIRST_MATCHED`, the returned outcome corresponds to the first rule that matched. The first rule is the rule with the highest priority. It's matched if it's evaluated as true. If the rule execution mode is `ALL_MATCHED`, the returned outcome corresponds to all rules that matched. That means that they're all evaluated to be true. Amazon Fraud Detector also returns the model score for any models added to your detector.

   You can change the inputs and run couple of tests to see different outcomes. You can use the *ip\$1address* and *email\$1address* values from your example dataset for the tests and check if the outcomes are as expected.

1. When you're satisfied with how the detector is working, promote it from `Draft` to `Active`. Doing so makes the detector available for use in real-time fraud detection.

   On the **Detector version details** page, choose **Actions**, **Publish**, **Publish version**. This changes the status of the detector from **Draft** to **Active.**

   At this point, your model and the associated detector logic are ready to evaluate online activities for fraud in real time using the Amazon Fraud Detector `GetEventPrediction` API. You can also evaluate events offline using a CSV input file and the `CreateBatchPredictionJob` API. For more information about fraud prediction, see [Fraud predictions](getting-fraud-predictions.md)

By completing this tutorial, you did the following:
+ Uploaded an example event dataset to Amazon S3.
+ Created and trained an Amazon Fraud Detector fraud detection model using the example dataset.
+ Viewed the model performance score and other performance metrics that Amazon Fraud Detector generated.
+ Deployed the fraud detection model.
+ Created a detector and added the deployed model.
+ Added rules, the rule execution order, and outcomes to the detector.
+ Tested the detector by providing different inputs and checking if the rules and rule execution order worked as expected.
+ Activated the detector by publishing it.

# Tutorial: Get started using the AWS SDK for Python (Boto3)
<a name="getting-started-python"></a>

This tutorial describes how to build and train an Amazon Fraud Detector model and then using this model to generate real-time fraud predictions using the AWS SDK for Python (Boto3). The model is trained using the account registration example data file that you upload to Amazon S3 bucket.

By the end of this tutorial, you complete the following actions:
+ Build and train an Amazon Fraud Detector model
+ Generate real-time fraud predictions

## Prerequisites
<a name="gs-sdk-prerequisites"></a>

The following are prerequisite steps for this tutorial.
+ Completed [Set up for Amazon Fraud Detector](set-up.md). 

  If you have already [Set up AWS SDK](set-up.md#set-up-sdk), make sure that you're using Boto3 SDK version 1.14.29 or higher.
+ Followed instructions to [Get and upload example dataset](step-1-get-s3-data.md) file that's required for this tutorial. 

## Get started
<a name="get-started-python"></a>

### Step 1: Set up and verify your Python environment
<a name="setup-and-verify-your-python-environment"></a>

Boto is the Amazon Web Services (AWS) SDK for Python. You can use it to create, configure, and manage AWS services. For instructions on how to install Boto3, see [AWS SDK for Python (Boto3)](https://boto3.amazonaws.com/v1/documentation/api/latest/index.html).

After you install AWS SDK for Python (Boto3), run the following Python example command to confirm that your environment is configured correctly. If your environment is configured correctly, the response contains a list of detectors. If no detectors were created, the list is empty. 

```
import boto3
fraudDetector = boto3.client('frauddetector')
            
response = fraudDetector.get_detectors()
print(response)
```

### Step 2: Create variables, entity type, and labels
<a name="create-variables-entity-type-and-labels"></a>

In this step, you create resources that are used to define model, event, and rules.

#### Create variable
<a name="create-variable-gs-sdk"></a>

A variable is a data element from your dataset that you want to use to create event type, model, and rules.

In the following example,the [CreateVariable](https://docs.aws.amazon.com//frauddetector/latest/api/API_CreateVariable.html) API is used to create two variables. The variables are `email_address` and `ip_address`. Assign them to the corresponding variable types: `EMAIL_ADDRESS` and `IP_ADDRESS`. These variables are part of the example dataset you uploaded. When you specify the variable type, Amazon Fraud Detector interprets the variable during model training and when getting predictions. Only variables with an associated variable type can be used for model training.

```
import boto3
fraudDetector = boto3.client('frauddetector')

 #Create variable email_address
fraudDetector.create_variable(
    name = 'email_address',
    variableType = 'EMAIL_ADDRESS',
    dataSource = 'EVENT',
    dataType = 'STRING',
    defaultValue = '<unknown>'
)

#Create variable ip_address
fraudDetector.create_variable(
    name = 'ip_address',
    variableType = 'IP_ADDRESS',
    dataSource = 'EVENT',
    dataType = 'STRING',
    defaultValue = '<unknown>'
)
```

#### Create entity type
<a name="create-entity-gs-sdk"></a>

An entity represents who is performing the event and an entity type classifies the entity. Example classifications include *customer*, *merchant*, or *account*.

In the following example, [PutEntityType](https://docs.aws.amazon.com//frauddetector/latest/api/API_PutEntityType.html) API is used to create a `sample_customer` entity type.

```
import boto3
fraudDetector = boto3.client('frauddetector')

fraudDetector.put_entity_type(
   name = 'sample_customer',
   description = 'sample customer entity type'
)
```

#### Create label
<a name="create-label-gs-sdk"></a>

A label classifies an event as fraudulent or legitimate and is used to train the fraud detection model. The model learns to classify events using these label values.

In the following example, the [Putlabel](https://docs.aws.amazon.com//frauddetector/latest/api/API_PutLabel.html) API is used to create two labels, `fraud` and `legit`.

```
import boto3
fraudDetector = boto3.client('frauddetector')

fraudDetector.put_label(
    name = 'fraud',
    description = 'label for fraud events'
)

fraudDetector.put_label(
    name = 'legit',
    description = 'label for legitimate events'
)
```

### Step 3: Create event type
<a name="python-create-event-type"></a>

With Amazon Fraud Detector, you build models that evaluate risks and generate fraud predictions for individual events. An event type defines the structure of an individual event. 

In the following example, the [PutEventType](https://docs.aws.amazon.com//frauddetector/latest/api/API_PutEventType.html) API is used to create an event type `sample_registration`. You define the event type by specifying the variables (`email_address`,`ip_address`), entity type (`sample_customer`), and labels (`fraud`, `legit`) that you created in the previous step. 

```
import boto3
fraudDetector = boto3.client('frauddetector')

fraudDetector.put_event_type (
     name = 'sample_registration',
     eventVariables = ['ip_address', 'email_address'],
     labels = ['legit', 'fraud'],
     entityTypes = ['sample_customer'])
```

### Step 4: Create, train, and deploy model
<a name="python-create-and-train-a-model"></a>

Amazon Fraud Detector trains models to learn to detect fraud for a specific event type. In the previous step, you created the event type. In this step, you create and train a model for the event type. The model acts as a container for your model versions. Each time you train a model, a new version is created. 

Use following example codes to create and train an Online Fraud Insights model. This model is called `sample_fraud_detection_model`. It's for the event type `sample_registration` using the account registration example dataset that you uploaded to Amazon S3.

For more information about different model types that Amazon Fraud Detector supports, see [Choose a model type](choosing-model-type.md).

**Create a model**

In the following example, the [CreateModel](https://docs.aws.amazon.com//frauddetector/latest/api/API_CreateModel.html) API is used to create a model.

```
import boto3
fraudDetector = boto3.client('frauddetector')

fraudDetector.create_model (
       modelId = 'sample_fraud_detection_model',
       eventTypeName = 'sample_registration',
       modelType = 'ONLINE_FRAUD_INSIGHTS')
```

**Train a model**

In the following example, the [CreateModelVersion](https://docs.aws.amazon.com//frauddetector/latest/api/API_CreateModelVersion.html) API is used to train the model. Specify `'EXTERNAL_EVENTS'` for the `trainingDataSource` and the Amazon S3 location where you stored your example dataset and the *RoleArn* of the Amazon S3 bucket for `externalEventsDetail`. For `trainingDataSchema` parameter, specify how Amazon Fraud Detector interprets the example data. More specifically, specify which variables to include and how to classify the event labels.

```
import boto3
fraudDetector = boto3.client('frauddetector')

fraudDetector.create_model_version (
         modelId = 'sample_fraud_detection_model',
         modelType = 'ONLINE_FRAUD_INSIGHTS',
         trainingDataSource = 'EXTERNAL_EVENTS',
         trainingDataSchema = {
            'modelVariables' : ['ip_address', 'email_address'],
            'labelSchema' : {
               'labelMapper' : {
                   'FRAUD' : ['fraud'],
                   'LEGIT' : ['legit']
        }
    }
}, 
         externalEventsDetail = {
              'dataLocation' : 's3://amzn-s3-demo-bucket/your-example-data-filename.csv',
              'dataAccessRoleArn' : 'role_arn'
}
)
```

You can train your model multiple times. Each time that you train a model, a new version is created. After model training is complete, the model version status updates to `TRAINING_COMPLETE`. You can review the model performance score and other model performance metrics.

**Review model performance**

An important step in using Amazon Fraud Detector is to assess the accuracy of your model using model scores and performance metrics. After model training is complete, Amazon Fraud Detector validates model performance using the 15% of your data that wasn't used to train the model. It generates a model performance score and other performance metrics.

Use the [DescribeModelVersions](https://docs.aws.amazon.com//frauddetector/latest/api/API_DescribeModelVersions.html) API to review model performance. Look at the **Model performance** overall score and all other metrics generated by Amazon Fraud Detector for this model.

To learn more about the model performance score and performance metrics, see [Model scores](model-scores.md) and [Model performance metrics](training-performance-metrics.md).

You can expect all your trained Amazon Fraud Detector models to have real-world fraud detection performance metrics, which are similar to the metrics in this tutorial.

**Deploy a model**

After you reviewed the performance metrics of your trained model, deploy the model and make it available to Amazon Fraud Detector to generate fraud predictions. To deploy the trained model, use the [UpdateModelVersionStatus](https://docs.aws.amazon.com//frauddetector/latest/api/API_UpdateModelVersionStatus.html) API. In the following example, it's used to update the model version status to ACTIVE.

```
import boto3
fraudDetector = boto3.client('frauddetector')

fraudDetector.update_model_version_status (
     modelId = 'sample_fraud_detection_model',
     modelType = 'ONLINE_FRAUD_INSIGHTS',
     modelVersionNumber = '1.00',
     status = 'ACTIVE'
)
```

### Step 5: Create detector, outcomes, rules, and detector version
<a name="python-create-a-detector-outcome-rules-and-detector-version"></a>

A detector contains the detection logic, such as the models and rules. This logic is for a particular event that you want to evaluate for fraud. A rule is a condition that you specify to tell Amazon Fraud Detector how to interpret variable values during prediction. And outcome is the result of a fraud prediction. A detector can have multiple versions with each version having a status of *DRAFT*, *ACTIVE*, or *INACTIVE*. A detector version must have at least one rule that's associated with it. 

Use the following example codes to create detector, rules, outcome, and to publish the detector. 

**Create a detector**

In the following example, the [PutDetector](https://docs.aws.amazon.com//frauddetector/latest/api/API_PutDetector.html) API is used to create a `sample_detector` detector for `sample_registration` event type.

```
import boto3
fraudDetector = boto3.client('frauddetector')

fraudDetector.put_detector (
     detectorId = 'sample_detector',
     eventTypeName = 'sample_registration'
)
```

**Create outcomes**

Outcomes are created for each possible fraud prediction result. In the following example, the [PutOutcome](https://docs.aws.amazon.com//frauddetector/latest/api/API_PutOutcome.html) API is used to create three outcomes - `verify_customer`, `review`, and `approve`. These outcomes are later assigned to rules. 

```
import boto3
fraudDetector = boto3.client('frauddetector')

fraudDetector.put_outcome(
     name = 'verify_customer',
     description = 'this outcome initiates a verification workflow'
    )

fraudDetector.put_outcome(
     name = 'review',
     description = 'this outcome sidelines event for review'
    )

fraudDetector.put_outcome(
     name = 'approve',
     description = 'this outcome approves the event'
)
```

**Create rules**

Rule consists of one or more variables from your dataset, a logic expression, and one or more outcomes. 

In the following example, the [CreateRule](https://docs.aws.amazon.com//frauddetector/latest/api/API_CreateRule.html) API is used to create three different rules: `high_risk`, `medium_risk`, and `low_risk`. Create rule expressions to compare the model performance score `sample_fraud_detection_model_insightscore` value against various thresholds. This is to determine the level of risk for an event and assign outcome that was defined in the previous step. 

```
import boto3
fraudDetector = boto3.client('frauddetector')

fraudDetector.create_rule(
     ruleId = 'high_fraud_risk',
     detectorId = 'sample_detector',
     expression = '$sample_fraud_detection_model_insightscore > 900',
     language = 'DETECTORPL',
     outcomes = ['verify_customer']
     )

fraudDetector.create_rule(
     ruleId = 'medium_fraud_risk',
     detectorId = 'sample_detector',
     expression = '$sample_fraud_detection_model_insightscore <= 900 and $sample_fraud_detection_model_insightscore > 700',
     language = 'DETECTORPL',
     outcomes = ['review']
     )

fraudDetector.create_rule(
     ruleId = 'low_fraud_risk',
     detectorId = 'sample_detector',
     expression = '$sample_fraud_detection_model_insightscore <= 700',
     language = 'DETECTORPL',
     outcomes = ['approve']
     )
```

**Create a detector version**

A detector version defines model and rules that are used to get fraud prediction.

In the following example, the [CreateDetectorVersion](https://docs.aws.amazon.com//frauddetector/latest/api/API_CreateDetectorVersion.html) API is used to create a detector version. It does this by providing model version details, rules, and a rule execution mode FIRST\$1MATCHED. A rule execution mode specifies the sequence for evaluating rules. The rule execution mode FIRST\$1MATCHED specifies that the rules are evaluated sequentially, first to last, stopping at first matched rule.

```
import boto3
fraudDetector = boto3.client('frauddetector')

fraudDetector.create_detector_version(
      detectorId = 'sample_detector',
      rules = [{
          'detectorId' : 'sample_detector',
          'ruleId' : 'high_fraud_risk',
          'ruleVersion' : '1'
},
{
          'detectorId' : 'sample_detector',
          'ruleId' : 'medium_fraud_risk',
          'ruleVersion' : '1'
},
{
          'detectorId' : 'sample_detector',
          'ruleId' : 'low_fraud_risk',
          'ruleVersion' : '1'
}
],
      modelVersions = [{
          'modelId' : 'sample_fraud_detection_model',
          'modelType': 'ONLINE_FRAUD_INSIGHTS',
          'modelVersionNumber' : '1.00'
}      ],
      ruleExecutionMode = 'FIRST_MATCHED'
)
```

### Step 6: Generate fraud predictions
<a name="python-generate-fraud-predictions"></a>

The last step of this tutorial uses the detector `sample_detector` created in the previous step to generate fraud predictions for `sample_registration` event type in real time. The detector evaluates the example data that's uploaded to Amazon S3. The response includes model performance scores as well as any outcomes that are associated to the matched rules. 

In the following example, the [GetEventPrediction](https://docs.aws.amazon.com//frauddetector/latest/api/API_GetEventPrediction.html) API is used to provide data from a single account registration with each request. For this tutorial, take data (email\$1address and ip\$1address) from the account registration example data file. Each line (row) after the top header line represents data from a single account registration event. 

```
import boto3
fraudDetector = boto3.client('frauddetector')

fraudDetector.get_event_prediction(
      detectorId = 'sample_detector',
      eventId = '802454d3-f7d8-482d-97e8-c4b6db9a0428',
      eventTypeName = 'sample_registration',
      eventTimestamp = '2020-07-13T23:18:21Z',
      entities = [{'entityType':'sample_customer', 'entityId':'12345'}],
 eventVariables = {
      'email_address': 'johndoe@exampledomain.com',
      'ip_address': '1.2.3.4'
}
)
```

After you completed this tutorial, you did the following:
+ Uploaded an example event dataset to Amazon S3.
+ Created variables, entities, and labels that are used to create and train a model.
+ Created and trained a model using the example dataset.
+ Viewed the model performance score and other performance metrics that Amazon Fraud Detector generated.
+ Deployed the fraud detection model.
+ Created a detector and added the deployed model.
+ Added rules, the rule execution order, and outcomes to the detector.
+ Created detector version.
+ Tested the detector by providing different inputs and checking if the rules and rule execution order worked as expected.

## (Optional) Explore the Amazon Fraud Detector APIs with a Jupyter (iPython) Notebook
<a name="gs-jupyter-notebook"></a>

For more examples for how to use the Amazon Fraud Detector APIs, see [aws-fraud-detector-samples GitHub repository](https://github.com/aws-samples/aws-fraud-detector-samples). The topics that the notebooks cover include both building models and detectors using the Amazon Fraud Detector APIs and making batch fraud prediction requests using the `GetEventPrediction` API.

# Next steps
<a name="next-steps-get-started-console"></a>

Now that you created a model and a detector, you can take a deeper dive and start to create models and detectors and generate fraud predictions.

The following sections in the Amazon Fraud Detector User Guide describe how your business or organization can use Amazon Fraud Detector to detect fraud.
+ Prepare and create your event dataset for training your model.
+ Create event type
+ Create model
+ Create detector
+ Get fraud predictions
+ Manage your Amazon Fraud Detector resources (specifically, Variables, Entities, Outcomes, and Labels) 
+ Configure Amazon Fraud Detector to meet your security and compliance objectives
+ Monitor Amazon Fraud Detector and log Amazon Fraud Detector API calls
+ Troubleshoot issues with Amazon Fraud Detector