

# Configuring a custom solution in Amazon Personalize
<a name="customizing-solution-config"></a>

After you finish importing data, you are ready to create a solution. A *solution* refers to the combination of an Amazon Personalize recipe, customized training parameters, and one or more solution versions. A *solution version* refers to a trained machine learning model.

By default, all new solutions use automatic training to create a new solution version every 7 days. Automatic training occurs only if you imported bulk or real-time interaction data since the last training. This includes item interactions or, for solutions that use the Next-Best-Action recipe, action interactions data. Automatic training continues until you delete the solution. For more information, see [Configuring automatic training](solution-config-auto-training.md). 

If you have an existing solution, you can use the Amazon Personalize console to clone the solution. When you clone a solution, you can use the configuration of the existing solution as a starting point, such as the recipe and hyperparameters, and make any changes. For more information, see [Cloning a solution (console)](cloning-solution.md). 

You can create and configure a solution by using the console, AWS Command Line Interface (AWS CLI), or AWS SDKs. After you create a solution, you can view its configuration details on the solution's details page of the Amazon Personalize console, or with the [DescribeSolution](API_DescribeSolution.md) operation.

By default, all new solutions use automatic training. With automatic training, you incur training costs while your solution is active. To avoid unnecessary costs, when you are finished you can [update the solution](updating-solution.md) to turn off automatic training. For information about training costs, see [Amazon Personalize pricing](https://aws.amazon.com/personalize/pricing/).

**Topics**
+ [Creating a solution](create-solution.md)
+ [Configuring automatic training](solution-config-auto-training.md)
+ [Configuring columns used when training](custom-config-columns.md)
+ [Optimizing a solution for an additional objective](optimizing-solution-for-objective.md)
+ [Optimizing a solution with events configuration](optimizing-solution-events-config.md)
+ [Hyperparameters and HPO](customizing-solution-config-hpo.md)
+ [Choosing the item interaction data used for training](event-values-types.md)
+ [Cloning a solution (console)](cloning-solution.md)

# Creating a solution
<a name="create-solution"></a>

You can create a custom solution with the Amazon Personalize console, AWS Command Line Interface (AWS CLI), or AWS SDKs. The following includes detailed steps to create a solution with the Amazon Personalize console and code examples that show how to create a solution with only the required fields. 

**Topics**
+ [Creating a solution (console)](#configure-solution-console)
+ [Creating a solution (AWS CLI)](#configure-solution-cli)
+ [Creating a solution (AWS SDKs)](#configure-solution-sdk)

## Creating a solution (console)
<a name="configure-solution-console"></a>

**Important**  
By default, all new solutions use automatic training. With automatic training, you incur training costs while your solution is active. To avoid unnecessary costs, when you are finished you can [update the solution](updating-solution.md) to turn off automatic training. For information about training costs, see [Amazon Personalize pricing](https://aws.amazon.com/personalize/pricing/).

 To create a solution in the console, choose your dataset group and then specify a solution name, recipe, and optional training configuration. 

**To configure a solution (console)**

1. Open the Amazon Personalize console at [https://console.aws.amazon.com/personalize/home](https://console.aws.amazon.com/personalize/home), and sign in to your account.

1. On the **Dataset groups** page, choose your dataset group.

1. On the **Overview** page, for **Step 3**, do one of the following:
   + If you created a Domain dataset group, choose **Use custom resources**, and choose **Create solutions**.
   + If you created a Custom dataset group, choose **Create solutions**. 

1. For **Solution name**, specify a name for your solution.

1. For **Solution type**, choose the type of solution that you want to create. The type you choose determines what recipes are available. 
   + Choose **Item recommendation** to get item recommendations for your users. For example, personalized movie recommendations. 
   + Choose **Action recommendation** to get action recommendations for your users. For example, generate the next best action for a user, such as download your app. 
   + Choose **User segmentation** to get user segments (groups of users) based on your item data.

1. For **Recipe**, choose a recipe (see [Choosing a recipe](working-with-predefined-recipes.md)). 

1. For **Tags**, optionally add any tags. For more information about tagging Amazon Personalize resources, see [Tagging Amazon Personalize resources](tagging-resources.md).

1. Choose **Next**.

1. On the **Training configuration** page, customize the solution to meet your business requirements. 
   + In **Automatic training**, choose whether the solution uses automatic training. If you use automatic training, you can change the `Automatic training frequency`. The default training frequency is every 7 days. 

     We recommend using automatic training. It makes it easier for you to maintain recommendation relevance. Your training frequency depends on your business requirements, the recipe that you use, and how frequently you import data. For more information, see [Configuring automatic training](solution-config-auto-training.md). For information about maintaining relevance, see [Maintaining recommendation relevance](maintaining-relevance.md).
   + In **Hyperparameter configuration**, configure any hyperparameter options based on your recipe and business needs. Different recipes use different hyperparameters. For the hyperparameters available to you, see the individual recipes in [Choosing a recipe](working-with-predefined-recipes.md). 
   + In **Columns for training**, if your recipe generates item recommendations or user segments, optionally choose the columns that Amazon Personalize considers when creating solution versions. For more information, see [Configuring columns used when training](custom-config-columns.md). 
   + In **Event configuration**, if your Item interactions dataset has EVENT\$1TYPE or both EVENT\$1TYPE and EVENT\$1VALUE columns, optionally use the **Event type** and **Event value threshold** fields to choose the item interactions data that Amazon Personalize uses when training the model. For more information, see [Choosing the item interaction data used for training](event-values-types.md). 

      If you have multiple event types and use the User-Personalization-v2 recipe or Personalized-Ranking-v2 recipe, you can also specify different weights for different types. For example, you can configure a solution to give more weight to purchase events than click events. For more information, see [Optimizing a solution with events configuration](optimizing-solution-events-config.md). 
   + If you use either the [User-Personalization recipe](native-recipe-new-item-USER_PERSONALIZATION.md) or [Personalized-Ranking recipe](native-recipe-search.md) recipe, optionally specify an **Objective** and choose an **Objective sensitivity** to optimize your solution for an objective in addition to relevance. The objective sensitivity configures how Amazon Personalize balances recommending items based on your objective compared with relevance through interactions data. For more information, see [Optimizing a solution for an additional objective](optimizing-solution-for-objective.md).

1. Choose **Next** and review the solution details. You can't change your solution's configuration after you create it.

1. Choose **Create solution**. After you create a solution, Amazon Personalize starts creating your first solution version within an hour. When training starts, you can monitor it in the **Solution versions** section on the details page for you solution. Automatically created solution versions have a **Training type** of AUTOMATIC. 

    When the solution version is ACTIVE, you are ready to use it to get recommendations. How you use an active solution version depends on how you get recommendations:
   +  For real-time recommendations, you deploy an ACTIVE solution version with an Amazon Personalize campaign. You use the campaign to get recommendations for your users. See [Deploying an Amazon Personalize solution version with a campaignCreating a campaign](campaigns.md).
   + For batch recommendations, you specify an ACTIVE solution version when you create a batch inference job or batch segment job. See [Getting batch item recommendations](getting-batch-recommendations.md) or [Getting batch user segments](getting-user-segments.md).

## Creating a solution (AWS CLI)
<a name="configure-solution-cli"></a>

**Important**  
By default, all new solutions use automatic training. With automatic training, you incur training costs while your solution is active. To avoid unnecessary costs, when you are finished you can [update the solution](updating-solution.md) to turn off automatic training. For information about training costs, see [Amazon Personalize pricing](https://aws.amazon.com/personalize/pricing/).

To create a solution with the AWS CLI, use the `create-solution` command. This command uses the [CreateSolution](API_CreateSolution.md) API operation. The following code shows you how to create a solution that uses automatic training. It automatically creates a new solution version every five days.

To use the code, update it to give the solution a name, specify the Amazon Resource Name (ARN) of your dataset group, optionally change the training frequency, and specify the ARN of the recipe to use. For information about recipes, see [Choosing a recipe](working-with-predefined-recipes.md). 

```
aws personalize create-solution \
--name solution name \
--dataset-group-arn dataset group ARN \
--recipe-arn recipe ARN \
--perform-auto-training \
--solution-config "{\"autoTrainingConfig\": {\"schedulingExpression\": \"rate(5 days)\"}}"
```
+ We recommend that you use automatic training. It makes it easier for you to maintain and improve recommendation relevance. By default, all new solutions use automatic training. The default training frequency is every 7 days. Your training frequency depends on your business requirements, the recipe that you use, and how frequently you import data. For more information, see [Configuring automatic training](solution-config-auto-training.md). 
+ Depending on your recipe, you can modify the code to configure recipe specific properties and hyperparameters (see [Hyperparameters and HPO](customizing-solution-config-hpo.md)), configure the columns used for training (see [Configuring columns used when training (AWS CLI)](custom-config-columns.md#custom-config-columns-cli)), or filter the item interactions data used for training (see [Choosing the item interaction data used for training](event-values-types.md)). 
+ If you use either the [User-Personalization recipe](native-recipe-new-item-USER_PERSONALIZATION.md) or [Personalized-Ranking recipe](native-recipe-search.md) recipe, you can optimize your solution for an objective, in addition to relevance. For more information, see [Optimizing a solution for an additional objective](optimizing-solution-for-objective.md).

After you create the solution, record the solution ARN for future use. With automatic training, solution version creation starts within one hour after the solution is ACTIVE. If you manually create a solution version within the hour, the solution skips the first automatic training. After training starts, you can get the solution version's Amazon Resource Name (ARN) with the [ListSolutionVersions](https://docs.aws.amazon.com/personalize/latest/dg/API_ListSolutionVersions.html) API operation. To get its status, use the [DescribeSolutionVersion](https://docs.aws.amazon.com/personalize/latest/dg/API_DescribeSolutionVersion.html) API operation. 

 When the solution version is ACTIVE, you are ready to use it to get recommendations. How you use an active solution version depends on how you get recommendations:
+  For real-time recommendations, you deploy an ACTIVE solution version with an Amazon Personalize campaign. You use the campaign to get recommendations for your users. See [Deploying an Amazon Personalize solution version with a campaignCreating a campaign](campaigns.md).
+ For batch recommendations, you specify an ACTIVE solution version when you create a batch inference job or batch segment job. See [Getting batch item recommendations](getting-batch-recommendations.md) or [Getting batch user segments](getting-user-segments.md).

## Creating a solution (AWS SDKs)
<a name="configure-solution-sdk"></a>

**Important**  
By default, all new solutions use automatic training. With automatic training, you incur training costs while your solution is active. To avoid unnecessary costs, when you are finished you can [update the solution](updating-solution.md) to turn off automatic training. For information about training costs, see [Amazon Personalize pricing](https://aws.amazon.com/personalize/pricing/).

To create a solution with AWS SDKs, use the [CreateSolution](API_CreateSolution.md) API operation. The following code shows you how to create a solution that uses automatic training. It automatically creates a new solution version every five days.

To use the code, update it to give the solution a name, specify the Amazon Resource Name (ARN) of your dataset group, optionally change the training frequency, and specify the ARN of the recipe that you want to use. For information about recipes, see [Choosing a recipe](working-with-predefined-recipes.md). 

------
#### [ SDK for Python (Boto3) ]

```
import boto3

personalize = boto3.client('personalize')

create_solution_response = personalize.create_solution(
  name = 'solution name',
  recipeArn = 'recipe ARN',
  datasetGroupArn = 'dataset group ARN',
  performAutoTraining = True,
  solutionConfig = {
    "autoTrainingConfig": {
      "schedulingExpression": "rate(5 days)"
    }
  }
)
solution_arn = create_solution_response['solutionArn']
print('solution_arn: ', solution_arn)
```

------
#### [ SDK for JavaScript v3 ]

```
import {
  CreateSolutionCommand,
  PersonalizeClient,
} from "@aws-sdk/client-personalize";

// create client
const personalizeClient = new PersonalizeClient({ region: "REGION" });

// set the solution parameters
export const solutionParam = {
  datasetGroupArn: "DATASET_GROUP_ARN" /* required */,
  recipeArn: "RECIPE_ARN" /* required */,
  name: "SOLUTION_NAME" /* required */,
  performAutoTraining: true /* optional, default is true */,
  solutionConfig: {
    autoTrainingConfig: {
      schedulingExpression:
        "rate(5 days)" /* optional, default is every 7 days */,
    },
  },
};

export const run = async () => {
  try {
    const response = await personalizeClient.send(
      new CreateSolutionCommand(solutionParam)
    );
    console.log("Success", response);
    return response; // For unit tests.
  } catch (err) {
    console.log("Error", err);
  }
};
run();
```

------
+ We recommend that you use automatic training. It makes it easier for you to maintain and improve recommendation relevance. By default, all new solutions use automatic training. The default training frequency is every 7 days. Your training frequency depends on your business requirements, the recipe that you use, and how frequently you import data. For more information, see [Configuring automatic training](solution-config-auto-training.md). 
+ Depending on your recipe, you can modify the code to configure recipe specific properties and hyperparameters (see [Hyperparameters and HPO](customizing-solution-config-hpo.md)), configure the columns used for training (see [Configuring columns used when training (AWS SDKs)](custom-config-columns.md#custom-configure-columns-sdk)), or filter the item interactions data used for training (see [Choosing the item interaction data used for training](event-values-types.md)). 
+ If you use either the [User-Personalization recipe](native-recipe-new-item-USER_PERSONALIZATION.md) or [Personalized-Ranking recipe](native-recipe-search.md) recipe, you can optimize your solution for an objective, in addition to relevance. For more information, see [Optimizing a solution for an additional objective](optimizing-solution-for-objective.md).

After you create the solution, record the solution ARN for future use. With automatic training, solution version creation starts within one hour after the solution is ACTIVE. If you manually create a solution version within the hour, the solution skips the first automatic training. After training starts, you can get the solution version's Amazon Resource Name (ARN) with the [ListSolutionVersions](https://docs.aws.amazon.com/personalize/latest/dg/API_ListSolutionVersions.html) API operation. To get its status, use the [DescribeSolutionVersion](https://docs.aws.amazon.com/personalize/latest/dg/API_DescribeSolutionVersion.html) API operation. 

You can use the following Python code to wait for automatic training to start. The `wait_for_training_to_start` method returns the ARN of the first solution version.

```
import time
import boto3


def wait_for_training_to_start(new_solution_arn):
    max_time = time.time() + 3 * 60 * 60    # 3 hours
    while time.time() < max_time:
        list_solution_versions_response = personalize.list_solution_versions(
            solutionArn=new_solution_arn
        )
        solution_versions = list_solution_versions_response.get('solutionVersions', [])
        if solution_versions:
            new_solution_version_arn = solution_versions[0]['solutionVersionArn']
            print(f"Solution version ARN: {new_solution_version_arn}")
            return new_solution_version_arn
        else:
            print(f"Training hasn't started yet. Training will start within the next hour.")
            time.sleep(60)


personalize = boto3.client('personalize')

solution_arn = "solution_arn"
solution_version_arn = wait_for_training_to_start(solution_arn)
```

 When the solution version is ACTIVE, you are ready to use it to get recommendations. How you use an active solution version depends on how you get recommendations:
+  For real-time recommendations, you deploy an ACTIVE solution version with an Amazon Personalize campaign. You use the campaign to get recommendations for your users. See [Deploying an Amazon Personalize solution version with a campaignCreating a campaign](campaigns.md).
+ For batch recommendations, you specify an ACTIVE solution version when you create a batch inference job or batch segment job. See [Getting batch item recommendations](getting-batch-recommendations.md) or [Getting batch user segments](getting-user-segments.md).

# Configuring automatic training
<a name="solution-config-auto-training"></a>

**Important**  
By default, all new solutions use automatic training. With automatic training, you incur training costs while your solution is active. To avoid unnecessary costs, when you are finished you can [update the solution](updating-solution.md) to turn off automatic training. For information about training costs, see [Amazon Personalize pricing](https://aws.amazon.com/personalize/pricing/).

When you create a solution, you can configure whether the solution uses automatic training. You can also configure the training frequency. For example, you can configure the solution to create a new solution version every five days.

By default, all new solutions use automatic training to create a new solution version every 7 days. Automatic training occurs only if you imported bulk or real-time interaction data since the last training. This includes item interactions or, for solutions that use the Next-Best-Action recipe, action interactions data. Automatic training continues until you delete the solution. 

We recommend that you use automatic training. It makes maintaining your solution easier. It removes the manual training required for the solution to learn from your most recent data. Without automatic training, you must manually create new solution versions for the solution to learn from your most recent data. This can result in stale recommendations and a lower conversion rate. For more information about maintaining Amazon Personalize recommendations, see [Maintaining recommendation relevance](maintaining-relevance.md). 

You can configure automatic training with the Amazon Personalize console, AWS Command Line Interface (AWS CLI), or AWS SDKs. For steps on configuring automatic training with the console, see [Creating a solution (console)](create-solution.md#configure-solution-console). 

After you create the solution, record the solution ARN for future use. With automatic training, solution version creation starts within one hour after the solution is ACTIVE. If you manually create a solution version within the hour, the solution skips the first automatic training. After training starts, you can get the solution version's Amazon Resource Name (ARN) with the [ListSolutionVersions](https://docs.aws.amazon.com/personalize/latest/dg/API_ListSolutionVersions.html) API operation. To get its status, use the [DescribeSolutionVersion](https://docs.aws.amazon.com/personalize/latest/dg/API_DescribeSolutionVersion.html) API operation. 

**Topics**
+ [Guidelines and requirements](#auto-training-guidelines)
+ [Configuring automatic training (AWS CLI)](#configure-solution-auto-training-cli)
+ [Configuring automatic training (SDKs)](#configure-solution-auto-training-sdk)

## Guidelines and requirements
<a name="auto-training-guidelines"></a>

The following are guidelines and requirements for automatic training:
+  Automatic training occurs only if you imported bulk or real-time interaction data since the last training. This includes item interactions or, for solutions that use the Next-Best-Action recipe, action interactions data. 
+ Each training considers all of the data in your dataset group that you include in training. For information about configuring the columns used in training, see [Configuring columns used when training](custom-config-columns.md).
+ You can still manually create solution versions.
+ Automatic training starts within one hour after your solution is active. If you manually create a solution version within the hour, the solution skips the first automatic training. 
+ Training scheduling is based on training start date. For example, if your first solution version starts training at 7:00 pm, and you use weekly training, the next solution version will start training a week later at 7:00 pm. 
+ For all recipes, we recommend at least a weekly training frequency. You can specify a training frequency between 1 and 30 days. The default is every 7 days. 
  +  If you use User-Personalization-v2, User-Personalization, or Next-Best-Action, the solution automatically updates to consider new items or actions for recommendations. Automatic updates aren't the same as automatic training. An automatic update doesn't create a completely new solution version, and the model doesn't learn from your most recent data. To maintain your solution, your training frequency should still be at least weekly. For more formation about automatic updates, including additional guidelines and requirements, see [Automatic updates](use-case-recipe-features.md#automatic-updates).
  + If you use Trending-Now, Amazon Personalize automatically identifies the top trending items in your interactions data over a configurable interval of time. Trending-Now can recommend items added since the last training through bulk or streaming interactions data. Your training frequency should still be at least weekly. For more information, see [Trending-Now recipe](native-recipe-trending-now.md).
  + If you don't use a recipe with automatic updates or the Trending-Now recipe, Amazon Personalize considers new items for recommendations only after the next training. For example, if you use the Similar-Items recipe and add new items daily, you would have to use a daily automatic training frequency for these items to appear in recommendations that same day.

## Configuring automatic training (AWS CLI)
<a name="configure-solution-auto-training-cli"></a>

The following code shows you how to create a solution that automatically creates a solution version every five days. To turn off automatic training, set `perform-auto-training` to `false`. 

To change the training frequency, you can modify the `schedulingExpression` in the `autoTrainingConfig`. The expression must be in `rate(value unit)` format. For the value, specify a number between 1 and 30. For the unit, specify `day` or `days`. 

For a full explanation of the `create-solution` command, see [Creating a solution (AWS CLI)](create-solution.md#configure-solution-cli).

```
aws personalize create-solution \
--name solution name \
--dataset-group-arn dataset group ARN \
--recipe-arn recipe ARN \
--perform-auto-training \
--solution-config "{\"autoTrainingConfig\": {\"schedulingExpression\": \"rate(5 days)\"}}"
```

## Configuring automatic training (SDKs)
<a name="configure-solution-auto-training-sdk"></a>

The following code shows you how to create a solution with automatic training with the AWS SDKs. The solution automatically creates a solution version every five days. To turn off automatic training, set `performAutoTraining` to `false`. 

To change the training frequency, you can modify the `schedulingExpression` in the `autoTrainingConfig`. The expression must be in `rate(value unit)` format. For the value, specify a number between 1 and 30. For the unit, specify `day` or `days`. 

For a full explanation of the CreateSolution API operation, see [Creating a solution (AWS SDKs)](create-solution.md#configure-solution-sdk).

------
#### [ SDK for Python (Boto3) ]

```
import boto3

personalize = boto3.client('personalize')

create_solution_response = personalize.create_solution(
  name = 'solution name',
  recipeArn = 'recipe ARN',
  datasetGroupArn = 'dataset group ARN',
  performAutoTraining = True,
  solutionConfig = {
    "autoTrainingConfig": {
      "schedulingExpression": "rate(5 days)"
    }
  }
)
solution_arn = create_solution_response['solutionArn']
print('solution_arn: ', solution_arn)
```

------
#### [ SDK for JavaScript v3 ]

```
import {
  CreateSolutionCommand,
  PersonalizeClient,
} from "@aws-sdk/client-personalize";

// create client
const personalizeClient = new PersonalizeClient({ region: "REGION" });

// set the solution parameters
export const solutionParam = {
  datasetGroupArn: "DATASET_GROUP_ARN" /* required */,
  recipeArn: "RECIPE_ARN" /* required */,
  name: "SOLUTION_NAME" /* required */,
  performAutoTraining: true /* optional, default is true */,
  solutionConfig: {
    autoTrainingConfig: {
      schedulingExpression:
        "rate(5 days)" /* optional, default is every 7 days */,
    },
  },
};

export const run = async () => {
  try {
    const response = await personalizeClient.send(
      new CreateSolutionCommand(solutionParam)
    );
    console.log("Success", response);
    return response; // For unit tests.
  } catch (err) {
    console.log("Error", err);
  }
};
run();
```

------

You can use the following Python code to wait for automatic training to start. The `wait_for_training_to_start` method returns the ARN of the first solution version.

```
import time
import boto3

def wait_for_training_to_start(new_solution_arn):
    max_time = time.time() + 3 * 60 * 60    # 3 hours
    while time.time() < max_time:
        list_solution_versions_response = personalize.list_solution_versions(
            solutionArn=new_solution_arn
        )
        solution_versions = list_solution_versions_response.get('solutionVersions', [])
        if solution_versions:
            new_solution_version_arn = solution_versions[0]['solutionVersionArn']
            print(f"Solution version ARN: {new_solution_version_arn}")
            return new_solution_version_arn
        else:
            print(f"Training hasn't started yet. Training will start within the next hour.")
            time.sleep(60)


personalize = boto3.client('personalize')

solution_arn = "solution_arn"
solution_version_arn = wait_for_training_to_start(solution_arn)
```

# Configuring columns used when training
<a name="custom-config-columns"></a>

**Important**  
By default, all new solutions use automatic training. With automatic training, you incur training costs while your solution is active. To avoid unnecessary costs, when you are finished you can [update the solution](updating-solution.md) to turn off automatic training. For information about training costs, see [Amazon Personalize pricing](https://aws.amazon.com/personalize/pricing/).

If your recipe generates item recommendations or user segments, you can modify the columns Amazon Personalize considers when creating a solution version (training a model). 

You can change the columns used when training to control what data Amazon Personalize uses when training a model (creating a solution version). You might do this to experiment with different combinations of training data. Or you might exclude columns without meaningful data. For example, might have a column that you want to use only to filter recommendations. You can exclude this column from training and Amazon Personalize considers it only when filtering.

You can't exclude EVENT\$1TYPE columns. By default, Amazon Personalize uses all columns that can be used when training. The following data is always excluded from training:
+ Columns with the boolean data type
+ [Impressions data](interactions-datasets.md#interactions-impressions-data)
+ Custom string fields that aren't categorical or textual

 You can't include impressions data in training, but if your use case or recipe uses it, Amazon Personalize uses impressions data to guide exploration when you get recommendations.

 If you have already created a solution and you want to modify the columns it uses when training, you can clone the solution. When you clone a solution, you can use the configuration of the existing solution as a starting point, such as the recipe and hyperparameters, and make any changes as necessary. For more information, see [Cloning a solution (console)](cloning-solution.md). 

You can configure the columns Amazon Personalize uses when training with the Amazon Personalize console, AWS Command Line Interface (AWS CLI), or AWS SDK. For information about choosing columns with the Amazon Personalize console, see the advanced configuration steps in [Creating a solution (console)](create-solution.md#configure-solution-console). After you create a solution, you can view the columns the solution uses on the solution's details page of the Amazon Personalize console, or with the [DescribeSolution](API_DescribeSolution.md) operation. 

**Topics**
+ [Configuring columns used when training (AWS CLI)](#custom-config-columns-cli)
+ [Configuring columns used when training (AWS SDKs)](#custom-configure-columns-sdk)

## Configuring columns used when training (AWS CLI)
<a name="custom-config-columns-cli"></a>

To exclude columns from training, provide the `excludedDatasetColumns` object in the `trainingDataConfig` as part of the solution configuration. For each key, provide the dataset type. For each value, provide the list of columns to exclude. The following code shows how to exclude columns from training when you create a solution with the AWS CLI. 

```
aws personalize create-solution \
--name solution name \
--dataset-group-arn dataset group ARN \
--recipe-arn recipe ARN \
--solution-config "{\"trainingDataConfig\": {\"excludedDatasetColumns\": { \"datasetType\" : [ \"column1Name\", \"column2Name\"]}}}"
```

## Configuring columns used when training (AWS SDKs)
<a name="custom-configure-columns-sdk"></a>

To exclude columns from training, provide the `excludedDatasetColumns` object in the `trainingDataConfig` as part of the solution configuration. For each key, provide the dataset type. For each value, provide the list of columns to exclude. The following code shows how to exclude columns from training when you create a solution with the SDK for Python (Boto3). 

```
import boto3

personalize = boto3.client('personalize')

create_solution_response = personalize.create_solution(
  name = 'solution name',
  recipeArn = 'recipe ARN',
  datasetGroupArn = 'dataset group ARN',
  solutionConfig = {
    "trainingDataConfig": {
      "excludedDatasetColumns": { 
          "datasetType": ["COLUMN_A", "COLUMN_B"]
      }
    }
  }
)
solution_arn = create_solution_response['solutionArn']
print('solution_arn: ', solution_arn)
```

# Optimizing a solution for an additional objective
<a name="optimizing-solution-for-objective"></a>

**Important**  
By default, all new solutions use automatic training. With automatic training, you incur training costs while your solution is active. To avoid unnecessary costs, when you are finished you can [update the solution](updating-solution.md) to turn off automatic training. For information about training costs, see [Amazon Personalize pricing](https://aws.amazon.com/personalize/pricing/).

 If you use the User-Personalization recipe or Personalized-Ranking recipe, you can optimize an Amazon Personalize solution for an objective in addition to maximum relevance, such as maximizing revenue.

 With item recommendation recipes, the primary objective of Amazon Personalize is to predict the most relevant items for your users based on historical and real-time item interactions data. These are the items your users will most likely interact with (for example, the items they will most likely click). If you have an additional objective, such as maximizing streaming minutes or increasing revenue, you can create a solution that generates recommendations based on both relevance and your objective. 

To optimize a solution for an additional objective, create a new solution with the User-Personalization recipe or Personalized-Ranking recipe and choose the numerical metadata column in your Items dataset that is related to your objective. When generating recommendations, Amazon Personalize gives more importance to items with higher values for this column of data. For example, you might choose a VIDEO\$1LENGTH column to maximize streaming minutes or a PRICE column to maximize revenue. 

You can use the Amazon Personalize console, AWS Command Line Interface (AWS CLI), or AWS SDKs. For information about using the Amazon Personalize console, see [Creating a solution (console)](create-solution.md#configure-solution-console). 

**Topics**
+ [Guidelines and requirements](#optimize-objective-guidelines-req)
+ [Balancing objective emphasis and relevance](#balancing-objective-emphasis)
+ [Measuring optimization performance](#measuring-performance)
+ [Optimizing a solution (AWS CLI)](#optimizing-solution-cli)
+ [Optimizing a solution (AWS SDKs)](#optimizing-solution-sdk)
+ [Sample Jupyter notebook](#optimization-objective-sample-notebooks)

## Guidelines and requirements
<a name="optimize-objective-guidelines-req"></a>

 Objective requirements are as follows: 
+ You can choose only one column for your objective.
+ The column must have a numerical type in your schema.
+ The column can't have a `null` type in your schema.

For more information about schemas and data types, see [Creating schema JSON files for Amazon Personalize schemas](how-it-works-dataset-schema.md).

## Balancing objective emphasis and relevance
<a name="balancing-objective-emphasis"></a>

 There can be a trade-off when recommending items based more on your objective than relevance. For example, if you want to increase revenue through recommendations, recommendations for only expensive items might make items less relevant for your users and decrease user engagement and conversion. 

To configure the balance between relevance and your objective, choose one of the following objective sensitivity levels when you create the solution: 
+ Off: Amazon Personalize uses primarily item interactions data to predict the most relevant items for your user.
+ Low: Amazon Personalize places less emphasis on your objective. Relevance through item interactions data is more important.
+ Medium: Amazon Personalize places equal emphasis on your objective and relevance through item interactions data.
+ High: Amazon Personalize places more emphasis on your objective. Relevance through item interactions data is less important.

## Measuring optimization performance
<a name="measuring-performance"></a>

When you create a solution version (train a model) for a solution with an optimization objective, Amazon Personalize generates an `average_rewards_at_k` metric. The score for `average_rewards_at_k` tells you how well the solution version performs in achieving your objective. To calculate this metric, Amazon Personalize calculates the rewards for each user as follows:

`rewards_per_user = total rewards from the user's interactions with their top 25 reward generating recommendations / total rewards from the user's interactions with recommendations`

The final `average_rewards_at_k` is the average of all `rewards_per_user` normalized to be a decimal value less than or equal to 1 and greater than 0. The closer the value is to 1, the more gains on average per user you can expect from recommendations.

For example, if your objective is to maximize revenue from clicks, Amazon Personalize calculates each user score by dividing total revenue generated by the items the user clicked from their top 25 most expensive recommendations by the revenue from all of the recommended items the user clicked. Amazon Personalize then returns a normalized average of all user scores. The closer the `average_rewards_at_k` is to 1, the more revenue on average you can expect to gain per user from recommendations.

For more information about generating metrics, see [Evaluating an Amazon Personalize solution version with metrics](working-with-training-metrics.md).

## Optimizing a solution (AWS CLI)
<a name="optimizing-solution-cli"></a>

 You can optimize for an objective only with the User-Personalization or Personalized-Ranking recipe. To optimize a solution for an additional objective using the AWS CLI, create a new solution and specify your objective details using the `optimizationObjective` key in the `solutionConfig` object. The `optimizationObjective` has the following fields: 
+ `itemAttribute`: Specify the name of the numerical metadata column from the Items dataset that relates to your objective.
+ `objectiveSensitivity`: Specify the level of emphasis that the solution places on your objective when generating recommendations. The objective sensitivity level configures how Amazon Personalize balances recommending items based on your objective versus relevance through item interaction datas data. The `objectiveSensitivity` can be `OFF`, LOW, `MEDIUM` or `HIGH`. For more information, see [Balancing objective emphasis and relevance](#balancing-objective-emphasis). 

The following is an example of the `create-solution` AWS CLI command. Replace the `solution name`, `dataset group arn`, and `recipe arn` values with your own. 

For `optimizationObjective`, replace `COLUMN_NAME` with the numerical metadata column name from the Items dataset that is related to your objective. For `objectiveSensitivity`, specify OFF, LOW, MEDIUM, or HIGH.

```
aws personalize create-solution \
--name solution name \
--dataset-group-arn dataset group arn \
--recipe-arn recipe arn \
--solution-config "{\"optimizationObjective\":{\"itemAttribute\":\"COLUMN_NAME\",\"objectiveSensitivity\":\"MEDIUM\"}}"
```

When your solution is ready, create a new solution version (for an example command see [Creating a solution (AWS CLI)](create-solution.md#configure-solution-cli)). Once you create a solution version, you can view the optimization performance with the solution version metrics. See [Measuring optimization performance](#measuring-performance).

## Optimizing a solution (AWS SDKs)
<a name="optimizing-solution-sdk"></a>

You can optimize for an objective only with the User-Personalization or Personalized-Ranking recipe. 

To optimize a solution for an additional objective using the AWS SDKs, create a new solution and specify your objective details using the `optimizationObjective` key in the `solutionConfig` object for the solution. The `optimizationObjective` has the following fields: 
+ `itemAttribute`: Specify the name of the numerical metadata column from the dataset group's Items dataset that relates to your objective.
+ `objectiveSensitivity`: Specify the level of emphasis that the solution places on your objective when generating recommendations. The objective sensitivity level configures how Amazon Personalize balances recommending items based on your objective versus relevance through item interaction datas data. The `objectiveSensitivity` can be `OFF`, `LOW`, `MEDIUM` or `HIGH`. For more information, see [Balancing objective emphasis and relevance](#balancing-objective-emphasis).

Use the following code to create a solution with an additional objective with the AWS SDK for Python (Boto3) or the AWS SDK for Java 2.x.

When your solution is ready, create a new solution version (for example code see [Creating a solution version (AWS SDKs)](creating-a-solution-version.md#create-solution-version-sdk)). Once you create a solution version, you can view the optimization performance with the solution version metrics. See [Measuring optimization performance](#measuring-performance).

------
#### [ SDK for Python (Boto3) ]

 To create a solution that is optimized for an additional objective, use the following `create_solution` method. Replace the `solution name`, `dataset group arn`, and `recipe arn` values with your own. 

For `optimizationObjective`, replace `COLUMN_NAME` with the numerical metadata column name from the Items dataset that is related to your objective. For `objectiveSensitivity`, specify OFF, LOW, MEDIUM, or HIGH.

```
import boto3

personalize = boto3.client('personalize')

create_solution_response = personalize.create_solution(
    name= 'solution name', 
    recipeArn = 'recipe arn', 
    datasetGroupArn = 'dataset group arn',
    solutionConfig = {
        "optimizationObjective": {
            "itemAttribute": "COLUMN_NAME",
            "objectiveSensitivity": "MEDIUM"
        }
    }
)
solution_arn = create_solution_response['solutionArn']
print('solution_arn: ', solution_arn)
```

------
#### [ SDK for Java 2.x ]

To create a solution that is optimized for an additional objective, use the following `createPersonalizeSolution` method and pass the following as parameters: an Amazon Personalize service client, the dataset group's Amazon Resource Name (ARN), a solution name, the recipe ARN, the item attribute, and the objective sensitivity level.

```
public static String createPersonalizeSolution(PersonalizeClient personalizeClient, 
                                             String datasetGroupArn, 
                                             String solutionName, 
                                             String recipeArn,
                                             String itemAttribute, 
                                             String objectiveSensitivity) {
    
    try {
        OptimizationObjective optimizationObjective = OptimizationObjective.builder()
            .itemAttribute(itemAttribute)
            .objectiveSensitivity(objectiveSensitivity)
            .build();
    
        SolutionConfig solutionConfig = SolutionConfig.builder()
            .optimizationObjective(optimizationObjective)
            .build();

        CreateSolutionRequest solutionRequest = CreateSolutionRequest.builder()
            .name(solutionName)
            .datasetGroupArn(datasetGroupArn)
            .recipeArn(recipeArn)
            .solutionConfig(solutionConfig)
            .build();

        CreateSolutionResponse solutionResponse = personalizeClient.createSolution(solutionRequest);
        
        return solutionResponse.solutionArn();

    } catch (PersonalizeException e) {
        System.err.println(e.awsErrorDetails().errorMessage());
        System.exit(1);
    }
    return "";
```

------
#### [ SDK for JavaScript v3 ]

```
// Get service clients and commands using ES6 syntax.
import { CreateSolutionCommand, PersonalizeClient } from
  "@aws-sdk/client-personalize";
  
// create the personalizeClient
const personalizeClient = new PersonalizeClient({ region: "REGION"});

// set the solution parameters.
export const createSolutionParam = {
  datasetGroupArn: 'DATASET_GROUP_ARN',              /* required */
  recipeArn: 'RECIPE_ARN',                           /* required */
  name: 'NAME',                                      /* required */
  solutionConfig: {
    optimizationObjective: {
      itemAttribute: "COLUMN_NAME",           /* specify the numerical column from the Items dataset related to your objective */
      objectiveSensitivity: "MEDIUM"          /* specify OFF, LOW, MEDIUM, or HIGH */
    }
  }
};

export const run = async () => {
  try {
    const response = await personalizeClient.send(new CreateSolutionCommand(createSolutionParam));
    console.log("Success", response);
    return response; // For unit tests.
  } catch (err) {
    console.log("Error", err);
  }
};
run();
```

------

## Sample Jupyter notebook
<a name="optimization-objective-sample-notebooks"></a>

For a sample Jupyter notebook that shows how to create a solution that is optimized for an additional objective based item metadata, see the [objective\$1optimization](https://github.com/aws-samples/amazon-personalize-samples/tree/master/next_steps/core_use_cases/objective_optimization) folder of the [Amazon Personalize samples](https://github.com/aws-samples/amazon-personalize-samples) GitHub repository

# Optimizing a solution with events configuration
<a name="optimizing-solution-events-config"></a>

**Important**  
By default, all new solutions use automatic training. With automatic training, you incur training costs while your solution is active. To avoid unnecessary costs, when you are finished you can [update the solution](updating-solution.md) to turn off automatic training. For information about training costs, see [Amazon Personalize pricing](https://aws.amazon.com/personalize/pricing/).

 If you use the User-Personalization-v2 recipe or Personalized-Ranking-v2 recipe, you can optimize an Amazon Personalize solution with an events configuration. 

 With item recommendation recipes, the primary objective of Amazon Personalize to predict the most relevant items for your users based on historical and real-time item interactions data. However, the interaction may carry additional information like whether a user clicked or purchase a certain item. You can record this by recording the event's type ([Event type and event value data](interactions-datasets.md#event-type-and-event-value-data)). When you configure a solution, you can have the solution give different weights to different interaction event types. For example, you can configure a solution to give more weight to `purchase` events than `click` events.

To have a solution give different weights to different event types, you specify the event types and their corresponding weights in the solution's event configuration. Additionally, you can set an event value threshold to exclude interactions with event value below that threshold. For example, if your EVENT\$1VALUE data for events with an EVENT\$1TYPE of watch is the percentage of a video that a user watched, if you set the event value threshold to 0.5, and the event type to watch, Amazon Personalize trains the model using only watch interaction events with an EVENT\$1VALUE greater than or equal to 0.5. 

 The weights associated with event types will determine their importance. An event type with higher weight will cause the trained model to more likely recommend an item that would be interacted with that event type. For example, if you specified “purchase” with a higher weight than “click” and the model learned that a user would either click item B or purchase item C with his or her interaction history, the model will rank item C higher. 

To optimize a solution with events config, you create a new solution with the User-Personalization-v2 recipe or Personalized-Ranking-v2 recipe and specify an events configuration. You can also update an existing solution ([Updating a solution to change its automatic training configuration](updating-solution.md)) with an events configuration. 

You can use the Amazon Personalize console, AWS Command Line Interface (AWS CLI), or AWS SDKs. For information about using the Amazon Personalize console, see [Creating a solution (console)](create-solution.md#configure-solution-console). 

**Topics**
+ [Guidelines and requirements](#optimize-event-config-guidelines-req)
+ [Measuring performance with event weight configuration](#optimize-event-configuration-measuring-performance)
+ [Optimizing a solution (AWS CLI)](#optimize-event-configuration-cli)
+ [Optimizing a solution (AWS SDKs)](#optimize-event-configuration-sdk)

## Guidelines and requirements
<a name="optimize-event-config-guidelines-req"></a>

 The following are guidelines and requirements for events configuration: 
+ To configure weights for different event types, your Item interactions dataset dataset must have an EVENT\$1TYPE column and optionally an EVENT\$1VALUE column.
+ You can specify a list of event parameters in the configuration. Include all event types you want to be considered for solution creation. You can specify maximum of 10 different event types.
+ You can specify event weight for each event type. Event weight must be between 0.0 and 1.0. Only the ratio of weights between event types matter. For example, setting an event type “purchase” with weight 0.3 and an event type “click” with weight 0.1 will have the same effect as setting “purchase with weight 0.6 and ”click“ with weight 0.2.
+ You can update the event configuration for an existing solution using the [UpdateSolution](https://docs.aws.amazon.com/personalize/latest/dg/API_UpdateSolution.html) API operation.

## Measuring performance with event weight configuration
<a name="optimize-event-configuration-measuring-performance"></a>

 When you create a solution version (train a model) for a solution with an events configuration, Amazon Personalize generates an `normalized_discounted_cumulative_gain_with_event_weights_at_k` metric. The score for `normalized_discounted_cumulative_gain_with_event_weights_at_k` tells you how well the solution version performs considering the events weight you set for each event types. 

 It is similar to normalized discounted cumulative gain (NDCG) at K but the reward for each correct prediction will be weighted. In contrast, in the original NDCG at K, each correct prediction will all carry a weight of 1. For example, with “purchase” of weight 0.3 and “click” of weight 0.1, correctly predicting “purchase” item will get a reward of 1.5 while predicting “click” item will get a reward of 0.5. 

For more information about generating metrics, see [Evaluating an Amazon Personalize solution version with metrics](working-with-training-metrics.md).

## Optimizing a solution (AWS CLI)
<a name="optimize-event-configuration-cli"></a>

You can optimize with events configuration with the User-Personalization-v2 or Personalized-Ranking-v2 recipe.

 To optimize a solution with events configuration using the AWS CLI, create a new solution and specify your events configuration details using the `eventsConfig` key in the `solutionConfig` object. The `eventsConfig` has a key of `eventParametersList` under which you can specify up to 10 eventParameters. Each `eventParameter` has the following fields:
+ eventType: specify the event type you want to be considered for solution creation.
+ eventValueThreshold: specify the event value threshold. Only events with event value greater or equal to this threshold will be considered for solution creation.
+ weight: specify the weight for each event type. A higher weight means higher importance of the event type for the created solution.

The following is an example of the create-solution AWS CLI command. Replace the `solution name`, `dataset group arn`, and `recipe arn` values with your own. 

```
aws personalize create-solution \
--name solution name \
--dataset-group-arn dataset group arn \
--recipe-arn recipe arn \
--solution-config "{\"eventsConfig\":{\"eventParametersList\":[{\"eventType\":\"Purchase\", \"eventValueThreshold\":0.1, \"weight\":0.3}, {\"eventType\":\"Click\", \"weight\":0.1}]}"
```

When your solution is ready, create a new solution version (for an example command see [Creating a solution (AWS CLI)](create-solution.md#configure-solution-cli)). Once you create a solution version, you can view the optimization performance with the solution version metrics. See [Measuring optimization performance](optimizing-solution-for-objective.md#measuring-performance).

## Optimizing a solution (AWS SDKs)
<a name="optimize-event-configuration-sdk"></a>

You can optimize with events configuration with the User-Personalization-v2 or Personalized-Ranking-v2 recipe.

 To optimize a solution with events configuration using the AWS SDKs, create a new solution and specify your events configuration details using the `eventsConfig` key in the `solutionConfig` object. The `eventsConfig` has a key of `eventParametersList` under which you can specify up to 10 `eventParameters`. Each `eventParameter` has the following fields:
+ eventType: specify the event type you want to be considered for solution creation.
+ eventValueThreshold: specify the event value threshold. Only events with event value greater or equal to this threshold will be considered for solution creation.
+ weight: specify the weight for each event type. A higher weight means higher importance of the event type for the created solution.

------
#### [ SDK for Python (Boto3) ]

```
import boto3

personalize = boto3.client('personalize')

create_solution_response = personalize.create_solution(
    name= 'solution name', 
    recipeArn = 'recipe arn', 
    datasetGroupArn = 'dataset group arn',
    solutionConfig = {
       "eventsConfig": {
          "eventParametersList": [
             {"eventType":"Purchase", 
              "eventValueThreshold":0.1, 
              "weight":0.3}, 
             {"eventType":"Click", 
              "weight":0.1}
          ]
       }
    }
)
solution_arn = create_solution_response['solutionArn']
print('solution_arn: ', solution_arn)
```

------
#### [ SDK for Java 2.x ]

```
public static String createPersonalizeSolution(PersonalizeClient personalizeClient, 
							  String datasetGroupArn, 
							  String solutionName, 
							  String recipeArn,
							  ) {
    
try {
    EventsConfig eventsConfig = EventsConfig.builder()
        .eventsParameterList(eventsParameterList)
        .build();

    SolutionConfig solutionConfig = SolutionConfig.builder()
        .eventsConfig(eventsConfig)
        .build();

    CreateSolutionRequest solutionRequest = CreateSolutionRequest.builder()
        .name(solutionName)
        .datasetGroupArn(datasetGroupArn)
        .recipeArn(recipeArn)
        .solutionConfig(solutionConfig)
        .build();

    CreateSolutionResponse solutionResponse = personalizeClient.createSolution(solutionRequest);
    
    return solutionResponse.solutionArn();

} catch (PersonalizeException e) {
    System.err.println(e.awsErrorDetails().errorMessage());
    System.exit(1);
}
return "";
```

------

When your solution is ready, create a new solution version (for an example command see [Creating a solution (AWS SDKs)](create-solution.md#configure-solution-sdk)). Once you create a solution version, you can view the optimization performance with the solution version metrics. See [Measuring optimization performance](optimizing-solution-for-objective.md#measuring-performance).

# Hyperparameters and HPO
<a name="customizing-solution-config-hpo"></a>

**Important**  
By default, all new solutions use automatic training. With automatic training, you incur training costs while your solution is active. To avoid unnecessary costs, when you are finished you can [update the solution](updating-solution.md) to turn off automatic training. For information about training costs, see [Amazon Personalize pricing](https://aws.amazon.com/personalize/pricing/).

You specify hyperparameters before training to optimize the trained model for your particular use case. This contrasts with model parameters whose values are determined during the training process.

Hyperparameters are specified using the `algorithmHyperParameters` key that is part of the [SolutionConfig](API_SolutionConfig.md) object that is passed to the [CreateSolution](API_CreateSolution.md) operation.

A condensed version of the `CreateSolution` request is below. The example includes the `solutionConfig` object. You use `solutionConfig` to override the default parameters of a recipe. 

```
{
  "name": "string",
  "recipeArn": "string",
  "eventType": "string",
  "solutionConfig": {
      "optimizationObjective": {
          "itemAttribute": "string",
          "objectiveSensitivity": "string"
      },
      "eventValueThreshold": "string",
      "featureTransformationParameters": {
          "string" : "string"
      },
      "algorithmHyperParameters": {
          "string" : "string"
      },
      "hpoConfig": {
          "algorithmHyperParameterRanges": {
              ...
          },
          "hpoResourceConfig": {
              "maxNumberOfTrainingJobs": "string",
              "maxParallelTrainingJobs": "string"
          }
      },
  },
}
```

Different recipes use different hyperparameters. For the available hyperparameters, see the individual recipes in [Choosing a recipe](working-with-predefined-recipes.md).

## Enabling hyperparameter optimization
<a name="hpo-tuning"></a>

Hyperparameter optimization (HPO), or tuning, is the task of choosing optimal hyperparameters for a specific learning objective. The optimal hyperparameters are determined by running many training jobs using different values from the specified ranges of possibilities. 

With [User-Personalization-v2](native-recipe-user-personalization-v2.md) and [Personalized-Ranking-v2](native-recipe-personalized-ranking-v2.md), if you turn on automatic training, Amazon Personalize automatically performs HPO every 90 days. Without automatic training, no HPO occurs. For all other recipes, you must enable HPO. To use HPO, set `performHPO` to `true`, and include the `hpoConfig` object.

Hyperparameters can be categorical, continuous, or integer-valued. The `hpoConfig` object has keys that correspond to each of these types, where you specify the hyperparameters and their ranges. You must provide each type in your request, but if a recipe doesn't have a parameter of a type, you can leave it empty. For example, User-Personalization does not have a tunable hyperparameter of continuous type. So for the `continousHyperParameterRange`, you would pass an empty array. 

The following code shows how to create a solution with HPO enabled using the SDK for Python (Boto3). The solution in the example uses the [User-Personalization recipe](native-recipe-new-item-USER_PERSONALIZATION.md) recipe and has HPO set to `true`. The code provides a value for `hidden_dimension` and the `categoricalHyperParameterRanges` and `integerHyperParameterRanges`. The `continousHyperParameterRange` is empty and the `hpoResourceConfig` sets the `maxNumberOfTrainingJobs` and `maxParallelTrainingJobs`. 

```
import boto3

personalize = boto3.client('personalize')

create_solution_response = personalize.create_solution(
    name = "solution name",
    datasetGroupArn = 'arn:aws:personalize:region:accountId:dataset-group/datasetGroupName',
    recipeArn = 'arn:aws:personalize:::recipe/aws-user-personalization',
    performHPO = True,
    solutionConfig = {
        "algorithmHyperParameters": {
          "hidden_dimension": "55"
        },
        "hpoConfig": {
          "algorithmHyperParameterRanges": {
              "categoricalHyperParameterRanges": [
                  {
                      "name": "recency_mask",
                      "values": [ "true", "false"]
                  }
              ],
              "integerHyperParameterRanges": [
                  {
                      "name": "bptt",
                      "minValue": 2,
                      "maxValue": 22
                  }
              ],
              "continuousHyperParameterRanges": [

              ]
          },
          "hpoResourceConfig": {
              "maxNumberOfTrainingJobs": "4",
              "maxParallelTrainingJobs": "2"
          }
        }
    }
)
```

For more information about HPO, see [Automatic model tuning](https://docs.aws.amazon.com/sagemaker/latest/dg/automatic-model-tuning.html). 

## Viewing hyperparameters
<a name="viewing-hyperparameters"></a>

You can view the hyperparameters of the solution by calling the [DescribeSolution](API_DescribeSolution.md) operation. The following sample shows a `DescribeSolution` output. After creating a solution version (training a model), you can also view hyperparameters with the [DescribeSolutionVersion](API_DescribeSolutionVersion.md) operation.

```
{
  "solution": {
    "name": "hpo_coonfig_solution",
    "solutionArn": "arn:aws:personalize:region:accountId:solution/solutionName",
    "performHPO": true,
    "performAutoML": false,
    "recipeArn": "arn:aws:personalize:::recipe/aws-user-personalization",
    "datasetGroupArn": "arn:aws:personalize:region:accountId:dataset-group/datasetGroupName",
    "eventType": "click",
    "solutionConfig": {
      "hpoConfig": {
        "hpoResourceConfig": {
          "maxNumberOfTrainingJobs": "4",
          "maxParallelTrainingJobs": "2"
        },
        "algorithmHyperParameterRanges": {
          "integerHyperParameterRanges": [
            {
              "name": "training.bptt",
              "minValue": 2,
              "maxValue": 22
            }
          ],
          "continuousHyperParameterRanges": [],
          "categoricalHyperParameterRanges": [
            {
              "name": "data.recency_mask",
              "values": [
                "true",
                "false"
              ]
            }
          ]
        }
      },
      "algorithmHyperParameters": {
        "hidden_dimension": "55"
      }
    },
    "status": "ACTIVE",
    "creationDateTime": "2022-07-08T12:12:48.565000-07:00",
    "lastUpdatedDateTime": "2022-07-08T12:12:48.565000-07:00"
  }
}
```

# Choosing the item interaction data used for training
<a name="event-values-types"></a>

**Important**  
By default, all new solutions use automatic training. With automatic training, you incur training costs while your solution is active. To avoid unnecessary costs, when you are finished you can [update the solution](updating-solution.md) to turn off automatic training. For information about training costs, see [Amazon Personalize pricing](https://aws.amazon.com/personalize/pricing/).

You can choose the events in an Item interactions dataset that Amazon Personalize uses when creating a solution version (training a model). Choosing item interaction data before training allows you to use only a relevant subset of your data for training or remove noise to train a more optimized model. For more information about Item interactions datasets, see [Item interaction data](interactions-datasets.md).

**Note**  
If you use User-Personalization-v2 or Personalized-Ranking-v2, your training cost is based on your item interactions data before filtering by event type or value. For more information about pricing, see [Amazon Personalize pricing](https://aws.amazon.com/personalize/pricing/). 

You can choose item interaction data as follows:
+ **Choose records based on type** – When you configure a solution, if your Item interactions dataset includes event types in an EVENT\$1TYPE column, you can optionally specify an event type to use in training. For example, if your Item interactions dataset includes *purchase*, *click*, and *watch* event types, and you want Amazon Personalize to train the model with only *watch* events, when you configure your solution, you would provide *watch* as the `event type` that Amazon Personalize uses in training. 

  If you have multiple event types and use the User-Personalization-v2 recipe or Personalized-Ranking-v2 recipe, when you configure a custom solution you can specify different weights for different types. For example, you can configure a solution to give more weight to purchase events than click events. For more information, see [Optimizing a solution with events configuration](optimizing-solution-events-config.md).

   If your Item interactions dataset has multiple event types in an EVENT\$1TYPE column, and you do not provide an event type when you configure your solution, Amazon Personalize uses all item interaction data for training with equal weight regardless of type. 
+ **Choose records based on type and value ** – When you configure a solution, if your Item interactions dataset includes EVENT\$1TYPE and EVENT\$1VALUE fields, you can set a specific value as a threshold to exclude records from training. For example, if your EVENT\$1VALUE data for events with an EVENT\$1TYPE of *watch* is the percentage of a video that a user watched, if you set the event value threshold to 0.5, and the event type to *watch*, Amazon Personalize trains the model using only *watch* interaction events with an EVENT\$1VALUE greater than or equal to 0.5. 

The following code shows how to use the SDK for Python (Boto3) to create a solution that uses only `watch` events where the use watched more than half of the video.

```
import boto3

personalize = boto3.client('personalize')

create_solution_response = personalize.create_solution(
    name = 'solution name',
    datasetGroupArn = 'arn:aws:personalize:region:accountId:dataset-group/datasetGroupName',
    recipeArn = 'arn:aws:personalize:::recipe/aws-user-personalization-v2',
    eventType = 'watch',
    solutionConfig = {
        "eventValueThreshold": "0.5"
    }
)

# Store the solution ARN
solution_arn = create_solution_response['solutionArn']

# Use the solution ARN to get the solution status
solution_description = personalize.describe_solution(solutionArn = solution_arn)['solution']
print('Solution status: ' + solution_description['status'])
```

# Cloning a solution (console)
<a name="cloning-solution"></a>

 When you create a new solution, you can use the Amazon Personalize console to clone a solution. When you clone a solution, you can use the configuration of the existing solution as a starting point, such as the recipe and hyperparameters, and make any changes as necessary. This is useful if you want to make one change to a solution, but leave all other properties unchanged. For example, adding a new column of training data to your dataset. In this case, you would clone a solution, give the solution a name, change the columns used when training, and leave all other properties unchanged. 

## Cloning a solution
<a name="cloning-solution-console"></a>

To clone a solution, you choose the existing solution, and choose the **Clone solution** option. Then give the new solution a name, and modify the relevant fields. 

**To clone a solution**

1. Open the Amazon Personalize console at [https://console.aws.amazon.com/personalize/home](https://console.aws.amazon.com/personalize/home) and sign in to your account.

1.  On the **Dataset groups** page, choose your dataset group. 

1.  Choose **Custom resources** and choose **Solutions**. 

1.  Choose the solution that you want to clone. 

1. Choose **Actions**, and choose **Clone solution**.

1. Give the new solution a name.

1. Make any changes to the solution details and advanced configuration. Amazon Personalize pre-populates these fields with values from the existing solution. For information about each field, see [Configuring a custom solution in Amazon Personalize](customizing-solution-config.md).