

本文為英文版的機器翻譯版本，如內容有任何歧義或不一致之處，概以英文版為準。

# 利用功能儲存範例筆記本偵測詐騙
<a name="feature-store-fraud-detection-notebook"></a>

**重要**  
允許 Amazon SageMaker Studio 或 Amazon SageMaker Studio Classic 建立 Amazon SageMaker 資源的自訂 IAM 政策也必須授與許可，才能將標籤新增至這些資源。需要將標籤新增至資源的許可，因為 Studio 和 Studio Classic 會自動標記它們建立的任何資源。如果 IAM 政策允許 Studio 和 Studio Classic 建立資源，但不允許標記，則在嘗試建立資源時可能會發生 "AccessDenied" 錯誤。如需詳細資訊，請參閱[提供標記 SageMaker AI 資源的許可](security_iam_id-based-policy-examples.md#grant-tagging-permissions)。  
提供許可來建立 SageMaker 資源的 [AWS Amazon SageMaker AI 的 受管政策](security-iam-awsmanpol.md) 已包含建立這些資源時新增標籤的許可。

此頁面上的範例程式碼是指範例筆記本：[使用 Amazon SageMaker Feature Store 進行詐騙偵測](https://sagemaker-examples.readthedocs.io/en/latest/sagemaker-featurestore/sagemaker_featurestore_fraud_detection_python_sdk.html)。建議您在 Studio Classic、筆記本執行個體或 JupyterLab 中執行此筆記本，因為本指南中的程式碼是概念性的，而且若複製，無法完全運作。

使用下列項目複製 [aws/amazon-sagemaker-examples](https://github.com/aws/amazon-sagemaker-examples) GitHub 儲存庫，其中包含範例筆記本。
+ **針對 Studio Classic**

  首先啟動 Studio Classic。如果 Studio 或 Studio Classic 已啟用做為您的預設體驗，則您可以開啟 Studio Classic。若要開啟 Studio Classic，請參閱[使用 Amazon SageMaker AI 主控台啟動 Amazon SageMaker Studio Classic](studio-launch.md#studio-launch-console)。

  遵循 [複製 Amazon SageMaker Studio Classic 中的 Git 儲存庫](studio-tasks-git.md) 中的步驟，將 [aws/amazon-sagemaker-examples](https://github.com/aws/amazon-sagemaker-examples) GitHub 儲存庫複製到 Studio Classic。
+ **針對 Amazon SageMaker 筆記本執行個體**

  首先遵循[存取筆記本執行個體](howitworks-access-ws.md)中的指示啟動 SageMaker 筆記本執行個體。

  然後，遵循[將 Git 儲存庫新增至您的 Amazon SageMaker AI 帳戶](nbi-git-resource.md)中的指示。

現在您有 SageMaker AI 範例筆記本，請導覽至 `amazon-sagemaker-examples/sagemaker-featurestore` 目錄並開啟[使用 Amazon SageMaker Feature Store 進行詐騙偵測](https://sagemaker-examples.readthedocs.io/en/latest/sagemaker-featurestore/sagemaker_featurestore_fraud_detection_python_sdk.html)範例筆記本。

## 步驟 1：設定您的 Feature Store 工作階段
<a name="feature-store-setup"></a>

若要開始使用 Feature Store，請建立 SageMaker AI 工作階段、Boto3 工作階段和 Feature Store 工作階段。此外，請設定要用於您的功能的 Amazon S3 儲存貯體。這是您的離線儲存。下列程式碼會使用 SageMaker AI 預設儲存貯體，並將自訂字首新增至其中。

**注意**  
您用來執行筆記本的角色必須附加下列受管的政策：`AmazonSageMakerFullAccess` 和 `AmazonSageMakerFeatureStoreAccess`。如需將政策新增至 IAM 角色的相關資訊，請參閱 [將政策新增至您的 IAM 角色](feature-store-adding-policies.md)。

```
import boto3
import sagemaker
from sagemaker.session import Session

sagemaker_session = sagemaker.Session()
region = sagemaker_session.boto_region_name
boto_session = boto3.Session(region_name=region)
role = sagemaker.get_execution_role()
default_bucket = sagemaker_session.default_bucket()
prefix = 'sagemaker-featurestore'
offline_feature_store_bucket = 's3://{}/{}'.format(default_bucket, prefix)

sagemaker_client = boto_session.client(service_name='sagemaker', region_name=region)
featurestore_runtime = boto_session.client(service_name='sagemaker-featurestore-runtime', region_name=region)

feature_store_session = Session(
    boto_session=boto_session,
    sagemaker_client=sagemaker_client,
    sagemaker_featurestore_runtime_client=featurestore_runtime
)
```

## 步驟 2：將資料集和分割資料載入功能群組
<a name="feature-store-load-datasets"></a>

將資料載入每個功能的資料框中。您可以在設置功能群組後使用這些資料框。在詐騙偵測範例中，您可以在下列程式碼中看到這些步驟。

```
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import io

s3_client = boto3.client(service_name='s3', region_name=region)

fraud_detection_bucket_name = 'sagemaker-featurestore-fraud-detection'
identity_file_key = 'sampled_identity.csv'
transaction_file_key = 'sampled_transactions.csv'

identity_data_object = s3_client.get_object(Bucket=fraud_detection_bucket_name, Key=identity_file_key)
transaction_data_object = s3_client.get_object(Bucket=fraud_detection_bucket_name, Key=transaction_file_key)

identity_data = pd.read_csv(io.BytesIO(identity_data_object['Body'].read()))
transaction_data = pd.read_csv(io.BytesIO(transaction_data_object['Body'].read()))

identity_data = identity_data.round(5)
transaction_data = transaction_data.round(5)

identity_data = identity_data.fillna(0)
transaction_data = transaction_data.fillna(0)

# Feature transformations for this dataset are applied before ingestion into FeatureStore.
# One hot encode card4, card6
encoded_card_bank = pd.get_dummies(transaction_data['card4'], prefix = 'card_bank')
encoded_card_type = pd.get_dummies(transaction_data['card6'], prefix = 'card_type')

transformed_transaction_data = pd.concat([transaction_data, encoded_card_type, encoded_card_bank], axis=1)
transformed_transaction_data = transformed_transaction_data.rename(columns={"card_bank_american express": "card_bank_american_express"})
```

## 步驟 3：設定功能群組
<a name="feature-store-set-up-feature-groups-fraud-detection"></a>

設置特徵群組時，需要使用唯一名稱自訂功能名稱，並使用 `FeatureGroup` 類別設置每個功能群組。

```
from sagemaker.feature_store.feature_group import FeatureGroup
feature_group_name = "some string for a name"
feature_group = FeatureGroup(name=feature_group_name, sagemaker_session=feature_store_session)
```

例如，在詐騙偵測範例中，這兩個特徵群組為 `identity` 和 `transaction`。在下面的代碼中，您可以看到如何使用時間戳自訂名稱，然後通過傳遞名稱和會話來設置每個組。

```
import time
from time import gmtime, strftime, sleep
from sagemaker.feature_store.feature_group import FeatureGroup

identity_feature_group_name = 'identity-feature-group-' + strftime('%d-%H-%M-%S', gmtime())
transaction_feature_group_name = 'transaction-feature-group-' + strftime('%d-%H-%M-%S', gmtime())

identity_feature_group = FeatureGroup(name=identity_feature_group_name, sagemaker_session=feature_store_session)
transaction_feature_group = FeatureGroup(name=transaction_feature_group_name, sagemaker_session=feature_store_session)
```

## 步驟 4：設定記錄識別碼和事件時間功能
<a name="feature-store-set-up-record-identifier-event-time"></a>

在此步驟中，您可以指定記錄識別碼名稱和事件時間功能名稱。此名稱對映至資料中相應功能的欄。例如，在詐騙偵測範例中，感興趣的欄為 `TransactionID`。當無時間戳記可用時，`EventTime` 可以附加至您的資料。在下面的代碼中，您可以看到這些變量是如何設置的，然後 `EventTime` 附加到這兩個功能的資料。

```
record_identifier_name = "TransactionID"
event_time_feature_name = "EventTime"
current_time_sec = int(round(time.time()))
identity_data[event_time_feature_name] = pd.Series([current_time_sec]*len(identity_data), dtype="float64")
transformed_transaction_data[event_time_feature_name] = pd.Series([current_time_sec]*len(transaction_data), dtype="float64")
```

## 步驟 5：載入功能定義
<a name="feature-store-load-feature-definitions"></a>

現在，您可以透過傳遞包含功能資料的資料框來載入功能定義。在下面的詐騙偵測範例代碼中，身分功能和交易功能是通過使用 `load_feature_definitions` 加載的，並且此功能自動偵測每列資料的資料類型。對於使用模式而不是自動偵測的開發人員，請參閱[從 Data Wrangler 匯出特徵群組](https://docs.aws.amazon.com/sagemaker/latest/dg/data-wrangler-data-export.html#data-wrangler-data-export-feature-store)範例，該代碼顯示如何加載模式、映射模式並將其新增為 `FeatureDefinition`，您可以使用它來建立 `FeatureGroup`。此範例也涵蓋了您可以用來取代 SageMaker Python SDK 的 適用於 Python (Boto3) 的 AWS SDK 實作。

```
identity_feature_group.load_feature_definitions(data_frame=identity_data); # output is suppressed
transaction_feature_group.load_feature_definitions(data_frame=transformed_transaction_data); # output is suppressed
```

## 步驟 6：建立功能群組
<a name="feature-store-setup-create-feature-group"></a>

在此步驟中，您使用 `create` 函式來建立特徵群組。下列程式碼範例顯示可用的參數。根據預設不會建立線上儲存，因此您必須將其設定為 `True`，如果您打算啟用它。`s3_uri` 是您離線儲存的 S3 儲存貯體位置。

```
# create a FeatureGroup
feature_group.create(
    description = "Some info about the feature group",
    feature_group_name = feature_group_name,
    record_identifier_name = record_identifier_name,
    event_time_feature_name = event_time_feature_name,
    feature_definitions = feature_definitions,
    role_arn = role,
    s3_uri = offline_feature_store_bucket,
    enable_online_store = True,
    online_store_kms_key_id = None,
    offline_store_kms_key_id = None,
    disable_glue_table_creation = False,
    data_catalog_config = None,
    tags = ["tag1","tag2"])
```

以下來自詐騙偵測範例的代碼顯示了對正在建立的兩個特徵群組中的每個群組的最小 `create` 呼叫。

```
identity_feature_group.create(
    s3_uri=offline_feature_store_bucket,
    record_identifier_name=record_identifier_name,
    event_time_feature_name=event_time_feature_name,
    role_arn=role,
    enable_online_store=True
)

transaction_feature_group.create(
    s3_uri=offline_feature_store_bucket,
    record_identifier_name=record_identifier_name,
    event_time_feature_name=event_time_feature_name,
    role_arn=role,
    enable_online_store=True
)
```

建立功能群組時，載入資料需要一些時間，並且需要等到建立功能群組後才能使用它。您可以使用下列方法來檢視和使用狀態檢查。

```
status = feature_group.describe().get("FeatureGroupStatus")
```

建立特徵群組時，您會收到 `Creating` 作為回應。當此步驟成功完成時，回應為 `Created`。其他可能的狀態為 `CreateFailed`、`Deleting`、或 `DeleteFailed`。

## 步驟 7：使用功能群組
<a name="feature-store-working-with-feature-groups"></a>

現在您已設定功能群組，您可以執行下列任何任務：

**Topics**
+ [描述功能群組](#feature-store-describe-feature-groups)
+ [列出特徵群組](#feature-store-list-feature-groups)
+ [將記錄放置到特徵群組中](#feature-store-put-records-feature-group)
+ [從特徵群組取得記錄](#feature-store-get-records-feature-group)
+ [生成配置單元 DDL 命令](#feature-store-generate-hive-ddl-commands-feature-group)
+ [建立訓練資料集](#feature-store-build-training-dataset)
+ [撰寫並執行 Athena 查詢](#feature-store-write-athena-query)
+ [刪除功能群組](#feature-store-delete-feature-group)

### 描述功能群組
<a name="feature-store-describe-feature-groups"></a>

您可以使用 `describe` 函式擷取關於特徵群組的資訊。

```
feature_group.describe()
```

### 列出特徵群組
<a name="feature-store-list-feature-groups"></a>

您可以使用此 `list_feature_groups` 函式列出所有特徵群組。

```
sagemaker_client.list_feature_groups()
```

### 將記錄放置到特徵群組中
<a name="feature-store-put-records-feature-group"></a>

您可以使用 `ingest` 函式載入功能資料。您可以傳入功能資料的資料框、設定工作者的數目，然後選擇等待其返回與否。以下範例示範的是使用 `ingest` 函式。

```
feature_group.ingest(
    data_frame=feature_data, max_workers=3, wait=True
)
```

對於您擁有的每個特徵群組，對要載入的功能資料執行 `ingest` 函式。

### 從特徵群組取得記錄
<a name="feature-store-get-records-feature-group"></a>

您可以使用 `get_record` 函式，透過其記錄識別碼擷取特定功能的資料。下列範例會使用範例識別碼來擷取記錄。

```
record_identifier_value = str(2990130)
featurestore_runtime.get_record(FeatureGroupName=transaction_feature_group_name, RecordIdentifierValueAsString=record_identifier_value)
```

詐騙偵測範例的範例回應：

```
...
'Record': [{'FeatureName': 'TransactionID', 'ValueAsString': '2990130'},
  {'FeatureName': 'isFraud', 'ValueAsString': '0'},
  {'FeatureName': 'TransactionDT', 'ValueAsString': '152647'},
  {'FeatureName': 'TransactionAmt', 'ValueAsString': '75.0'},
  {'FeatureName': 'ProductCD', 'ValueAsString': 'H'},
  {'FeatureName': 'card1', 'ValueAsString': '4577'},
...
```

### 生成配置單元 DDL 命令
<a name="feature-store-generate-hive-ddl-commands-feature-group"></a>

此外，SageMaker Python SDK 的 `FeatureStore` 類別也提供了產生蜂巢 DDL 命令的功能。表格的結構描述是根據功能定義產生的。欄以功能名稱命名，並根據功能類型推斷資料類型。

```
print(feature_group.as_hive_ddl())
```

輸出範例：

```
CREATE EXTERNAL TABLE IF NOT EXISTS sagemaker_featurestore.identity-feature-group-27-19-33-00 (
  TransactionID INT
  id_01 FLOAT
  id_02 FLOAT
  id_03 FLOAT
  id_04 FLOAT
 ...
```

### 建立訓練資料集
<a name="feature-store-build-training-dataset"></a>

功能存放區會在您建立功能群組時自動建置 AWS Glue 資料目錄，而且您可以視需要將其關閉。以下說明如何使用本主題先前建立的身分識別和交易功能群組的功能值來建立單一訓練資料集。此外，以下內容說明如何執行 Amazon Athena 查詢，從身分和交易功能群組加入存放在離線存放區中的資料。

若要開始，首先建立 Athena 查詢，並使用 `athena_query()` 提供給身分識別和交易特徵群組。`table\$1name` 是由特徵商店自動產生的 AWS Glue 資料表。

```
identity_query = identity_feature_group.athena_query()
transaction_query = transaction_feature_group.athena_query()

identity_table = identity_query.table_name
transaction_table = transaction_query.table_name
```

### 撰寫並執行 Athena 查詢
<a name="feature-store-write-athena-query"></a>

您可以在這些特徵群組上使用 SQL 撰寫查詢，然後使用 `.run()` 命令執行查詢，並為要儲存在該處的資料集指定 Amazon S3 儲存貯體位置。

```
# Athena query
query_string = 'SELECT * FROM "'+transaction_table+'" LEFT JOIN "'+identity_table+'" ON "'+transaction_table+'".transactionid = "'+identity_table+'".transactionid'

# run Athena query. The output is loaded to a Pandas dataframe.
dataset = pd.DataFrame()
identity_query.run(query_string=query_string, output_location='s3://'+default_s3_bucket_name+'/query_results/')
identity_query.wait()
dataset = identity_query.as_dataframe()
```

從這裡，您可以使用此資料集訓練模型，然後執行推論。

### 刪除功能群組
<a name="feature-store-delete-feature-group"></a>

您可以使用該 `delete` 功能刪除特徵群組。

```
feature_group.delete()
```

下列程式碼範例來自詐騙偵測範例。

```
identity_feature_group.delete()
transaction_feature_group.delete()
```

如需詳細資訊，請參閱[刪除特徵群組 API](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_DeleteFeatureGroup.html)