

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

# 用於圖形上機器學習的 Amazon Neptune ML
<a name="machine-learning"></a>

在大型連線的資料集中通常會有珍貴的資訊，但很難僅根據人類的直覺使用查詢來擷取這些資訊。機器學習 (ML) 技術可以協助在具有數十億個關係的圖形中找出隱藏的關聯性。這些關聯性可能有助於推薦產品、預測信用度，識別詐欺等等。

Neptune ML 功能可讓您在數小時而不是數週的時間內，在大型圖形上建置並訓練有用的機器學習模型。為了達成此目的，Neptune ML 使用採用 [Amazon SageMaker AI ](https://aws.amazon.com/sagemaker/)和 [Deep Graph Library (DGL) （開放原始碼） 技術的圖形神經網路 (](https://www.dgl.ai/)GNN) 技術。 [https://github.com/dmlc/dgl/](https://github.com/dmlc/dgl/)圖形神經網路是人工智慧的新興領域 (例如，請參閱[圖形神經網路的全面調查](https://arxiv.org/abs/1901.00596))。如需有關使用 GNN 搭配 DGL 的實作教學課程，請參閱[使用 Deep Graph Library 學習圖形神經網路](https://www.amazon.science/videos-webinars/learning-graph-neural-networks-with-deep-graph-library)。

**注意**  
圖形頂點會在 Neptune ML 模型識別為「節點」。例如，頂點分類會使用節點分類機器學習模型，而頂點迴歸則會使用節點迴歸模型。

## Neptune ML 可以做什麼
<a name="machine-learning-capabilities"></a>

Neptune 同時支援直推式推論 (根據當時的圖形資料傳回訓練時預先計算的預測) 和直推式推論 (根據目前的資料，即時套用資料處理和模型評估)。請參閱 [歸納推論與直推式推論之間的區別](machine-learning-overview-evolving-data.md#inductive-vs-transductive-inference)。

Neptune ML 可以訓練機器學習模型，以支援五種不同類別的推論：

**Neptune ML 目前支援的推論任務類型**
+ **節點分類** – 預測頂點屬性的類別特徵。

  例如, 鑑於電影 *The Shawshank Redemption*，Neptune ML 可以從 `[story, crime, action, fantasy, drama, family, ...]` 的候選集將其 `genre` 屬性預測為 `story`。

  有兩種類型的節點分類任務：
  + **單一類別分類**：在這種任務中，每個節點只有一個目標特徵。例如，`Alan Turing` 的屬性 `Place_of_birth` 具有值 `UK`。
  + **多類別分類**：在這種任務中，每個節點可有多個目標特徵。例如，影片 *The Godfather* 的屬性 `genre` 具有值 `crime` 和 `story`。
+ **節點迴歸** – 預測頂點的數值屬性。

  例如，鑑於電影 *Avengers: Endgame*，Neptune ML 可以預測其屬性 `popularity` 具有 `5.0` 一值。
+ **邊緣分類** – 預測邊緣屬性的類別特徵。

  有兩種類型的邊緣分類任務：
  + **單一類別分類**：在這種任務中，每個邊緣只有一個目標特徵。例如，使用者與電影之間的評分邊緣可能具有屬性 `liked`，其值為「Yes」或「No」。
  + **多類別分類**：在這種任務中，每個邊緣可有多個目標特徵。例如，使用者與電影之間的評分可能會對「Funny」、「Heartwarming」、「Chilling」等屬性標籤具有多個值。
+ **邊緣迴歸** – 預測邊緣的數值屬性。

  例如，使用者與電影之間的評分邊緣可能具有數值屬性 `score`，Neptune ML 可以鑑於使用者和電影針對該屬性預測一值。
+ **連結預測** – 為特定來源節點和傳出邊緣預測最有可能的目的地節點，或為給定的目的地節點和傳入邊緣預測最有可能的來源節點。

  例如，透過藥物疾病知識圖譜，假設 `Aspirin` 作為來源節點，且 `treats` 作為傳出邊緣，Neptune ML 可以將最相關的目的地節點預測為 `heart disease`、`fever` 等等。

  或者，透過 Wikimedia 知識圖譜，假設 `President-of` 作為邊緣或關聯，且 `United-States` 作為目的地節點，Neptune ML 可以將最相關的前端預測為 `George Washington`、`Abraham Lincoln`、`Franklin D. Roosevelt` 等等。

**注意**  
節點分類和邊緣分類僅支援字串值。這表示不支援數值屬性值 (例如 `0` 或 `1`)，儘管字串等同於 `"0"` 和 `"1"`。同樣地，布林屬性值 `true` 和 `false` 不起作用，但 `"true"` 和 `"false"` 可以。

搭配 Neptune ML，您可以使用分為兩大類的機器學習模型：

**Neptune ML 目前支援的機器學習模型類型**
+ **圖形神經網路（GNN）模型** – 其中包含 [Relational Graph Convolutional Networks (R-GCNs)](https://arxiv.org/abs/1703.06103)。GNN 模型適用於上述所有三種類型的任務。
+ **知識圖譜嵌入 (KGE) 模型** – 其中包括 `TransE`、`DistMult` 和 `RotatE` 模型。它們僅適用於鏈接預測。

**使用者定義的模型** – Neptune ML 也可讓您為上面列出的所有類型任務提供您自己的自訂模型實作。在使用 Neptune ML 訓練 API 搭配您的模型之前，您可以使用 [Neptune ML 工具組](https://github.com/awslabs/neptuneml-toolkit)，來開發並測試 Python 型自訂模型實作。如需如何建構和組織實作，以便其與 Neptune ML 的訓練基礎結構相容的詳細資訊，請參閱 [Neptune ML 中的自訂模型](machine-learning-custom-models.md)。

# 設定 Neptune ML
<a name="machine-learning-setup"></a>

開始使用 Neptune ML 最簡單的方法是[使用 CloudFormation 快速入門範本](machine-learning-quick-start.md)。此範本會安裝所有必要的元件，包括新的 Neptune DB 叢集、所有必要的 IAM 角色，以及新的 Neptune 圖形筆記本，讓使用 Neptune ML 變得更輕鬆。

您也可以手動安裝 Neptune ML，如 [不使用快速入門 CloudFormation 範本設定 Neptune ML](machine-learning-manual-setup.md) 中所述。

# 使用 Neptune ML AWS CloudFormation 範本在新的資料庫叢集中快速開始使用
<a name="machine-learning-quick-start"></a>

開始使用 Neptune ML 最簡單的方法是使用 CloudFormation 快速入門範本。此範本會安裝所有必要的元件，包括新的 Neptune DB 叢集、所有必要的 IAM 角色，以及新的 Neptune 圖形筆記本，讓使用 Neptune ML 變得更輕鬆。

**建立 Neptune ML 快速入門堆疊**

1. 若要在 CloudFormation 主控台上啟動 CloudFormation 堆疊，請選擇下表中的其中一個**啟動堆疊**按鈕：    
[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/neptune/latest/userguide/machine-learning-quick-start.html)

1.  在 **Select Template** (選取範本) 頁面上，請選擇 **Next** (下一步)。

1. 在**指定詳細資訊**頁面上，選擇**下一步**。

1. 在**選項**頁面上，選擇**下一步**。

1. 在**檢閱**頁面上，有兩個您需要核取的核取方塊：
   + 第一個確認 AWS CloudFormation 可能會建立具有自訂名稱的 IAM 資源。
   + 第二個確認 AWS CloudFormation 可能需要新堆疊的 `CAPABILITY_AUTO_EXPAND`功能。 `CAPABILITY_AUTO_EXPAND` 明確允許 在建立堆疊時自動 CloudFormation 展開巨集，無需事先審核。

     客戶通常會在處理過的範本中建立變更集，以便在實際建立堆疊之前，檢閱巨集所做的變更。如需詳細資訊，請參閱 CloudFormation [CreateStack](https://docs.aws.amazon.com/AWSCloudFormation/latest/APIReference/API_CreateStack.html) API。

   然後選擇 **Create (建立)**。

快速入門範本會建立並設定下列項目：
+ Neptune 資料庫叢集。
+ 必要的 IAM 角色 (並附加它們)。
+ 必要的 Amazon EC2 安全群組。
+ 必要的 SageMaker AI VPC 端點。
+ Neptune ML 的資料庫叢集參數群組。
+ 該參數群組中的必要參數。
+ 預先填入 Neptune ML 筆記本範例的 SageMaker AI 筆記本。請注意，並非每個區域都提供所有執行個體大小，因此您必須確定選取的筆記型電腦執行個體大小是您所在地區支援的大小。
+ Neptune-Export 服務。

當快速入門堆疊準備就緒時，請前往範本建立的 SageMaker AI 筆記本，並查看預先填入的範例。它們將協助您下載要用於嘗試 Neptune ML 功能的範例資料集。

當您使用 Neptune ML 時，它們還可以為您節省大量時間。例如，請參閱這些筆記本支援的 [%neptune\$1ml](notebooks-magics.md#notebooks-line-magics-neptune_ml) 行魔法和 [%%neptune\$1ml](notebooks-magics.md#notebooks-cell-magics-neptune_ml) 儲存格魔法。

您也可以使用下列 AWS CLI 命令來執行快速入門 CloudFormation 範本：

```
aws cloudformation create-stack \
  --stack-name neptune-ml-fullstack-$(date '+%Y-%m-%d-%H-%M') \
  --template-url https://aws-neptune-customer-samples.s3.amazonaws.com/v2/cloudformation-templates/neptune-ml-nested-stack.json \
  --parameters ParameterKey=EnableIAMAuthOnExportAPI,ParameterValue=(true if you have IAM auth enabled, or false otherwise) \
               ParameterKey=Env,ParameterValue=test$(date '+%H%M')\
  --capabilities CAPABILITY_IAM \
  --region (the AWS region, like us-east-1) \
  --disable-rollback \
  --profile (optionally, a named CLI profile of yours)
```

# 不使用快速入門 CloudFormation 範本設定 Neptune ML
<a name="machine-learning-manual-setup"></a>

 本指南提供step-by-step說明。 Amazon Neptune AWS CloudFormation 它假設您已經有運作中的 Neptune 資料庫叢集，並涵蓋必要的設定，包括安裝 Neptune-Export 服務、建立自訂 IAM 角色，以及設定資料庫叢集以啟用 Neptune ML。本指南也說明如何在 Neptune VPC 中建立兩個 SageMaker AI 端點，讓 Neptune 引擎存取必要的 SageMaker AI 管理 APIs。透過遵循這些指示，您可以在現有的 Neptune 基礎設施上設定 Neptune ML，而無需依賴 CloudFormation 範本。

## 從運作中的 Neptune 資料庫叢集開始
<a name="ml-manual-setup-prereq"></a>

如果您不使用 CloudFormation 快速入門範本來設定 Neptune ML，則需要現有的 Neptune 資料庫叢集才能使用。如果想要的話，您可以使用已有的叢集，或複製您已使用中的叢集，或者您可以建立新的叢集 (請參閱 [建立 Neptune 叢集](get-started-create-cluster.md))。

## 安裝 Neptune-Export 服務
<a name="ml-manual-setup-export-svc"></a>

如果您尚未安裝，請安裝 Neptune-Export 服務，如 [使用 Neptune-Export 服務匯出 Neptune 資料](export-service.md) 中所述。

使用下列設定，將傳入規則新增至安裝所建立的 `NeptuneExportSecurityGroup` 安全群組：
+ *Type (類型)*：`Custom TCP`
+ *Protocol (通訊協定)*：`TCP`
+ *連接埠範圍*：`80 - 443`
+ *來源*：*(Neptune 資料庫叢集安全群組 ID)*

## 建立自訂 NeptuneLoadFromS3 IAM 角色
<a name="ml-manual-setup-s3-role"></a>

如果您尚未建立，請建立自訂 `NeptuneLoadFromS3` IAM 角色，如 [建立 IAM 角色來存取 Amazon S3](bulk-load-tutorial-IAM-CreateRole.md) 中所述。

## 建立自訂 NeptuneSageMakerIAMRole 角色
<a name="ml-manual-setup-sm-role"></a>

使用 [IAM 主控台](https://console.aws.amazon.com/iam/)搭配下列政策建立自訂 `NeptuneSageMakerIAMRole`：

------
#### [ JSON ]

****  

```
{
  "Version":"2012-10-17",		 	 	 
  "Statement": [
    {
      "Action": [
        "ec2:CreateNetworkInterface",
        "ec2:CreateNetworkInterfacePermission",
        "ec2:CreateVpcEndpoint",
        "ec2:DeleteNetworkInterface",
        "ec2:DeleteNetworkInterfacePermission",
        "ec2:DescribeDhcpOptions",
        "ec2:DescribeNetworkInterfaces",
        "ec2:DescribeRouteTables",
        "ec2:DescribeSecurityGroups",
        "ec2:DescribeSubnets",
        "ec2:DescribeVpcEndpoints",
        "ec2:DescribeVpcs"
      ],
      "Resource": "*",
      "Effect": "Allow"
    },
    {
      "Action": [
        "ecr:GetAuthorizationToken",
        "ecr:GetDownloadUrlForLayer",
        "ecr:BatchGetImage",
        "ecr:BatchCheckLayerAvailability"
      ],
      "Resource": "*",
      "Effect": "Allow"
    },
    {
      "Action": [
        "iam:PassRole"
      ],
      "Resource": [
        "arn:aws:iam::*:role/*"
      ],
      "Condition": {
        "StringEquals": {
          "iam:PassedToService": [
            "sagemaker.amazonaws.com"
          ]
        }
      },
      "Effect": "Allow"
    },
    {
      "Action": [
        "kms:CreateGrant",
        "kms:Decrypt",
        "kms:GenerateDataKey*"
      ],
      "Resource": "arn:aws:kms:*:*:key/*",
      "Effect": "Allow"
    },
    {
      "Action": [
        "logs:CreateLogGroup",
        "logs:CreateLogStream",
        "logs:PutLogEvents",
        "logs:DescribeLogGroups",
        "logs:DescribeLogStreams",
        "logs:GetLogEvents"
      ],
      "Resource": [
        "arn:aws:logs:*:*:log-group:/aws/sagemaker/*"
      ],
      "Effect": "Allow"
    },
    {
      "Action": [
        "sagemaker:AddTags",
        "sagemaker:CreateEndpoint",
        "sagemaker:CreateEndpointConfig",
        "sagemaker:CreateHyperParameterTuningJob",
        "sagemaker:CreateModel",
        "sagemaker:CreateProcessingJob",
        "sagemaker:CreateTrainingJob",
        "sagemaker:CreateTransformJob",
        "sagemaker:DeleteEndpoint",
        "sagemaker:DeleteEndpointConfig",
        "sagemaker:DeleteModel",
        "sagemaker:DescribeEndpoint",
        "sagemaker:DescribeEndpointConfig",
        "sagemaker:DescribeHyperParameterTuningJob",
        "sagemaker:DescribeModel",
        "sagemaker:DescribeProcessingJob",
        "sagemaker:DescribeTrainingJob",
        "sagemaker:DescribeTransformJob",
        "sagemaker:InvokeEndpoint",
        "sagemaker:ListTags",
        "sagemaker:ListTrainingJobsForHyperParameterTuningJob",
        "sagemaker:StopHyperParameterTuningJob",
        "sagemaker:StopProcessingJob",
        "sagemaker:StopTrainingJob",
        "sagemaker:StopTransformJob",
        "sagemaker:UpdateEndpoint",
        "sagemaker:UpdateEndpointWeightsAndCapacities"
      ],
      "Resource": [
        "arn:aws:sagemaker:*:*:*"
      ],
      "Effect": "Allow"
    },
    {
      "Action": [
        "sagemaker:ListEndpointConfigs",
        "sagemaker:ListEndpoints",
        "sagemaker:ListHyperParameterTuningJobs",
        "sagemaker:ListModels",
        "sagemaker:ListProcessingJobs",
        "sagemaker:ListTrainingJobs",
        "sagemaker:ListTransformJobs"
      ],
      "Resource": "*",
      "Effect": "Allow"
    },
    {
      "Action": [
        "s3:GetObject",
        "s3:PutObject",
        "s3:DeleteObject",
        "s3:AbortMultipartUpload",
        "s3:ListBucket"
      ],
      "Resource": [
        "arn:aws:s3:::*"
      ],
      "Effect": "Allow"
    }
  ]
}
```

------

建立此角色時，請編輯信任關係，以便其如下所示：

------
#### [ JSON ]

****  

```
{
  "Version":"2012-10-17",		 	 	 
  "Statement": [
    {
      "Effect": "Allow",
      "Principal": {
        "Service": [
          "ec2.amazonaws.com",
          "rds.amazonaws.com",
          "sagemaker.amazonaws.com"
        ]
      },
      "Action": "sts:AssumeRole"
    }
  ]
}
```

------

最後，複製指派給這個新 `NeptuneSageMakerIAMRole` 角色的 ARN。

**重要**  
確定 `NeptuneSageMakerIAMRole` 中的 Amazon S3 許可符合上述的許可。
在上述政策中，通用 ARN (`arn:aws:s3:::*`) 用於 Amazon S3 資源。如果由於某種原因無法使用通用 ARN，則 NeptuneML 命令將使用的任何其他客戶 Amazon S3 資源的 `arn:aws:s3:::graphlytics*` 和 ARN 必須新增到資源區段。

## 設定資料庫叢集以啟用 Neptune ML
<a name="ml-manual-setup-cluster-config"></a>

**為 Neptune ML 設定資料庫叢集**

1. 在 [Neptune 主控台](https://console.aws.amazon.com/neptune)中，導覽至**參數群組**，然後導覽至與您將要使用的資料庫叢集相關聯的資料庫叢集參數群組。將 `neptune_ml_iam_role` 參數設定為指派給您剛建立之 `NeptuneSageMakerIAMRole` 角色的 ARN。

1. 導覽至資料庫，然後選取將要用於 Neptune ML 的資料庫叢集。選取**動作**，然後選取**管理 IAM 角色**。

1. 在**管理 IAM 角色**頁面上，選取**新增角色**，然後新增 `NeptuneSageMakerIAMRole`。然後新增 `NeptuneLoadFromS3` 角色。

1. 重新啟動資料庫叢集的寫入器執行個體。

## 在 Neptune VPC 中建立兩個 SageMaker AI 端點
<a name="ml-manual-setup-endpoints"></a>

最後，若要讓 Neptune 引擎存取必要的 SageMaker AI 管理 APIs，您需要在 Neptune VPC 中建立兩個 SageMaker AI 端點，如中所述[在 Neptune VPC 中為 SageMaker AI 建立兩個端點](machine-learning-cluster-setup.md#machine-learning-sm-endpoints)。

# 為 Neptune ML 手動設定 Neptune 筆記本
<a name="ml-manual-setup-notebooks"></a>

Neptune SageMaker AI 筆記本預先載入了適用於 Neptune ML 的各種範例筆記本。您可以在[開放原始碼圖形筆記本 GitHub 儲存庫](https://github.com/aws/graph-notebook/tree/main/src/graph_notebook/notebooks/04-Machine-Learning)中預覽這些範例。

您可以使用其中一個現有的 Neptune 筆記本，或者如果想要的話，您可以遵循 [使用 Neptune 工作台託管 Neptune 筆記本](graph-notebooks.md#graph-notebooks-workbench) 中的指示建立自己的筆記本。

您也可以遵循下列步驟，設定預設 Neptune 筆記本以搭配 Neptune ML 使用：

**修改 Neptune ML 的筆記本**

1. 開啟位在 [https://console.aws.amazon.com/sagemaker/](https://console.aws.amazon.com/sagemaker/) 的 Amazon SageMaker AI 主控台。

1. 在左側的導覽窗格中，選擇**筆記本**，然後選擇**筆記本執行個體**。尋找您要用於 Neptune ML 的 Neptune 筆記本名稱，然後選取該名稱以前往其詳細資訊頁面。

1. 如果筆記本執行個體正在執行，請選取筆記本詳細資料頁面右上方的**停止**按鈕。

1. 在**筆記本執行個體設定**中的**生命週期組態**下，選取連結以開啟筆記本生命週期的頁面。

1. 選取右上方的**編輯**，然後選取**繼續**。

1. 在**啟動筆記本**索引標籤中，修改指令碼以包含其他匯出命令，並填入 Neptune ML IAM 角色和匯出服務 URI 的欄位 (如下所示)，取決於您的 Shell：

   ```
   echo "export NEPTUNE_ML_ROLE_ARN=(your Neptune ML IAM role ARN)" >> ~/.bashrc
   echo "export NEPTUNE_EXPORT_API_URI=(your export service URI)" >> ~/.bashrc
   ```

1. 選取 **Update** (更新)。

1. 返回筆記本執行個體頁面。在**許可和加密**下，**IAM 角色 ARN** 有一個欄位。選取此欄位中的連結，即可前往此筆記本執行個體搭配執行的 IAM 角色。

1. 建立新的內嵌政策，如下所示：

------
#### [ JSON ]

****  

   ```
   {
     "Version":"2012-10-17",		 	 	 
     "Statement": [
       {
         "Action": [
           "cloudwatch:PutMetricData"
         ],
         "Resource": "arn:aws:cloudwatch:us-east-1:111122223333:*",
         "Sid": "AllowPutMetrics",
         "Effect": "Allow"
       },
       {
         "Action": [
           "logs:CreateLogGroup",
           "logs:CreateLogStream",
           "logs:DescribeLogStreams",
           "logs:PutLogEvents",
           "logs:GetLogEvents"
         ],
         "Resource": "arn:aws:logs:us-east-1:111122223333:*",
         "Sid": "AllowCreateLogs",
         "Effect": "Allow"
       },
       {
         "Action": [
           "s3:Put*",
           "s3:Get*",
           "s3:List*"
         ],
         "Resource": "arn:aws:s3:::*",
         "Sid": "AllowS3Actions",
         "Effect": "Allow"
       },
       {
         "Action": "execute-api:Invoke",
         "Resource": "arn:aws:execute-api:us-east-1:111122223333:*/*",
         "Sid": "AllowExecute",
         "Effect": "Allow"
       },
       {
         "Action": [
           "sagemaker:CreateModel",
           "sagemaker:CreateEndpointConfig",
           "sagemaker:CreateEndpoint",
           "sagemaker:DescribeModel",
           "sagemaker:DescribeEndpointConfig",
           "sagemaker:DescribeEndpoint",
           "sagemaker:DeleteModel",
           "sagemaker:DeleteEndpointConfig",
           "sagemaker:DeleteEndpoint"
         ],
         "Resource": "arn:aws:sagemaker:us-east-1:111122223333:*/*",
         "Sid": "AllowApiActions",
         "Effect": "Allow"
       },
       {
         "Action": [
           "iam:PassRole"
         ],
         "Resource": "arn:aws:iam::111122223333:role/role-name",
         "Sid": "AllowPassRole",
         "Effect": "Allow"
       }
     ]
   }
   ```

------

1. 儲存此新政策並在步驟 8 中將其附加至 IAM 角色。

1. 選取 SageMaker AI 筆記本執行個體詳細資訊頁面右上角的**開始**，以啟動筆記本執行個體。

# 使用 AWS CLI 在資料庫叢集上設定 Neptune ML
<a name="machine-learning-cluster-setup"></a>

除了 CloudFormation 快速入門範本和 之外 AWS 管理主控台，您也可以使用 設定 Neptune ML AWS CLI。

## 為新的 Neptune ML 叢集建立資料庫叢集參數群組
<a name="machine-learning-enabling-create-param-group"></a>

下列 AWS CLI 命令會建立新的資料庫叢集參數群組，並將其設定為使用 Neptune ML：

**建立和設定 Neptune ML 的資料庫叢集參數群組**

1. 建立新的資料庫叢集參數群組：

   ```
   aws neptune create-db-cluster-parameter-group \
     --db-cluster-parameter-group-name (name of the new DB cluster parameter group) \
     --db-parameter-group-family neptune1
     --description "(description of your machine learning project)" \
     --region (AWS region, such as us-east-1)
   ```

1. 建立`neptune_ml_iam_role`資料庫叢集參數設定為 的 ARN，`SageMakerExcecutionIAMRole`以供資料庫叢集在呼叫 SageMaker AI 以建立任務並從託管 ML 模型取得預測時使用：

   ```
   aws neptune modify-db-cluster-parameter-group \
     --db-cluster-parameter-group-name (name of the new DB cluster parameter group) \
     --parameters "ParameterName=neptune_ml_iam_role, \
                   ParameterValue=ARN of the SageMakerExcecutionIAMRole, \
                   Description=NeptuneMLRole, \
                   ApplyMethod=pending-reboot" \
     --region (AWS region, such as us-east-1)
   ```

   設定此參數可讓 Neptune 存取 SageMaker AI，而無需在每次呼叫時傳入角色。

   如需如何建立 `SageMakerExcecutionIAMRole` 的相關資訊，請參閱 [建立自訂 NeptuneSageMakerIAMRole 角色](machine-learning-manual-setup.md#ml-manual-setup-sm-role)。

1. 最後，使用 `describe-db-cluster-parameters` 檢查新資料庫叢集參數群組中的所有參數是否都按照您想要的方式進行設定：

   ```
   aws neptune describe-db-cluster-parameters \
     --db-cluster-parameter-group-name (name of the new DB cluster parameter group) \
     --region (AWS region, such as us-east-1)
   ```

## 將新的資料庫叢集參數群組附加至您將搭配 Neptune ML 使用的資料庫叢集
<a name="machine-learning-enabling-attach-param-group"></a>

現在，您可以使用下列命令，將剛建立的新資料庫叢集參數群組附加至現有的資料庫叢集：

```
aws neptune modify-db-cluster \
  --db-cluster-identifier (the name of your existing DB cluster) \
  --apply-immediately
  --db-cluster-parameter-group-name (name of your new DB cluster parameter group) \
  --region (AWS region, such as us-east-1)
```

若要使所有參數生效，您可以接著重新啟動資料庫叢集：

```
aws neptune reboot-db-instance
  --db-instance-identifier (name of the primary instance of your DB cluster) \
  --profile (name of your AWS profile to use) \
  --region (AWS region, such as us-east-1)
```

或者，如果您要建立新的資料庫叢集以搭配 Neptune ML 使用，則可以使用下列命令，建立附加新參數群組的叢集，然後建立新的主要 (寫入器) 執行個體：

```
cluster-name=(the name of the new DB cluster)
aws neptune create-db-cluster
  --db-cluster-identifier ${cluster-name}
  --engine graphdb \
  --engine-version 1.0.4.1 \
  --db-cluster-parameter-group-name (name of your new DB cluster parameter group) \
  --db-subnet-group-name (name of the subnet to use) \
  --region (AWS region, such as us-east-1)

aws neptune create-db-instance
  --db-cluster-identifier ${cluster-name}
  --db-instance-identifier ${cluster-name}-i \
  --db-instance-class (the instance class to use, such as db.r5.xlarge)
  --engine graphdb \
  --region (AWS region, such as us-east-1)
```

## 將 `NeptuneSageMakerIAMRole`連接至資料庫叢集，以便其可存取 SageMaker AI 和 Amazon S3 資源
<a name="machine-learning-enabling-attach-neptune-sagemaker-role"></a>

最後，請依照 中的指示[建立自訂 NeptuneSageMakerIAMRole 角色](machine-learning-manual-setup.md#ml-manual-setup-sm-role)建立 IAM 角色，讓您的資料庫叢集能夠與 SageMaker AI 和 Amazon S3 通訊。然後，使用以下命令將您建立的 `NeptuneSageMakerIAMRole` 角色附加至資料庫叢集：

```
aws neptune add-role-to-db-cluster
  --db-cluster-identifier ${cluster-name}
  --role-arn arn:aws:iam::(the ARN number of the role's ARN):role/NeptuneMLRole \
  --region (AWS region, such as us-east-1)
```

## 在 Neptune VPC 中為 SageMaker AI 建立兩個端點
<a name="machine-learning-sm-endpoints"></a>

Neptune ML 在 Neptune 資料庫叢集的 VPC 中需要兩個 SageMaker AI 端點：
+ `com.amazonaws.(AWS region, like us-east-1).sagemaker.runtime`
+ `com.amazonaws.(AWS region, like us-east-1).sagemaker.api`

如果您尚未使用快速入門 CloudFormation 範本，而該範本會自動為您建立這些範本，您可以使用下列 AWS CLI 命令來建立這些範本：

下列命令會建立 `sagemaker.runtime` 端點：

```
aws ec2 create-vpc-endpoint
  --vpc-id (the ID of your Neptune DB cluster's VPC)
  --vpc-endpoint-type Interface
  --service-name com.amazonaws.(AWS region, like us-east-1).sagemaker.runtime
  --subnet-ids (the subnet ID or IDs that you want to use)
  --security-group-ids (the security group for the endpoint network interface, or omit to use the default)
  --private-dns-enabled
```

下列命令則會建立 `sagemaker.api` 端點：

```
aws ec2 create-vpc-endpoint
  --vpc-id (the ID of your Neptune DB cluster's VPC)
  --vpc-endpoint-type Interface
  --service-name com.amazonaws.(AWS region, like us-east-1).sagemaker.api
  --subnet-ids (the subnet ID or IDs that you want to use)
  --security-group-ids (the security group for the endpoint network interface, or omit to use the default)
  --private-dns-enabled
```

您也可以使用 [VPC 主控台](https://console.aws.amazon.com/vpc/)建立這些端點。請參閱 [Amazon SageMaker with AWS PrivateLink 中的安全預測呼叫](https://aws.amazon.com/blogs/machine-learning/secure-prediction-calls-in-amazon-sagemaker-with-aws-privatelink/)和[使用 AWS PrivateLink 保護所有 Amazon SageMaker API 呼叫](https://aws.amazon.com/blogs/machine-learning/securing-all-amazon-sagemaker-api-calls-with-aws-privatelink/)。

## 在資料庫叢集參數群組中建立 SageMaker AI 推論端點參數
<a name="machine-learning-set-inference-endpoint-cluster-parameter"></a>

若要避免在對模型進行的每個查詢中指定模型的 SageMaker AI 推論端點，請在 Neptune ML 的資料庫叢集參數群組`neptune_ml_endpoint`中建立名為 的資料庫叢集參數。將參數設定為有問題執行個體端點的 `id`。

您可以使用下列 AWS CLI 命令來執行此操作：

```
aws neptune modify-db-cluster-parameter-group \
  --db-cluster-parameter-group-name neptune-ml-demo \
  --parameters "ParameterName=neptune_ml_endpoint, \
                ParameterValue=(the name of the SageMaker AI inference endpoint you want to query), \
                Description=NeptuneMLEndpoint, \
                ApplyMethod=pending-reboot" \
  --region (AWS region, such as us-east-1)
```

# 如何使用 Neptune ML 特徵的概觀
<a name="machine-learning-overview"></a>

 Amazon Neptune 中的 Neptune ML 功能提供簡化的工作流程，以利用圖形資料庫中的機器學習模型。此程序涉及幾個關鍵步驟：將資料從 Neptune 匯出為 CSV 格式、預先處理資料以準備模型訓練、使用 Amazon SageMaker AI 訓練機器學習模型、建立推論端點以提供預測，然後直接從 Gremlin 查詢查詢模型。Neptune 工作台提供便利的明細和儲存格魔術命令，以協助管理和自動化這些步驟。透過將機器學習功能直接整合到圖形資料庫中，Neptune ML 可讓使用者衍生寶貴的洞見，並使用儲存在 Neptune 圖形中的豐富關聯式資料進行預測。

## 啟動使用 Neptune ML 的工作流程
<a name="machine-learning-overview-starting-workflow"></a>

在 Amazon Neptune 中使用 Neptune ML 功能通常涉及以下五個步驟以開始：

![\[Neptune ML 工作流程圖\]](http://docs.aws.amazon.com/zh_tw/neptune/latest/userguide/images/neptune-ML-workflow.png)


1. **資料匯出和組態** – 資料匯出步驟會使用 Neptune-Export 服務或 `neptune-export` 命令列工具，以 CSV 格式將資料從 Neptune 匯出至 Amazon Simple Storage Service (Amazon S3)。名為 `training-data-configuration.json` 的組態檔案會同時自動產生，指定如何將匯出的資料載入至可訓練的圖形。

1. **資料預先處理** – 在此步驟中，匯出的資料集會使用標準技術預先處理，以準備進行模型訓練。可針對數值資料執行特徵標準化，並可以使用 `word2vec` 編碼文字特徵。在此步驟結束時，會從匯出的資料集產生 DGL (Deep Graph Library) 圖形，供模型訓練步驟使用。

   此步驟是使用您帳戶中的 SageMaker AI 處理任務來實作，產生的資料會存放在您指定的 Amazon S3 位置。

1. **模型訓練** – 模型訓練步驟會訓練將用於預測的機器學習模型。

   模型訓練分兩個階段完成：
   + 第一階段使用 SageMaker AI 處理任務來產生模型訓練策略組態集，指定要用於模型訓練的模型和模型超參數範圍類型。
   + 第二階段接著使用 SageMaker AI 模型調校任務來嘗試不同的超參數組態，然後選取產生最佳效能模型的訓練任務。調整工作會對已處理的資料執行預先指定數量的模型訓練工作試驗。在此階段結束時，會使用最佳訓練工作的訓練模型參數，產生用於推論的模型成品。

1. 在 **Amazon SageMaker AI 中建立推論端點** – 推論端點是使用最佳訓練任務產生的模型成品啟動的 SageMaker AI 端點執行個體。每個模型都繫結至單一端點。端點能夠接受來自圖形資料庫的傳入請求，並傳回請求中輸入的模型預測。在您建立端點之後，它會保持作用中狀態，直到您將其刪除為止。

1. **使用 Gremlin 查詢機器學習模型** – 您可以使用 Gremlin 查詢語言的延伸模組，從推論端點查詢預測。

**注意**  
[Neptune 工作台](graph-notebooks.md#graph-notebooks-workbench)包含一個行魔法和一個儲存格魔法，其可以為您節省管理這些步驟的大量時間，即：  
[%neptune\$1ml](notebooks-magics.md#notebooks-line-magics-neptune_ml)
[%%neptune\$1ml](notebooks-magics.md#notebooks-cell-magics-neptune_ml)

# 根據不斷發展的圖形資料進行預測
<a name="machine-learning-overview-evolving-data"></a>

使用持續變更的圖形，您可能想要使用全新資料定期建立新的批次預測。查詢預先計算的預測 (直推式推論) 比根據最新資料 (歸納推論) 即時產生新預測要快得多。這兩種方法都有自己的可取之處，取決於資料變更的速度和效能需求。

## 歸納推論與直推式推論之間的區別
<a name="inductive-vs-transductive-inference"></a>

執行直推式推論時，Neptune 會查詢並傳回訓練時預先計算的預測。

執行歸納推論時，Neptune 會建構相關的子圖形並擷取其屬性。然後，DGL GNN 模型會即時套用資料處理和模型評估。

因此，歸納推論可以產生涉及節點和邊緣的預測，而這些節點和邊緣在訓練時不存在，並會反映圖形的目前狀態。代價是更高的延遲。

如果您的圖形是動態的，您可能想要使用歸納推論來確保將最新資料納入考慮，但是如果您的圖形是靜態的，則直推式推論更快、更有效率。

歸納推論預設為停用。您可以在查詢中使用 Gremlin [Neptune\$1ml.inductiveInference](machine-learning-gremlin-inference-query-predicates.md#machine-learning-gremlin-inference-neptune-ml-inductiveInference) 述詞，啟用此推論進行查詢，如下所示：

```
.with( "Neptune#ml.inductiveInference")
```

# 增量直推式工作流程
<a name="machine-learning-overview-evolving-data-incremental"></a>

儘管您只需重新執行步驟一到三 (從**資料匯出和組態**到**模型轉換**) 即可更新模型成品，但 Neptune ML 支援更簡單的方法，以使用新資料更新批次 ML 預測。一種是使用[增量模型工作流程](#machine-learning-overview-incremental)，而另一種則是使用[透過暖啟動進行模型重新訓練](#machine-learning-overview-model-retraining)。

## 增量模型工作流程
<a name="machine-learning-overview-incremental"></a>

在此工作流程中，您可以更新 ML 預測，而無需要重新訓練 ML 模型。

**注意**  
只有當圖形資料已使用新的節點和/或邊緣進行更新時，您才能執行此操作。目前，當節點遭刪除時，它無法運作。

1. **資料匯出和組態** – 此步驟與主工作流程中的步驟相同。

1. **增量資料預先處理** – 此步驟類似於主工作流程中的資料預先處理步驟，但使用先前使用的相同處理組態，此組態對應至特定的訓練模型。

1. **模型轉換** – 此模型轉換步驟不是模型訓練步驟，而是從主工作流程和增量資料預先處理步驟的結果中取得訓練模型，並產生要用於推論的新模型成品。模型轉換步驟會啟動 SageMaker AI 處理任務，以執行產生更新模型成品的運算。

1. **更新 Amazon SageMaker AI 推論端點** – 或者，如果您有現有的推論端點，此步驟會使用模型轉換步驟所產生的新模型成品來更新端點。或者，您也可以使用新的模型成品建立新的推論端點。

## 透過暖啟動進行模型重新訓練
<a name="machine-learning-overview-model-retraining"></a>

使用此工作流程，您可以訓練和部署新的 ML 模型，以使用增量圖形資料進行預測，但是從使用主工作流程產生的現有模型開始：

1. **資料匯出和組態** – 此步驟與主工作流程中的步驟相同。

1. **增量資料預先處理** – 此步驟與增量模型推論工作流程中的步驟相同。新的圖形資料應該使用先前用於模型訓練的相同處理方法來處理。

1. **透過暖啟動進行模型訓練** – 模型訓練類似於主工作流程中發生的情況，但是您可以利用來自先前模型訓練任務的資訊來加速模型超參數搜尋。

1. **更新 Amazon SageMaker AI 推論端點** – 此步驟與增量模型推論工作流程中的相同。

# Neptune ML 中自訂模型的工作流程
<a name="machine-learning-overview-custom-model-workflow"></a>

Neptune ML 可讓您針對 Neptune ML 支援的任何任務實作、訓練和部署您自己的自訂模型。開發和部署自訂模型的工作流程基本上與內建模型的工作流程相同，但有一些差異，如 [自訂模型工作流](machine-learning-custom-model-overview.md#machine-learning-custom-model-workflow) 中所述。

# Neptune ML 階段的執行個體選擇
<a name="machine-learning-on-graphs-instance-selection"></a>

Neptune ML 處理的不同階段使用不同的 SageMaker AI 執行個體。在此，我們討論如何為每個階段選擇正確的執行個體類型。您可以在 Amazon SageMaker 定價中找到 SageMaker AI 執行個體類型和定價的相關資訊。 [Amazon SageMaker ](https://aws.amazon.com/sagemaker/pricing/)

## 選取執行個體進行資料處理
<a name="machine-learning-on-graphs-processing-instance-size"></a>

SageMaker AI [資料處理](machine-learning-on-graphs-processing.md)步驟需要一個[處理執行個體](https://docs.aws.amazon.com/sagemaker/latest/dg/processing-job.html)，該執行個體具有足夠的記憶體和磁碟儲存空間，可用於輸入、中繼和輸出資料。所需的特定記憶體和磁碟儲存體容量取決於 Neptune ML 圖形的特性及其匯出的特徵。

根據預設，Neptune ML 會選擇其記憶體十倍於磁碟上所匯出圖形資料大小的最小 `ml.r5` 執行個體。

## 選取執行個體進行模型訓練和模型轉換
<a name="machine-learning-on-graphs-training-transform-instance-size"></a>

選取正確的執行個體類型進行[模型訓練](https://docs.aws.amazon.com/sagemaker/latest/dg/how-it-works-training.html)或[模型轉換](https://docs.aws.amazon.com/sagemaker/latest/dg/how-it-works-batch.html)，取決於任務類型、圖形大小和您的周轉需求。GPU 執行個體可提供最佳效能。我們通常建議 `p3` 和 `g4dn` 序列執行個體。您也可以使用 `p2` 或 `p4d` 執行個體。

根據預設，Neptune ML 會選擇其記憶體超過模型訓練和模型轉換所需的最小 GPU 執行個體。您可以在 Amazon S3 資料處理輸出位置的 `train_instance_recommendation.json` 檔案中找到該選擇的內容。以下是 `train_instance_recommendation.json` 檔案的內容範例：

```
{ 
  "instance":     "(the recommended instance type for model training and transform)",
  "cpu_instance": "(the recommended instance type for base processing instance)", 
  "disk_size":    "(the estimated disk space required)",
  "mem_size":     "(the estimated memory required)"
}
```

## 為推論端點選取執行個體
<a name="machine-learning-on-graphs-inference-endpoint-instance-size"></a>

為[推論端點](machine-learning-on-graphs-inference-endpoint.md)選取正確的執行個體類型，取決於任務類型、圖形大小和預算。根據預設，Neptune ML 會選擇其記憶體超過推論端點所需的最小`ml.m5d`執行個體。

**注意**  
如果需要超過 384 GB 的記憶體，Neptune ML 會使用 `ml.r5d.24xlarge` 執行個體。

您可以在 `infer_instance_recommendation.json` 檔案中查看 Neptune ML 建議的執行個體類型，此檔案位於您用於模型訓練的 Amazon S3 位置。以下是該檔案的內容範例：

```
{ 
  "instance" :   "(the recommended instance type for an inference endpoint)",
  "disk_size" :  "(the estimated disk space required)",
  "mem_size" :   "(the estimated memory required)"
}
```

# 使用 neptune-export 工具或 Neptune-Export 服務從 Neptune for Neptune ML 匯出資料
<a name="machine-learning-data-export"></a>

Neptune ML 需要您為 [Deep Graph Library (DGL)](https://www.dgl.ai/) 提供訓練資料，以建立和評估模型。

您可以使用 [Neptune-Export 服務](export-service.md)或 [`neptune-export` 公用程式](export-utility.md)，從 Neptune 中匯出資料。此服務和命令列工具兩者都會以 CSV 格式將資料發佈至 Amazon Simple Storage Service (Amazon S3)，並使用 Amazon S3 伺服器端加密 (`SSE-S3`) 進行加密。請參閱 [由 Neptune-Export 和 `neptune-export` 匯出的檔案](exported-files.md)。

此外，當您針對 Neptune ML 設定訓練資料的匯出時，匯出工作會建立並發佈加密的模型訓練組態檔案，以及匯出的資料。根據預設，此檔案會命名為 `training-data-configuration.json`。

# 使用 Neptune-Export 服務匯出 Neptune ML 訓練資料的範例
<a name="machine-learning-export-examples"></a>

此請求會匯出節點分類任務的屬性圖訓練資料：

```
curl \
  (your NeptuneExportApiUri) \
  -X POST \
  -H 'Content-Type: application/json' \
  -d '{
        "command": "export-pg",
        "outputS3Path": "s3://(your Amazon S3 bucket)/neptune-export",
        "params": {
          "endpoint": "(your Neptune endpoint DNS name)",
          "profile": "neptune_ml"
        },
        "additionalParams": {
          "neptune_ml": {
            "version": "v2.0",
            "targets": [
              {
                "node": "Movie",
                "property": "genre",
                "type": "classification"
              }
            ]
          }
        }
      }'
```

此請求會匯出節點分類任務的 RDF 訓練資料：

```
curl \
  (your NeptuneExportApiUri) \
  -X POST \
  -H 'Content-Type: application/json' \
  -d '{
        "command": "export-rdf",
        "outputS3Path": "s3://(your Amazon S3 bucket)/neptune-export",
        "params": {
          "endpoint": "(your Neptune endpoint DNS name)",
          "profile": "neptune_ml"
        },
        "additionalParams": {
          "neptune_ml": {
            "version": "v2.0",
            "targets": [
              {
                "node": "http://aws.amazon.com/neptune/csv2rdf/class/Movie",
                "predicate": "http://aws.amazon.com/neptune/csv2rdf/datatypeProperty/genre",
                "type": "classification"
              }
            ]
          }
        }
      }'
```

# 匯出訓練資料時要在參數物件中設定的欄位
<a name="machine-learning-params"></a>

匯出請求中的 `params` 物件可以包含各種欄位，如 [`params` 文件](export-params-fields.md)中所述。下列欄位與匯出機器學習訓練資料最相關：

****
+ **`endpoint`** – 使用 `endpoint` 來指定資料庫叢集中 Neptune 執行個體的端點，匯出程序可以查詢該資料庫叢集來擷取資料。
+ **`profile`** – 必須將 `params` 物件中的 `profile` 欄位設為 **`neptune-ml`**。

  這會導致匯出程序針對 Neptune ML 模型訓練適當地格式化匯出的資料，若是屬性圖資料採取 CSV 格式，若是 RDF 資料則以 N-Triples 表示。它也會導致系統建立 `training-data-configuration.json` 檔案，並將其寫入與匯出的訓練資料相同的 Amazon S3 位置。
+ **`cloneCluster`** – 如果設為 `true`，匯出程序會複製您的資料庫叢集、從該複製中匯出，然後在完成時刪除該複製。
+ **`useIamAuth`** – 如果您的資料庫叢集已啟用 [IAM 身分驗證](iam-auth-enable.md)，則您必須包含這個設為 `true` 的欄位。

匯出程序還提供了幾種篩選您匯出之資料的方法 (請參閱[這些範例](export-filtering-examples.md))。

# 使用 additionalParams 物件來調整模型訓練資訊的匯出
<a name="machine-learning-additionalParams"></a>

`additionalParams` 物件包含若干欄位，您可以使用這些欄位，來指定機器學習類別標籤特徵以供訓練用途，並且指導訓練資料組態檔案的建立。

匯出程序無法自動推斷哪些節點和邊緣屬性應該是機器學習類別標籤，以作為訓練用途的範例。它也無法自動推斷數值、類別和文字屬性的最佳特徵編碼，因此您需要使用 `additionalParams` 物件中的欄位提供提示，來指定這些項目或覆寫預設編碼。

對於屬性圖資料，匯出要求中 `additionalParams` 的最上層結構可能如下所示：

```
{
  "command": "export-pg",
  "outputS3Path": "s3://(your Amazon S3 bucket)/neptune-export",
  "params": {
    "endpoint": "(your Neptune endpoint DNS name)",
    "profile": "neptune_ml"
  },
  "additionalParams": {
      "neptune_ml": {
        "version": "v2.0",
        "targets": [ (an array of node and edge class label targets) ],
        "features": [ (an array of node feature hints) ]
    }
  }
}
```

對於 RDF 資料，其最上層結構可能如下所示：

```
{
  "command": "export-rdf",
  "outputS3Path": "s3://(your Amazon S3 bucket)/neptune-export",
  "params": {
    "endpoint": "(your Neptune endpoint DNS name)",
    "profile": "neptune_ml"
  },
  "additionalParams": {
      "neptune_ml": {
        "version": "v2.0",
        "targets": [ (an array of node and edge class label targets) ]
    }
  }
}
```

您也可以使用 `jobs` 欄位來提供多個匯出組態：

```
{
  "command": "export-pg",
  "outputS3Path": "s3://(your Amazon S3 bucket)/neptune-export",
  "params": {
    "endpoint": "(your Neptune endpoint DNS name)",
    "profile": "neptune_ml"
  },
  "additionalParams" : {
    "neptune_ml" : {
      "version": "v2.0",
      "jobs": [
        {
          "name" : "(training data configuration name)",
          "targets": [ (an array of node and edge class label targets) ],
          "features": [ (an array of node feature hints) ]
        },
        {
          "name" : "(another training data configuration name)",
          "targets": [ (an array of node and edge class label targets) ],
          "features": [ (an array of node feature hints) ]
        }
      ]
    }
  }
}
```

# additionalParams 中 neptune\$1ml 欄位的最上層元素
<a name="machine-learning-neptune_ml-top-level"></a>

## neptune\$1ml 中的版本元素
<a name="machine-learning-neptune_ml-version"></a>

指定要產生的訓練資料組態版本。

(*選用*)，*類型*：字串，*預設值*：「v2.0」。

如果確實包含 `version`，請將其設為 `v2.0`。

## neptune\$1ml 中的任務欄位
<a name="machine-learning-neptune_ml-jobs"></a>

包含訓練資料組態物件的陣列，每個物件都會定義資料處理工作，並包含：
+ **`name`** – 要建立的訓練資料組態名稱。

   例如，名稱為「job-number-1」的訓練資料組態會產生一個名為 `job-number-1.json` 的訓練資料組態檔案。
+ **`targets`** – 節點和邊緣類別標籤目標的 JSON 陣列，這些目標代表供訓練用途的機器學習類別標籤。請參閱 [neptune\$1ml 物件中的目標欄位](machine-learning-neptune_ml-targets.md)。
+ **`features`** – 節點屬性特徵的 JSON 陣列。請參閱[neptune\$1ml 中的功能欄位](machine-learning-neptune_ml-features.md)。

# neptune\$1ml 物件中的目標欄位
<a name="machine-learning-neptune_ml-targets"></a>

JSON 訓練資料匯出組態中的 `targets` 欄位包含目標物件的陣列，這些物件會指定訓練任務，以及用於訓練此任務的機器學習類別標籤。目標物件的內容會有所不同，取決於您是在屬性圖資料還是 RDF 資料上進行訓練。

對於屬性圖節點分類和迴歸任務，陣列中的目標物件可能如下所示：

```
{
  "node": "(node property-graph label)",
  "property": "(property name)",
  "type" : "(used to specify classification or regression)",
  "split_rate": [0.8,0.2,0.0],
  "separator": ","
}
```

對於屬性圖邊緣分類，迴歸或連結預測任務，它們可以如下所示：

```
{
  "edge": "(edge property-graph label)",
  "property": "(property name)",
  "type" : "(used to specify classification, regression or link_prediction)",
  "split_rate": [0.8,0.2,0.0],
  "separator": ","
}
```

對於 RDF 分類和迴歸任務，陣列中的目標物件可能如下所示：

```
{
  "node": "(node type of an RDF node)",
  "predicate": "(predicate IRI)",
  "type" : "(used to specify classification or regression)",
  "split_rate": [0.8,0.2,0.0]
}
```

對於 RDF 連結預測任務，陣列中的目標物件可以如下所示：

```
{
  "subject": "(source node type of an edge)",
  "predicate": "(relation type of an edge)",
  "object": "(destination node type of an edge)",
  "type" : "link_prediction",
  "split_rate": [0.8,0.2,0.0]
}
```

目標物件可以包含下列欄位：

**Contents**
+ [屬性圖目標欄位](#machine-learning-property-graph-neptune_ml-targets)
  + [節點](#machine-learning-property-graph-neptune_ml-targets-node)
  + [節點](#machine-learning-property-graph-neptune_ml-targets-edge)
  + [屬性](#machine-learning-property-graph-neptune_ml-targets-property)
  + [type](#machine-learning-property-graph-neptune_ml-targets-type)
  + [split\$1rate](#machine-learning-property-graph-neptune_ml-targets-split_rate)
  + [separator](#machine-learning-property-graph-neptune_ml-targets-separator)
+ [RDF 目標欄位](#machine-learning-RDF-neptune_ml-targets)
  + [節點](#machine-learning-RDF-neptune_ml-targets-node)
  + [subject](#machine-learning-RDF-neptune_ml-targets-subject)
  + [述詞](#machine-learning-RDF-neptune_ml-targets-predicate)
  + [object](#machine-learning-RDF-neptune_ml-targets-object)
  + [type](#machine-learning-RDF-neptune_ml-targets-type)
  + [split\$1rate](#machine-learning-RDF-neptune_ml-targets-split_rate)

## 屬性圖目標物件中的欄位
<a name="machine-learning-property-graph-neptune_ml-targets"></a>

### 目標物件中的節點 （頂點） 欄位
<a name="machine-learning-property-graph-neptune_ml-targets-node"></a>

目標節點 (頂點) 的屬性圖標籤。目標物件必須包含 `node` 元素或 `edge` 元素，但不能同時包含兩者。

`node` 可以採取單一值，如下所示：

```
  "node": "Movie"
```

或者，在多標籤頂點的情況下，它可以採取值陣列，如下所示：

```
  "node": ["Content", "Movie"]
```

### 屬性圖目標物件中的邊緣欄位
<a name="machine-learning-property-graph-neptune_ml-targets-edge"></a>

透過其起始節點標籤、自己的標籤及其結束節點標籤來指定目標邊緣。目標物件必須包含 `edge` 元素或 `node` 元素，但不能同時包含兩者。

`edge` 欄位的值是一個 JSON 陣列，由三個字串組成，這些字串代表起始節點的屬性圖標籤、邊緣本身的屬性圖標籤，以及結束節點的屬性圖標籤，如下所示：

```
  "edge": ["Person_A", "knows", "Person_B"]
```

如果起始節點和/或結束節點有多個標籤，請以陣列括住它們，如下所示：

```
  "edge": [ ["Admin", Person_A"], "knows", ["Admin", "Person_B"] ]
```

### 屬性圖目標物件中的屬性欄位
<a name="machine-learning-property-graph-neptune_ml-targets-property"></a>

指定目標頂點或邊緣的屬性，如下所示：

```
  "property" : "rating"
```

除了目標任務為連結預測時，此欄位都為必要的。

### 屬性圖目標物件中的類型欄位
<a name="machine-learning-property-graph-neptune_ml-targets-type"></a>

指出要在 `node` 或 `edge` 上執行的目標任務類型，如下所示：

```
  "type" : "regression"
```

節點支援的任務類型如下：
+ `classification`
+ `regression`

邊緣支援的任務類型如下：
+ `classification`
+ `regression`
+ `link_prediction`

此欄位為必填。

### 屬性圖目標物件中的 split\$1rate 欄位
<a name="machine-learning-property-graph-neptune_ml-targets-split_rate"></a>

(*選用*) 訓練、驗證和測試階段將分別使用的節點或邊緣比例估計。這些比例是以 JSON 陣列表示，該陣列由介於零與一之間的三個數字組成，加起來最多為 1：

```
"split_rate": [0.7, 0.1, 0.2]
```

如果您不提供選用`split_rate`欄位，預設的預估值是`[0.9, 0.1, 0.0]`用於分類和迴歸任務，以及`[0.9,0.05, 0.05]`用於連結預測任務。

### 屬性圖目標物件中的分隔符號欄位
<a name="machine-learning-property-graph-neptune_ml-targets-separator"></a>

(*選用*) 搭配分類任務使用。

`separator` 欄位會指定一個字元，用來在其用來將多個類別值儲存在字串中時，將目標屬性值分割為多個類別值。例如：

```
"separator": "|"
```

`separator` 欄位的存在表示任務是多目標分類任務。

## RDF 目標物件中的欄位
<a name="machine-learning-RDF-neptune_ml-targets"></a>

### RDF 目標物件中的節點欄位
<a name="machine-learning-RDF-neptune_ml-targets-node"></a>

定義目標節點的節點類型。與節點分類任務或節點迴歸任務搭配使用。RDF 中節點的節點類型，其定義方式如下：

```
  node_id, <http://www.w3.org/1999/02/22-rdf-syntax-ns#type>, node_type
```

RDF `node` 只能採取單一值，如下所示：

```
  "node": "http://aws.amazon.com/neptune/csv2rdf/class/Movie"
```

### RDF 目標物件中的主旨欄位
<a name="machine-learning-RDF-neptune_ml-targets-subject"></a>

對於連結預測任務，`subject` 定義目標邊緣的來源節點類型。

```
  "subject": "http://aws.amazon.com/neptune/csv2rdf/class/Director"
```

**注意**  
對於連結預測任務，`subject` 應同時與 `predicate` 和 `object` 搭配使用。如果未提供這三個的任一個，則會將所有邊緣視為訓練目標。

### RDF 目標物件中的述詞欄位
<a name="machine-learning-RDF-neptune_ml-targets-predicate"></a>

對於節點分類和節點迴歸任務，`predicate` 定義要使用哪個常值資料做為目標節點的目標節點特徵。

```
  "predicate": "http://aws.amazon.com/neptune/csv2rdf/datatypeProperty/genre"
```

**注意**  
如果目標節點只有一個定義目標節點特徵的述詞，則可以省略 `predicate` 欄位。

對於連結預測任務，`predicate` 定義目標邊緣的關聯類型：

```
"predicate": "http://aws.amazon.com/neptune/csv2rdf/datatypeProperty/direct"
```

**注意**  
對於連結預測任務，`predicate` 應同時與 `subject` 和 `object` 搭配使用。如果未提供這三個的任一個，則會將所有邊緣視為訓練目標。

### RDF 目標物件中的物件欄位
<a name="machine-learning-RDF-neptune_ml-targets-object"></a>

對於連結預測任務，`object` 定義目標邊緣的目的地節點類型：

```
  "object": "http://aws.amazon.com/neptune/csv2rdf/class/Movie"
```

**注意**  
對於連結預測任務，`object` 應同時與 `subject` 和 `predicate` 搭配使用。如果未提供這三個的任一個，則會將所有邊緣視為訓練目標。

### RDF 目標物件中的類型欄位
<a name="machine-learning-RDF-neptune_ml-targets-type"></a>

指示要執行的目標任務類型，如下所示：

```
  "type" : "regression"
```

RDF 資料支援的任務類型如下：
+ `link_prediction`
+ `classification`
+ `regression`

此欄位為必填。

### 屬性圖目標物件中的 `split_rate` 欄位
<a name="machine-learning-RDF-neptune_ml-targets-split_rate"></a>

(*選用*) 訓練、驗證和測試階段將分別使用的節點或邊緣比例估計。這些比例是以 JSON 陣列表示，該陣列由介於零與一之間的三個數字組成，加起來最多為 1：

```
"split_rate": [0.7, 0.1, 0.2]
```

如果您未提供選用 `split_rate` 欄位，則預設估計值為 `[0.9, 0.1, 0.0]`。

# neptune\$1ml 中的功能欄位
<a name="machine-learning-neptune_ml-features"></a>

屬性值和 RDF 常值有不同的格式和資料類型。若要在機器學習中實現良好的效能，必須將這些值轉換為稱為*特徵*的數值編碼。

Neptune ML 會執行特徵擷取和編碼，做為資料匯出和資料處理步驟的一部分，如 [Neptune ML 中的特徵編碼](machine-learning-feature-encoding.md) 中所述。

對於屬性圖資料集，匯出程序會自動針對字串屬性和包含多個值的數值屬性推斷 `auto` 特徵。對於包含單一值的數值屬性，它會推斷 `numerical` 特徵。對於日期屬性，它會推斷 `datetime` 特徵。

如果您想要覆寫自動推斷的特徵規格，或為屬性新增儲存貯體數值、TF-IDF、FastText 或 SBERT 規格，您可以使用特徵欄位控制特徵編碼。

**注意**  
您只能使用 `features` 欄位來控制屬性圖資料的特徵規格，而不能控制 RDF 資料的特徵規格。

對於自由格式的文字，Neptune ML 可以使用數個不同的模型，將字串屬性值中的記號序列轉換為固定大小的實數值向量：
+ [`text_fasttext`](machine-learning-feature-encoding.md#machine-learning-fasttext-features) – 使用 [fastText](https://fasttext.cc/) 編碼。對於使用 fastText 所支援五種語言的一種且只有一種的特徵，這是建議的編碼方式。
+ [`text_sbert`](machine-learning-feature-encoding.md#machine-learning-sbert-features) – 使用[句子 BERT](https://www.sbert.net/docs/pretrained_models.html#sentence-embedding-models) (SBERT) 編碼模型。對於 `text_fasttext` 不支援的文字，這是建議的編碼方式。
+ [`text_word2vec`](machine-learning-feature-encoding.md#machine-learning-word2vec-features) – 使用 [Google](https://code.google.com/archive/p/word2vec/) 最初發佈的 [Word2VEC](https://wikipedia.org/wiki/Word2vec) 演算法來編碼文字。Word2Vec 只支援英文。
+ [`text_tfidf`](machine-learning-feature-encoding.md#machine-learning-tfidf-features) – 使用[詞頻-逆向文件頻率](https://wikipedia.org/wiki/Tf-idf) (TF-IDF) 向量化程式來編碼文字。TF-IDF 編碼支援其他編碼不支援的統計特徵。

`features` 欄位包含節點屬性特徵的 JSON 陣列。陣列中的物件可以包含下列欄位：

**Contents**
+ [節點](#machine-learning-neptune_ml-features-node)
+ [節點](#machine-learning-neptune_ml-features-edge)
+ [屬性](#machine-learning-neptune_ml-features-property)
+ [type](#machine-learning-neptune_ml-feature-types)
+ [norm](#machine-learning-neptune_ml-features-norm)
+ [語言](#machine-learning-neptune_ml-features-language)
+ [max\$1length](#machine-learning-neptune_ml-features-max_length)
+ [separator](#machine-learning-neptune_ml-features-separator)
+ [range](#machine-learning-neptune_ml-features-range)
+ [bucket\$1cnt](#machine-learning-neptune_ml-features-bucket_cnt)
+ [slide\$1window\$1size](#machine-learning-neptune_ml-features-slide_window_size)
+ [imputer](#machine-learning-neptune_ml-features-imputer)
+ [max\$1features](#machine-learning-neptune_ml-features-max_features)
+ [min\$1df](#machine-learning-neptune_ml-features-min_df)
+ [ngram\$1range](#machine-learning-neptune_ml-features-ngram_range)
+ [datetime\$1parts](#machine-learning-neptune_ml-features-datetime_parts)

## 功能中的節點欄位
<a name="machine-learning-neptune_ml-features-node"></a>

`node` 欄位指定特徵頂點的屬性圖標籤。例如：

```
  "node": "Person"
```

如果一個頂點有多個標籤，請使用陣列來包含它們。例如：

```
  "node": ["Admin", "Person"]
```

## 功能中的邊緣欄位
<a name="machine-learning-neptune_ml-features-edge"></a>

`edge` 欄位指定特徵邊緣的邊緣類型。邊緣類型由陣列組成，此陣列包含來源頂點的屬性圖標籤、邊緣的屬性圖標籤，以及目的地頂點的屬性圖標籤。指定邊緣特徵時，您必須提供全部三個值。例如：

```
  "edge": ["User", "reviewed", "Movie"]
```

如果邊緣類型的來源或目標頂點有多個標籤，請使用另一個陣列來包含它們。例如：

```
  "edge": [["Admin", "Person"]. "edited", "Post"]
```

## 功能中的屬性欄位
<a name="machine-learning-neptune_ml-features-property"></a>

使用屬性參數來指定由 `node` 參數所識別之頂點的屬性。例如：

```
  "property" : "age"
```

## 功能的類型欄位可能值
<a name="machine-learning-neptune_ml-feature-types"></a>

`type` 參數指定要定義的特徵類型。例如：

```
  "type": "bucket_numerical"
```

**`type` 參數的可能值**
+ **`"auto"`** – 指定 Neptune ML 應該自動偵測屬性類型並套用適當的特徵編碼。`auto` 特徵也可以具有一個選用 `separator` 欄位。

  請參閱 [Neptune ML 中的自動特徵編碼](machine-learning-feature-encoding.md#machine-learning-auto-encoding)。
+ **`"category"`** – 此特徵編碼將屬性值表示為數個類別的其中一個。換句話說，此特徵可以採取一個或多個離散值。`category` 特徵也可以具有一個選用 `separator` 欄位。

  請參閱 [Neptune ML 中的類別特徵](machine-learning-feature-encoding.md#machine-learning-categorical-features)。
+ **`"numerical"`** – 此特徵編碼會將數值屬性值表示為連續間隔中的數字，其中「大於」和「小於」都有意義。

   `numerical` 特徵也可以具有選用 `norm`、`imputer` 和 `separator` 欄位。

  請參閱 [Neptune ML 中的數值特徵](machine-learning-feature-encoding.md#machine-learning-numerical-features)。
+ **`"bucket_numerical"`** – 此特徵編碼會將數值屬性值分成一組*儲存貯體*或類別。

  例如，您可以將人們的年齡編碼為 4 個儲存貯體：小孩 (0-20)、年輕人 (20-40)、中年人 (40-60) 和長者 (60 歲以上)。

  `bucket_numerical` 特徵需要 `range` 和 `bucket_cnt` 欄位，也可以選擇性地包含 `imputer` 和/或 `slide_window_size` 欄位。

  請參閱 [Neptune ML 中的儲存貯體數值特徵](machine-learning-feature-encoding.md#machine-learning-bucket_numerical-features)。
+ **`"datetime"`** – 此特徵編碼會將 datetime 屬性值表示為下列類別特徵的陣列：年、月、工作日和小時。

  可以使用 `datetime_parts` 參數消除這四個類別中的一個或多個類別。

  請參閱 [Neptune ML 中的日期時間特徵](machine-learning-feature-encoding.md#machine-learning-datetime-features)。
+ **`"text_fasttext"`** – 此特徵編碼會使用 [fastText](https://fasttext.cc/) 模型，將由句子或自由格式文字組成的屬性值轉換為數值向量。它支持五種語言，即英文 (`en`)、中文 (`zh`)、北印度文 (`hi`)、西班牙文 (`es`) 和法文 (`fr`)。對於這五種語言中任何一種的文字屬性值，`text_fasttext` 是建議的編碼方式。不過，它無法處理同一句子包含多種語言單字的情況。

  對於 fastText 所支援語言以外的其他語言，請使用 `text_sbert` 編碼。

  假設，如果您的屬性值文字字串長度超過 120 個記號，請使用 `max_length` 欄位來限制 `"text_fasttext"` 編碼的每個字串中的記號數目。

  請參閱 [Neptune ML 中文字屬性值的 *fastText* 編碼](machine-learning-feature-encoding.md#machine-learning-fasttext-features)。
+ **`"text_sbert"`** – 此編碼會使用[句子 BERT](https://www.sbert.net/docs/pretrained_models.html#sentence-embedding-models) (SBERT) 模型，將文字屬性值轉換為數值向量。Neptune 支援兩種 SBERT 方法，即 `text_sbert128`，這是預設值，如果您僅指定 `text_sbert` 和 `text_sbert512` 的話。它們之間的差異在於進行編碼的文字屬性中的記號數目上限。`text_sbert128` 編碼僅會編碼前 128 個記號，而 `text_sbert512` 最多可編碼 512 個記號。因此，使用 `text_sbert512` 可能比 `text_sbert128` 需要更多的處理時間。這兩種方法都比 `text_fasttext` 慢。

  `text_sbert*` 方法支援多種語言，而且可以編碼包含多種語言的句子。

  請參閱 [Neptune ML 中文字特徵的句子 BERT (SBERT) 編碼](machine-learning-feature-encoding.md#machine-learning-sbert-features)。
+ **`"text_word2vec"`** – 此編碼會使用 [Word2VEC](https://wikipedia.org/wiki/Word2vec) 演算法，將文字屬性值轉換為數值向量。它僅支援英文。

  請參閱 [Neptune ML 中文字特徵的 Word2Vec 編碼](machine-learning-feature-encoding.md#machine-learning-word2vec-features)。
+ **`"text_tfidf"`** – 此編碼會使用[詞頻-逆向文件頻率](https://wikipedia.org/wiki/Tf-idf) (TF-IDF) 向量化程式，將文字屬性值轉換為數值向量。

  您可以使用 `ngram_range` 欄位、`min_df` 欄位和 `max_features` 欄位來定義 `text_tfidf` 特徵編碼的參數。

  請參閱 [Neptune ML 中文字特徵的 TF-IDF 編碼](machine-learning-feature-encoding.md#machine-learning-tfidf-features)。
+ **`"none"`** – 使用 `none` 類型會導致不發生任何特徵編碼。反而會剖析並儲存原始屬性值。

  僅在您計劃執行自己的自訂特徵編碼，做為自訂模型訓練的一部分時，才會使用 `none`。

## 標準欄位
<a name="machine-learning-neptune_ml-features-norm"></a>

數值特徵需要此欄位。它會指定要在數值上使用的標準化方法：

```
"norm": "min-max"
```

支援以下標準化方法：
+ **「min-max」** – 透過從中減去最小值，然後將其除以最大值與最小值之間的差值來標準化每個值。
+ **「standard」** – 將每個值除以所有值的總和來標準化這些值。
+ **「none」** – 不要在編碼期間標準化數值。

請參閱 [Neptune ML 中的數值特徵](machine-learning-feature-encoding.md#machine-learning-numerical-features)。

## 語言欄位
<a name="machine-learning-neptune_ml-features-language"></a>

語言欄位會指定文字屬性值中使用的語言。它的用法取決於文字編碼方法：
+ 對於 [`text_fasttext`](machine-learning-feature-encoding.md#machine-learning-fasttext-features) 編碼，此欄位是必要的，且必須指定下列其中一種語言：
  + `en` (英文)
  + `zh` (中文)
  + `hi` (北印度文)
  + `es` (西班牙文)
  + `fr` (法文)
+ 對於 [`text_sbert`](machine-learning-feature-encoding.md#machine-learning-fasttext-features) 編碼，不會使用此欄位，因為 SBERT 編碼是多語系的。
+ 對於 [`text_word2vec`](machine-learning-feature-encoding.md#machine-learning-word2vec-features) 編碼，此欄位是選用的，因為 `text_word2vec` 僅支援英文。如果存在，它必須指定英文模型的名稱：

  ```
  "language" : "en_core_web_lg"
  ```
+ 對於 [`text_tfidf`](machine-learning-feature-encoding.md#machine-learning-tfidf-features) 編碼，不會使用此欄位。

## max\$1length 欄位
<a name="machine-learning-neptune_ml-features-max_length"></a>

`max_length` 欄位是 `text_fasttext` 特徵的選用欄位，其中指定將編碼之輸入文字特徵中的記號數目上限。長度超過 `max_length` 的輸入文字會被截斷。例如，將 max\$1length 設定為 128，表示將忽略文字序列中第 128 之後的任何記號：

```
"max_length": 128
```

## 分隔符號欄位
<a name="machine-learning-neptune_ml-features-separator"></a>

此欄位可選擇性地與 `category`、`numerical` 和 `auto` 特徵搭配使用。它會指定一個字元，其可以用來將屬性值分成多個類別值或數值：

```
"separator": ";"
```

僅在屬性將多個分隔值儲存在單一字串 (例如 `"Actor;Director"` 或 `"0.1;0.2"`) 中時，才會使用 `separator` 欄位。

請參閱[類別功能](machine-learning-feature-encoding.md#machine-learning-categorical-features)、[數值特徵](machine-learning-feature-encoding.md#machine-learning-numerical-features)和[自動編碼](machine-learning-feature-encoding.md#machine-learning-auto-encoding)。

## 範圍欄位
<a name="machine-learning-neptune_ml-features-range"></a>

`bucket_numerical` 特徵需要此欄位。它會指定要分成儲存貯體的數值範圍，格式為 `[lower-bound, upper-bound]`：

```
"range" : [20, 100]
```

如果屬性值小於下限，則會將其指派給第一個儲存貯體，或者如果它大於上限，則會將其指派給最後一個儲存貯體。

請參閱 [Neptune ML 中的儲存貯體數值特徵](machine-learning-feature-encoding.md#machine-learning-bucket_numerical-features)。

## bucket\$1cnt 欄位
<a name="machine-learning-neptune_ml-features-bucket_cnt"></a>

`bucket_numerical` 特徵需要此欄位。它會指定由 `range` 參數定義的數值範圍應分成的儲存貯體數目：

```
"bucket_cnt": 10
```

請參閱 [Neptune ML 中的儲存貯體數值特徵](machine-learning-feature-encoding.md#machine-learning-bucket_numerical-features)。

## slide\$1window\$1size 欄位
<a name="machine-learning-neptune_ml-features-slide_window_size"></a>

此欄位可選擇性地搭配 `bucket_numerical` 特徵使用，以將值指派給多個儲存貯體：

```
"slide_window_size": 5
```

滑動視窗的運作方式是 Neptune ML 採取視窗大小 **`s`**，並將屬性的每個數值 **`v`** 轉換為從 ` v - s/2 ` 到 ` v + s/2 ` 的範圍。然後，此值會指定給範圍重疊的每個儲存貯體。

請參閱 [Neptune ML 中的儲存貯體數值特徵](machine-learning-feature-encoding.md#machine-learning-bucket_numerical-features)。

## imputer 欄位
<a name="machine-learning-neptune_ml-features-imputer"></a>

此欄位可選擇搭配 `numerical` 和 `bucket_numerical` 特徵使用，以提供填入缺失值的插補技術：

```
"imputer": "mean"
```

支援的插補技術如下：
+ `"mean"`
+ `"median"`
+ `"most-frequent"`

如果您未包含 imputer 參數，資料預先處理會在遇到缺失值時停止並結束。

請參閱 [Neptune ML 中的數值特徵](machine-learning-feature-encoding.md#machine-learning-numerical-features) 和 [Neptune ML 中的儲存貯體數值特徵](machine-learning-feature-encoding.md#machine-learning-bucket_numerical-features)。

## max\$1features 欄位
<a name="machine-learning-neptune_ml-features-max_features"></a>

此欄位是 `text_tfidf` 特徵可選擇性地用來指定要編碼的詞數上限：

```
"max_features": 100
```

設定為 100 會導致 TF-IDF 向量化程式只編碼 100 個最常見的字詞。如果未包含 `max_features`，則預設值為 5,000。

請參閱 [Neptune ML 中文字特徵的 TF-IDF 編碼](machine-learning-feature-encoding.md#machine-learning-tfidf-features)。

## min\$1df 欄位
<a name="machine-learning-neptune_ml-features-min_df"></a>

`text_tfidf` 特徵可選擇性地使用此欄位，來指定要編碼之字詞的文件頻率上限：

```
"min_df": 5
```

設定 5 表示字詞必須出現在至少 5 個不同的屬性值中，才能進行編碼。

如果您未包含 `min_df` 參數，預設值為 `2`。

請參閱 [Neptune ML 中文字特徵的 TF-IDF 編碼](machine-learning-feature-encoding.md#machine-learning-tfidf-features)。

## ngram\$1range 欄位
<a name="machine-learning-neptune_ml-features-ngram_range"></a>

`text_tfidf` 特徵可選擇性地使用此欄位，指定應將單字或記號的哪些大小序列視為要編碼的潛在個別字詞：

```
"ngram_range": [2, 4]
```

值 `[2, 4]` 指定 2、3 和 4 個單字的序列應被視為潛在的個別字詞。

如果您沒有明確設定 `ngram_range`，則預設值為 `[1, 1]`，這表示只有單一單字或記號會被視為要編碼的字詞。

請參閱 [Neptune ML 中文字特徵的 TF-IDF 編碼](machine-learning-feature-encoding.md#machine-learning-tfidf-features)。

## datetime\$1parts 欄位
<a name="machine-learning-neptune_ml-features-datetime_parts"></a>

`datetime` 特徵可選擇性地使用此欄位，來指定要以分類方式編碼 datetime 值的哪些部分：

```
"datetime_parts": ["weekday", "hour"]
```

如果您未包含 `datetime_parts`，Neptune ML 預設會編碼 datetime 值的年、月、工作日和小時部分。值 `["weekday", "hour"]` 表示只有 datetime 值的工作日和小時應在特徵中進行分類編碼。

如果其中一個部分在訓練集中沒有多個唯一值，則不會對其進行編碼。

請參閱[Neptune ML 中的日期時間特徵](machine-learning-feature-encoding.md#machine-learning-datetime-features)。

# 在 additionalParams 中使用參數來調校模型訓練組態的範例
<a name="machine-learning-data-export-additionalParams-examples"></a>

 下列範例示範如何在屬性圖和 RDF 資料模型中使用「additionalParams」功能，為 Neptune ML 應用程式設定模型訓練程序的各個層面。這些範例涵蓋各種功能，包括指定training/validation/test資料的預設分割率、定義節點分類、迴歸和連結預測任務，以及設定不同的特徵類型，例如數值儲存貯體、文字內嵌、日期時間和分類資料。這些詳細組態可讓您根據特定資料和建模需求量身打造機器學習管道，釋放 Neptune ML 功能的完整潛力。

**Contents**
+ [使用 additionalParams 的屬性圖範例](#machine-learning-property-graph-additionalParams-examples)
  + [為模型訓練組態指定預設分割率](#machine-learning-property-graph-additionalParams-default-split-rate-example)
  + [為模型訓練組態指定節點分類任務](#machine-learning-property-graph-additionalParams-node-classification-example)
  + [為模型訓練組態指定多類別節點分類任務](#machine-learning-property-graph-additionalParams-multi-class-example)
  + [為模型訓練組態指定節點迴歸任務](#machine-learning-property-graph-additionalParams-node-regression-example)
  + [為模型訓練組態指定 edge-classification 任務](#machine-learning-property-graph-additionalParams-edge-classification-example)
  + [為模型訓練組態指定多類別邊緣分類任務](#machine-learning-property-graph-additionalParams-multi-edge-classification-example)
  + [為模型訓練組態指定邊緣迴歸](#machine-learning-property-graph-additionalParams-edge-regression-example)
  + [為模型訓練組態指定連結預測任務](#machine-learning-property-graph-additionalParams-link-prediction-example)
  + [指定數值儲存貯體特徵](#machine-learning-property-graph-additionalParams-numeric-bucket-example)
  + [指定 `Word2Vec` 特徵](#machine-learning-property-graph-additionalParams-word2vec-example)
  + [指定 `FastText` 特徵](#machine-learning-property-graph-additionalParams-fasttext-example)
  + [指定 `Sentence BERT` 特徵](#machine-learning-property-graph-additionalParams-sbert-example)
  + [指定 `TF-IDF` 特徵](#machine-learning-property-graph-additionalParams-tf-idf-example)
  + [指定 `datetime` 特徵](#machine-learning-property-graph-additionalParams-datetime-example)
  + [指定 `category` 特徵](#machine-learning-property-graph-additionalParams-category-example)
  + [指定 `numerical` 特徵](#machine-learning-property-graph-additionalParams-numerical-example)
  + [指定 `auto` 特徵](#machine-learning-property-graph-additionalParams-auto-example)
+ [使用 `additionalParams` 的 RDF 範例](#machine-learning-RDF-additionalParams-examples)
  + [為模型訓練組態指定預設分割率](#machine-learning-RDF-additionalParams-default-split-rate-example)
  + [為模型訓練組態指定節點分類任務](#machine-learning-RDF-additionalParams-node-classification-example)
  + [為模型訓練組態指定節點迴歸任務](#machine-learning-RDF-additionalParams-node-regression-example)
  + [為特定邊緣指定連結預測任務](#machine-learning-RDF-additionalParams-link-prediction-example)
  + [為所有邊緣指定連結預測任務](#machine-learning-RDF-additionalParams-link-prediction-example)

## 使用 additionalParams 的屬性圖範例
<a name="machine-learning-property-graph-additionalParams-examples"></a>

### 為模型訓練組態指定預設分割率
<a name="machine-learning-property-graph-additionalParams-default-split-rate-example"></a>

在下列範例中，`split_rate` 參數會設定模型訓練的預設分割率。如果未指定預設分割率，則訓練會使用 [0.9, 0.1, 0.0] 的值。您可以透過為每個目標指定 `split_rate`，覆寫每個目標上的預設值。

在下列範例中，`default split_rate` 欄位指示除非針對每個目標進行覆寫，否則應使用 `[0.7,0.1,0.2]` 的分割率：

```
  "additionalParams": {
  "neptune_ml": {
    "version": "v2.0",
    "split_rate": [0.7,0.1,0.2],
    "targets": [
      (...)
    ],
    "features": [
      (...)
    ]
  }
}
```

### 為模型訓練組態指定節點分類任務
<a name="machine-learning-property-graph-additionalParams-node-classification-example"></a>

若要指示哪個節點屬性包含標記的範例可供訓練用途，請使用 `"type" : "classification"` 將節點分類元素新增至 `targets` 陣列。如果想要覆寫預設分割率，請新增 `split_rate` 欄位。

在下列範例中，`node` 目標會指示應將每個 `Movie` 節點的 `genre` 屬性視為節點類別標籤。`split_rate` 值會覆寫預設分割率：

```
  "additionalParams": {
  "neptune_ml": {
    "version": "v2.0",
    "targets": [
      {
        "node": "Movie",
        "property": "genre",
        "type": "classification",
        "split_rate": [0.7,0.1,0.2]
      }
    ],
    "features": [
      (...)
    ]
  }
}
```

### 為模型訓練組態指定多類別節點分類任務
<a name="machine-learning-property-graph-additionalParams-multi-class-example"></a>

若要指示哪個節點屬性包含多個標記的範例可供訓練用途，請使用 `"type" : "classification"` 和 `separator` 將節點分類元素新增至目標陣列，來指定可以用來將目標屬性值分割為多個類別值的字元。如果想要覆寫預設分割率，請新增 `split_rate` 欄位。

在下列範例中，`node` 目標會指示應將每個 `Movie` 節點的 `genre` 屬性視為節點類別標籤。`separator` 欄位指示每個類型屬性包含多個分號分隔值：

```
  "additionalParams": {
  "neptune_ml": {
    "version": "v2.0",
    "targets": [
      {
        "node": "Movie",
        "property": "genre",
        "type": "classification",
        "separator": ";"
      }
    ],
    "features": [
      (...)
    ]
  }
}
```

### 為模型訓練組態指定節點迴歸任務
<a name="machine-learning-property-graph-additionalParams-node-regression-example"></a>

若要指示哪個節點屬性包含用於訓練用途的標記迴歸，請使用 `"type" : "regression"` 將節點迴歸元素新增至陣列。如果想要覆寫預設分割率，請新增 split\$1rate 欄位。

下列 `node` 目標指示應將每個 `Movie` 節點的 `rating` 屬性視為節點迴歸標籤。

```
    "additionalParams": {
  "neptune_ml": {
    "version": "v2.0",
    "targets": [
      {
        "node": "Movie",
        "property": "rating",
        "type" : "regression",
        "split_rate": [0.7,0.1,0.2]
      }
    ],
    "features": [
      ...
    ]
  }
}
```

### 為模型訓練組態指定 edge-classification 任務
<a name="machine-learning-property-graph-additionalParams-edge-classification-example"></a>

若要指示哪個邊緣屬性包含用於訓練用途的標記範例，請使用 `"type" : "regression"` 將邊緣元素新增至 `targets` 陣列。如果想要覆寫預設分割率，請新增 split\$1rate 欄位。

下列 `edge` 目標指示應將每個 `knows` 邊緣的 `metAtLocation` 屬性視為迴歸類別標籤：

```
  "additionalParams": {
  "neptune_ml": {
    "version": "v2.0",
    "targets": [
      {
        "edge": ["Person", "knows", "Person"],
        "property": "metAtLocation",
        "type": "classification"
      }
    ],
    "features": [
      (...)
    ]
  }
}
```

### 為模型訓練組態指定多類別邊緣分類任務
<a name="machine-learning-property-graph-additionalParams-multi-edge-classification-example"></a>

若要指示哪個邊緣屬性包含多個用於訓練用途的標記範例，請使用 `"type" : "classification"` 和 `separator` 欄位將邊緣元素新增至 `targets` 陣列，來指定用來將目標屬性值分割為多個類別值的字元。如果想要覆寫預設分割率，請新增 `split_rate` 欄位。

下列 `edge` 目標指示應將每個 `repliedTo` 邊緣的 `sentiment` 屬性視為迴歸類別標籤。分隔符號欄位會指示每個情緒屬性都包含多個逗號分隔值：

```
  "additionalParams": {
  "neptune_ml": {
    "version": "v2.0",
    "targets": [
      {
        "edge": ["Person", "repliedTo", "Message"],
        "property": "sentiment",
        "type": "classification",
        "separator": ","
      }
    ],
    "features": [
      (...)
    ]
  }
}
```

### 為模型訓練組態指定邊緣迴歸
<a name="machine-learning-property-graph-additionalParams-edge-regression-example"></a>

若要指示哪個邊緣屬性包含用於訓練用途的標記迴歸範例，請使用 `"type" : "regression"` 將 `edge` 元素新增至 `targets` 陣列。如果想要覆寫預設分割率，請新增 `split_rate` 欄位。

下列 `edge` 目標指示應將每個 `reviewed` 邊緣的 `rating` 屬性視為邊緣迴歸：

```
  "additionalParams": {
  "neptune_ml": {
    "version": "v2.0",
    "targets": [
      {
        "edge": ["Person", "reviewed", "Movie"],
        "property": "rating",
        "type" : "regression"
      }
    ],
    "features": [
      (...)
    ]
  }
}
```

### 為模型訓練組態指定連結預測任務
<a name="machine-learning-property-graph-additionalParams-link-prediction-example"></a>

若要指示應將哪些邊緣用於連結預測訓練用途，請使用 `"type" : "link_prediction"` 將邊緣元素新增至目標陣列。如果想要覆寫預設分割率，請新增 `split_rate` 欄位。

下列 `edge` 目標指示應該使用 `cites` 邊緣進行連結預測：

```
  "additionalParams": {
  "neptune_ml": {
    "version": "v2.0",
    "targets": [
      {
        "edge": ["Article", "cites", "Article"],
        "type" : "link_prediction"
      }
    ],
    "features": [
      (...)
    ]
  }
}
```

### 指定數值儲存貯體特徵
<a name="machine-learning-property-graph-additionalParams-numeric-bucket-example"></a>

您可以透過將 `"type": "bucket_numerical"` 新增至 `features` 陣列來為節點屬性指定數值資料特徵。

下列 `node` 特徵指示應將每個 `Person` 節點的 `age` 屬性視為數值儲存貯體特徵：

```
  "additionalParams": {
  "neptune_ml": {
    "targets": [
      ...
    ],
    "features": [
      {
        "node": "Person",
        "property": "age",
        "type": "bucket_numerical",
        "range": [1, 100],
        "bucket_cnt": 5,
        "slide_window_size": 3,
        "imputer": "median"
      }
    ]
  }
}
```

### 指定 `Word2Vec` 特徵
<a name="machine-learning-property-graph-additionalParams-word2vec-example"></a>

您可以透過將 `"type": "text_word2vec"` 新增至 `features` 陣列來為節點屬性指定 `Word2Vec` 特徵。

下列 `node` 特徵指示應將每個 `Movie` 節點的 `description` 屬性視為 `Word2Vec` 特徵：

```
"additionalParams": {
  "neptune_ml": {
    "version": "v2.0",
    "targets": [
      ...
    ],
    "features": [
      {
        "node": "Movie",
        "property": "description",
        "type": "text_word2vec",
        "language": "en_core_web_lg"
      }
    ]
  }
}
```

### 指定 `FastText` 特徵
<a name="machine-learning-property-graph-additionalParams-fasttext-example"></a>

您可以透過將 `"type": "text_fasttext"` 新增至 `features` 陣列來為節點屬性指定 `FastText` 特徵。`language` 欄位為必要的，且必須指定下列其中一個語言代碼：
+ `en` (英文)
+ `zh` (中文)
+ `hi` (北印度文)
+ `es` (西班牙文)
+ `fr` (法文)

請注意，`text_fasttext` 編碼無法在特徵中一次處理多種語言。

下列 `node` 特徵指示應將每個 `Movie` 節點的法文 `description` 屬性視為 `FastText` 特徵：

```
"additionalParams": {
  "neptune_ml": {
    "version": "v2.0",
    "targets": [
      ...
    ],
    "features": [
      {
        "node": "Movie",
        "property": "description",
        "type": "text_fasttext",
        "language": "fr",
        "max_length": 1024
      }
    ]
  }
}
```

### 指定 `Sentence BERT` 特徵
<a name="machine-learning-property-graph-additionalParams-sbert-example"></a>

您可以透過將 `"type": "text_sbert"` 新增至 `features` 陣列來為節點屬性指定 `Sentence BERT` 特徵。您不需要指定語言，因為方法會使用多語系模型自動編碼文字特徵。

下列 `node` 特徵指示應將每個 `Movie` 節點的 `description` 屬性視為 `Sentence BERT` 特徵：

```
"additionalParams": {
  "neptune_ml": {
    "version": "v2.0",
    "targets": [
      ...
    ],
    "features": [
      {
        "node": "Movie",
        "property": "description",
        "type": "text_sbert128",
      }
    ]
  }
}
```

### 指定 `TF-IDF` 特徵
<a name="machine-learning-property-graph-additionalParams-tf-idf-example"></a>

您可以透過將 `"type": "text_tfidf"` 新增至 `features` 陣列來為節點屬性指定 `TF-IDF` 特徵。

下列 `node` 特徵指示應將每個 `Person` 節點的 `bio` 屬性視為 `TF-IDF` 特徵：

```
  "additionalParams": {
  "neptune_ml": {
    "version": "v2.0",
    "targets": [
      ...
    ],
    "features": [
      {
        "node": "Movie",
        "property": "bio",
        "type": "text_tfidf",
        "ngram_range": [1, 2],
        "min_df": 5,
        "max_features": 1000
      }
    ]
  }
}
```

### 指定 `datetime` 特徵
<a name="machine-learning-property-graph-additionalParams-datetime-example"></a>

匯出程序會自動推斷日期屬性的 `datetime` 特徵。不過，如果要限制用於 `datetime` 特徵的 `datetime_parts`，或覆寫特徵規格，以便將通常被視為 `auto` 特徵的屬性明確地視為 `datetime` 特徵，則您可以透過將特徵陣列新增至 `"type": "datetime"` 來執行此操作。

下列 `node` 特徵指示應將每個 `Post` 節點的 `createdAt` 屬性視為 `datetime` 特徵：

```
  "additionalParams": {
  "neptune_ml": {
    "version": "v2.0",
    "targets": [
      ...
    ],
    "features": [
      {
        "node": "Post",
        "property": "createdAt",
        "type": "datetime",
        "datetime_parts": ["month", "weekday", "hour"]
      }
    ]
  }
}
```

### 指定 `category` 特徵
<a name="machine-learning-property-graph-additionalParams-category-example"></a>

匯出程序會自動針對字串屬性和包含多個值的數值屬性推斷 `auto` 特徵。對於包含單一值的數值屬性，它會推斷 `numerical` 特徵。對於日期屬性，它會推斷 `datetime` 特徵。

如果您想要覆寫特徵規格，以便將屬性視為類別特徵，請將 `"type": "category"` 新增至特徵陣列。如果屬性包含多個值，請包括一個 `separator` 欄位。例如：

```
  "additionalParams": {
  "neptune_ml": {
    "version": "v2.0",
    "targets": [
      ...
    ],
    "features": [
      {
        "node": "Post",
        "property": "tag",
        "type": "category",
        "separator": "|"
      }
    ]
  }
}
```

### 指定 `numerical` 特徵
<a name="machine-learning-property-graph-additionalParams-numerical-example"></a>

匯出程序會自動針對字串屬性和包含多個值的數值屬性推斷 `auto` 特徵。對於包含單一值的數值屬性，它會推斷 `numerical` 特徵。對於日期屬性，它會推斷 `datetime` 特徵。

如果您想要覆寫特徵規格，以便將屬性視為 `numerical` 特徵，請將 `"type": "numerical"` 新增至特徵陣列。如果屬性包含多個值，請包括一個 `separator` 欄位。例如：

```
  "additionalParams": {
  "neptune_ml": {
    "version": "v2.0",
    "targets": [
      ...
    ],
    "features": [
      {
        "node": "Recording",
        "property": "duration",
        "type": "numerical",
        "separator": ","
      }
    ]
  }
}
```

### 指定 `auto` 特徵
<a name="machine-learning-property-graph-additionalParams-auto-example"></a>

匯出程序會自動針對字串屬性和包含多個值的數值屬性推斷 `auto` 特徵。對於包含單一值的數值屬性，它會推斷 `numerical` 特徵。對於日期屬性，它會推斷 `datetime` 特徵。

如果您想要覆寫特徵規格，以便將屬性視為 `auto` 特徵，請將 `"type": "auto"` 新增至特徵陣列。如果屬性包含多個值，請包括一個 `separator` 欄位。例如：

```
  "additionalParams": {
  "neptune_ml": {
    "version": "v2.0",
    "targets": [
      ...
    ],
    "features": [
      {
        "node": "User",
        "property": "role",
        "type": "auto",
        "separator": ","
      }
    ]
  }
}
```

## 使用 `additionalParams` 的 RDF 範例
<a name="machine-learning-RDF-additionalParams-examples"></a>

### 為模型訓練組態指定預設分割率
<a name="machine-learning-RDF-additionalParams-default-split-rate-example"></a>

在下列範例中，`split_rate` 參數會設定模型訓練的預設分割率。如果未指定預設分割率，則訓練會使用 [0.9, 0.1, 0.0] 的值。您可以透過為每個目標指定 `split_rate`，覆寫每個目標上的預設值。

在下列範例中，`default split_rate` 欄位指示除非針對每個目標進行覆寫，否則應使用 `[0.7,0.1,0.2]` 的分割率：

```
  "additionalParams": {
  "neptune_ml": {
    "version": "v2.0",
    "split_rate": [0.7,0.1,0.2],
    "targets": [
      (...)
    ]
  }
}
```

### 為模型訓練組態指定節點分類任務
<a name="machine-learning-RDF-additionalParams-node-classification-example"></a>

若要指示哪個節點屬性包含訓練用途的標記範例，請使用 `"type" : "classification"` 將節點分類元素新增至 `targets` 陣列。新增節點欄位以指示目標節點的節點類型。新增 `predicate` 欄位以定義使用哪個常值資料做為目標節點的目標節點特徵。如果想要覆寫預設分割率，請新增 `split_rate` 欄位。

在下列範例中，`node` 目標會指示應將每個 `Movie` 節點的 `genre` 屬性視為節點類別標籤。`split_rate` 值會覆寫預設分割率：

```
  "additionalParams": {
  "neptune_ml": {
    "version": "v2.0",
    "targets": [
      {
        "node": "http://aws.amazon.com/neptune/csv2rdf/class/Movie",
        "predicate": "http://aws.amazon.com/neptune/csv2rdf/datatypeProperty/genre",
        "type": "classification",
        "split_rate": [0.7,0.1,0.2]
      }
    ]
  }
}
```

### 為模型訓練組態指定節點迴歸任務
<a name="machine-learning-RDF-additionalParams-node-regression-example"></a>

若要指示哪個節點屬性包含用於訓練用途的標記迴歸，請使用 `"type" : "regression"` 將節點迴歸元素新增至陣列。新增 `node` 欄位以指示目標節點的節點類型。新增 `predicate` 欄位以定義使用哪個常值資料做為目標節點的目標節點特徵。如果想要覆寫預設分割率，請新增 `split_rate` 欄位。

下列 `node` 目標指示應將每個 `Movie` 節點的 `rating` 屬性視為節點迴歸標籤。

```
    "additionalParams": {
  "neptune_ml": {
    "version": "v2.0",
    "targets": [
      {
        "node": "http://aws.amazon.com/neptune/csv2rdf/class/Movie",
        "predicate": "http://aws.amazon.com/neptune/csv2rdf/datatypeProperty/rating",
        "type": "regression",
        "split_rate": [0.7,0.1,0.2]
      }
    ]
  }
}
```

### 為特定邊緣指定連結預測任務
<a name="machine-learning-RDF-additionalParams-link-prediction-example"></a>

若要指示應將哪些邊緣用於連結預測訓練用途，請使用 `"type" : "link_prediction"` 將邊緣元素新增至目標陣列。新增 `subject`、`predicate` 和 `object` 欄位以指定邊緣類型。如果想要覆寫預設分割率，請新增 `split_rate` 欄位。

下列 `edge` 目標指示將 `Directors` 連線至 `Movies` 的 `directed` 邊緣應該用於連結預測：

```
  "additionalParams": {
  "neptune_ml": {
    "version": "v2.0",
    "targets": [
      {
        "subject": "http://aws.amazon.com/neptune/csv2rdf/class/Director",
        "predicate": "http://aws.amazon.com/neptune/csv2rdf/datatypeProperty/directed",
        "object": "http://aws.amazon.com/neptune/csv2rdf/class/Movie",
        "type" : "link_prediction"
      }
    ]
  }
}
```

### 為所有邊緣指定連結預測任務
<a name="machine-learning-RDF-additionalParams-link-prediction-example"></a>

若要指示應將所有邊緣用於連結預測訓練用途，請使用 `"type" : "link_prediction"` 將 `edge` 元素新增至目標陣列。請不要新增 `subject`、`predicate` 或 `object` 欄位。如果想要覆寫預設分割率，請新增 `split_rate` 欄位。

```
  "additionalParams": {
  "neptune_ml": {
    "version": "v2.0",
    "targets": [
      {
        "type" : "link_prediction"
      }
    ]
  }
}
```

# 處理從 Neptune 匯出用於訓練的圖形資料
<a name="machine-learning-on-graphs-processing"></a>

資料處理步驟會取得匯出程序所建立的 Neptune 圖形資料，並建立 [Deep Graph Library (DGL)](https://www.dgl.ai/) 在訓練期間使用的資訊。這包括執行各種資料對應和轉換：
+ 解析節點和邊緣以建構 DGL 所需的圖形和 ID 對應檔案。
+ 將節點和邊緣屬性轉換為 DGL 所需的節點和邊緣特徵。
+ 將資料分割為訓練、驗證和測試集。

## 管理 Neptune ML 的資料處理步驟
<a name="machine-learning-on-graphs-processing-managing"></a>

在從 Neptune 匯出了您要用於模型訓練的資料之後，您可以使用 `curl` (或 `awscurl`) 命令啟動資料處理工作，如下所示：

```
curl \
  -X POST https://(your Neptune endpoint)/ml/dataprocessing \
  -H 'Content-Type: application/json' \
  -d '{
        "inputDataS3Location" : "s3://(Amazon S3 bucket name)/(path to your input folder)",
        "id" : "(a job ID for the new job)",
        "processedDataS3Location" : "s3://(S3 bucket name)/(path to your output folder)",
        "configFileName" : "training-job-configuration.json"
      }'
```

如何使用此命令的詳細資訊會在 [dataprocessing 命令](machine-learning-api-dataprocessing.md) 中加以說明，伴隨如何取得執行中工作狀態、如何停止執行中工作，以及如何列出所有執行中工作的相關資訊。

## 處理 Neptune ML 的更新圖形資料
<a name="machine-learning-on-graphs-processing-updated"></a>

您也可以將 `previousDataProcessingJobId` 提供給 API，以確保新的資料處理工作使用與先前工作相同的處理方法。當您想要透過對新資料重新訓練舊模型，或對新資料上重新計算模型成品，以在 Neptune 中取得更新圖形資料的預測時，這是必要的。

您可以使用 `curl` (或 `awscurl`) 命令來執行此操作，如下所示：

```
curl \
  -X POST https://(your Neptune endpoint)/ml/dataprocessing \
  -H 'Content-Type: application/json' \
  -d '{ "inputDataS3Location" : "s3://(Amazon S3 bucket name)/(path to your input folder)",
        "id" : "(a job ID for the new job)",
        "processedDataS3Location" : "s3://(Amazon S3 bucket name)/(path to your output folder)",
        "previousDataProcessingJobId", "(the job ID of the previous data-processing job)"}'
```

將 `previousDataProcessingJobId` 參數值設定為對應至訓練模型之先前資料處理工作的工作 ID。

**注意**  
目前不支援更新圖形中的節點刪除。如果節點已在更新圖形中移除，您必須啟動全新的資料處理工作，而不是使用 `previousDataProcessingJobId`。

# Neptune ML 中的特徵編碼
<a name="machine-learning-feature-encoding"></a>

屬性值有不同的格式和資料類型。若要在機器學習中實現良好的效能，必須將這些值轉換為稱為*特徵*的數值編碼。

Neptune ML 會使用這裡描述的特徵編碼技術，執行特徵擷取和編碼，做為資料匯出和資料處理步驟的一部分。

**注意**  
如果您計劃在自訂模型實作中實作自己的特徵編碼，則可以選取 `none` 做為特徵編碼類型，來停用資料預先處理階段中的自動特徵編碼。然後，不會對該節點或邊緣屬性進行任何特徵編碼，而是剖析原始屬性值並將其儲存在字典中。資料預先處理仍會從匯出的資料集建立 DGL 圖形，但是建構的 DGL 圖形沒有預先處理的訓練特徵。  
僅在您計劃執行自訂特徵編碼，做為自訂模型訓練的一部分時，才應使用此選項。如需詳細資訊，請參閱 [Neptune ML 中的自訂模型](machine-learning-custom-models.md)。

## Neptune ML 中的類別特徵
<a name="machine-learning-categorical-features"></a>

可以從可能值的固定清單中獲得一個或多個不同值的屬性，就是類別特徵。在 Neptune ML 中，類別特徵會使用[獨熱編碼](https://en.wikipedia.org/wiki/One-hot)進行編碼。以下範例顯示了不同食物的屬性名稱如何根據其類別進行獨熱編碼：

```
    Food        Veg.   Meat   Fruit    Encoding
   ---------    ----   ----   -----    --------
    Apple         0      0      1         001
    Chicken       0      1      0         010
    Broccoli      1      0      0         100
```

**注意**  
任何類別特徵中的類別數目上限為 100。如果一個屬性具有超過 100 種類別的值，則僅會將其中最常見的 99 個放置在不同的類別中，其餘則會放置在名為 `OTHER` 的特殊類別中。

## Neptune ML 中的數值特徵
<a name="machine-learning-numerical-features"></a>

其值為實數的任何屬性都可以編碼為 Neptune ML 中的數值特徵。數值特徵會使用浮點數進行編碼。

您可以指定要在編碼數值特徵時使用的資料標準化方法，如下所示：`"norm": "normalization technique"`。支援以下標準化技術：
+ **「none」** – 不要在編碼期間標準化數值。
+ **「min-max」** – 透過從中減去最小值，然後將其除以最大值與最小值之間的差值來標準化每個值。
+ **「standard」** – 將每個值除以所有值的總和來標準化這些值。

## Neptune ML 中的儲存貯體數值特徵
<a name="machine-learning-bucket_numerical-features"></a>

您可以將數值壓縮為類別，而不是使用原始數字表示數值屬性。例如，您可以將人們的年齡分成兒童 (0-20 歲)、年輕人 (20-40 歲)、中年人 (40-60 歲) 和老年人 (從 60 歲開始)。使用這些數值儲存貯體，您可以將數值屬性轉換為一種類別特徵。

在 Neptune ML 中，您可能會導致數值屬性編碼為儲存貯體數值特徵。您必須提供兩個項目：
+ 格式為 ` "range": [a, b] ` 的數值範圍，其中 `a` 和 `b` 是整數。
+ 格式為 ` "bucket_cnt": c ` 的儲存貯體計數，其中 `c` 是儲存貯體的數目，也是一個整數。

然後，Neptune ML 會將每個儲存貯體的大小計算為 ` ( b - a ) / c `，並將每個數值編碼為其落入的任何儲存貯體的數目。任何小於 `a` 的值都會被視為屬於第一個儲存貯體，而任何大於 `b` 的值都會被視為屬於最後一個儲存貯體。

您也可以選擇性地使數值落入多個儲存貯體，方法是指定滑動視窗大小，如下所示：` "slide_window_size": s `，其中 `s` 是一個數字。Neptune ML 接著會將屬性的每個數值 `v` 轉換為從 ` v - s/2 ` 到 ` v + s/2 ` 的範圍，並將值 `v` 指派給範圍涵蓋的每個儲存貯體。

最後，您還可以選擇性地提供一種為數值特徵和儲存貯體數值特徵填入缺失值的方法。您可以使用 ` "imputer": "imputation technique "` 執行此操作，其中插補技術是 `"mean"`、`"median"` 或 `"most-frequent"` 之一。如果您未指定 imputer，缺失值可能會導致處理停止。

## Neptune ML 中的文字特徵編碼
<a name="machine-learning-text-features"></a>

對於自由格式的文字，Neptune ML 可以使用數個不同的模型，將屬性值字串中的記號序列轉換為固定大小的實數值向量：
+ [`text_fasttext`](#machine-learning-fasttext-features) – 使用 [fastText](https://fasttext.cc/) 編碼。對於使用 fastText 所支援五種語言的一種且只有一種的特徵，這是建議的編碼方式。
+ [`text_sbert`](#machine-learning-sbert-features) – 使用[句子 BERT](https://www.sbert.net/docs/pretrained_models.html#sentence-embedding-models) (SBERT) 編碼模型。對於 `text_fasttext` 不支援的文字，這是建議的編碼方式。
+ [`text_word2vec`](#machine-learning-word2vec-features) – 使用 [Google](https://code.google.com/archive/p/word2vec/) 最初發佈的 [Word2VEC](https://wikipedia.org/wiki/Word2vec) 演算法來編碼文字。Word2Vec 只支援英文。
+ [`text_tfidf`](#machine-learning-tfidf-features) – 使用[詞頻-逆向文件頻率](https://wikipedia.org/wiki/Tf-idf) (TF-IDF) 向量化程式來編碼文字。TF-IDF 編碼支援其他編碼不支援的統計特徵。

### Neptune ML 中文字屬性值的 *fastText* 編碼
<a name="machine-learning-fasttext-features"></a>

Neptune ML 可以使用 [fastText](https://fasttext.cc/) 模型，將文字屬性值轉換為固定大小的實數值向量。對於 FastText 支援的五種語言中任何一種語言中的文字屬性值，這是建議的編碼方法：
+ `en` (英文)
+ `zh` (中文)
+ `hi` (北印度文)
+ `es` (西班牙文)
+ `fr` (法文)

請注意，fastText 無法處理包含多種語言單字的句子。

`text_fasttext` 方法可以選擇性地採取 `max_length` 欄位，指定將編碼之文字屬性值中的記號數上限，之後字串會遭截斷。當文字屬性值包含長字串時，這可以改善效能，因為如果未指定 `max_length`，fastText 會編碼所有記號，而不論字串長度為何。

這個範例指定法文電影標題使用 fastText 進貐編碼：

```
{
    "file_name" : "nodes/movie.csv",
    "separator" : ",",
    "node" : ["~id", "movie"],
    "features" : [
      {
        "feature": ["title", "title", "text_fasttext"],
        "language": "fr",
        "max_length": 1024
      }
    ]
  }
```

### Neptune ML 中文字特徵的句子 BERT (SBERT) 編碼
<a name="machine-learning-sbert-features"></a>

Neptune ML 可以使用[句子 BERT](https://www.sbert.net/docs/pretrained_models.html#sentence-embedding-models) (SBERT) 模型，將字串屬性值中的記號序列轉換為固定大小的實數值向量。Neptune 支援兩種 SBERT 方法：`text_sbert128`，這是預設值，如果您僅指定 `text_sbert` 和 `text_sbert512` 的話。兩者之間的差異是編碼的文字屬性值字串的長度上限。`text_sbert128` 編碼會在編碼 128 個記號之後截斷文字字串，而 `text_sbert512` 會在編碼 512 個記號之後截斷文字字串。因此，`text_sbert512` 可能比 `text_sbert128` 需要更多的處理時間。這兩種方法都比 `text_fasttext` 慢。

SBERT 編碼是多語系，因此無需為您正要編碼的屬性值文字指定語言。SBERT 方法支援多種語言，而且可以編碼包含多種語言的句子。如果您要編碼的屬性值包含以 FastText 不支援的語言撰寫的文字，則 SBERT 是建議的編碼方法。

下列範例會指定影片標題編碼為 SBERT，最多可有 128 個記號：

```
{
    "file_name" : "nodes/movie.csv",
    "separator" : ",",
    "node" : ["~id", "movie"],
    "features" : [
      { "feature": ["title", "title", "text_sbert128"] }
    ]
  }
```

### Neptune ML 中文字特徵的 Word2Vec 編碼
<a name="machine-learning-word2vec-features"></a>

Neptune ML 可以將字串屬性值編碼為 Word2Vec 特徵 ([Word2Vec 演算法](https://wikipedia.org/wiki/Word2vec)最初是由 [Google](https://code.google.com/archive/p/word2vec/) 發布)。`text_word2vec` 方法會使用其中一個 [spaCy 訓練模型](https://spacy.io/models)，將字串中的記號編碼為密集向量。這只支援使用 [en\$1core\$1web\$1lg](https://spacy.io/models/en#en_core_web_lg) 模型的英文。

下列範例會指定影片標題使用 Word2VEC 進行編碼：

```
{
    "file_name" : "nodes/movie.csv",
    "separator" : ",",
    "node" : ["~id", "movie"],
    "features" : [
      {
        "feature": ["title", "title", "text_word2vec"],
        "language": "en_core_web_lg"
      }
    ]
  }
```

請注意，語言欄位是選用的，因為英文 `en_core_web_lg` 模型是 Neptune 支援的唯一模型。

### Neptune ML 中文字特徵的 TF-IDF 編碼
<a name="machine-learning-tfidf-features"></a>

Neptune ML 可以將文字屬性值編碼為 `text_tfidf` 特徵。這種編碼會使用[詞頻-逆向文件頻率](https://wikipedia.org/wiki/Tf-idf) (TF-IDF) 向量化程式，接著進行維數縮減操作，將文字中的單字序列轉換為數值向量。

[TF-IDF](https://en.wikipedia.org/wiki/Tf%E2%80%93idf) (詞頻 - 逆向文件頻率) 是旨在測量單字在文件集中有多重要的數值。它的計算方法是將單字在給定屬性值中出現的次數，除以其出現所在的此類屬性值的總數。

例如，如果在給定電影標題中出現兩次「kiss」一字 (例如，「kiss kiss bang bang」)，並且「kiss」出現在所有 4 部電影的標題中，則「kiss kiss bang bang」標題中「kiss」的 TF-IDF 值將是 ` 2 / 4 `。

最初建立的向量具有 ***d*** 維度，其中 ***d*** 是該類型之所有屬性值中獨特字詞的數目。維數縮減操作會使用隨機稀疏投影，將該數目減少至上限 (100)。然後，透過合併其中的所有 `text_tfidf` 特徵來產生圖形的詞彙。

您可以透過多種方式控制 TF-IDF 向量化程式：
+ **`max_features`**   –   使用 `max_features` 參數，您可以將 `text_tfidf` 特徵中的字詞數限制為最常用的字詞。例如，如果您將 `max_features` 設為 100，則只會包含前 100 個最常用的字詞。如果您未明確地設定它，則 `max_features` 的預設值為 5,000。
+ **`min_df`** – 使用 `min_df` 參數，您可以將 `text_tfidf` 特徵中的字詞數限制為至少具有所指定文件頻率的字詞。例如，如果將 `min_df` 設為 5，則只會使用出現在至少 5 個不同屬性值的字詞。如果您未明確地設定它，則 `min_df` 的預設值為 2。
+ **`ngram_range`** – `ngram_range` 參數決定要將哪些單字組合會被視為字詞。例如，如果您將 `ngram_range` 設為 `[2, 4]`，則將會在「kiss kiss bang bang」標題中找到以下 6 個字詞：
  + *2 字字詞*：「kiss kiss」、「kiss bang」和「bang bang」。
  + *3 字字詞*：「kiss kiss bang」和「kiss bang bang」。
  + *4 字字詞*：「kiss kiss bang bang」。

  `ngram_range` 的預設設定為 `[1, 1]`。

## Neptune ML 中的日期時間特徵
<a name="machine-learning-datetime-features"></a>

Neptune ML 可以將 `datetime` 屬性值的一部分編碼為類別特徵，方法是將它們轉換為[獨熱陣列](https://en.wikipedia.org/wiki/One-hot)。使用 `datetime_parts` 參數指定下列一或多個要編碼 `["year", "month", "weekday", "hour"]` 的部分：如果未設定 `datetime_parts`，預設為編碼所有四個部分。

例如，如果日期時間值的範圍橫越 2010 到 2012 年，則日期時間項目 `2011-04-22 01:16:34` 的四個部分如下：
+ **year** – `[0, 1, 0]`。

  由於跨度 (2010、2011 和 2012) 只有 3 年，因此獨熱陣列有三個項目，每年一個。
+ **month** – `[0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0]`。

  在這裡，獨熱陣列對於一年中的每個月都有一個項目。
+ **weekday** – `[0, 0, 0, 0, 1, 0, 0]`。

  ISO 8601 標準規定，星期一是一周的第一天，並且由於 2011 年 4 月 22 日是星期五，所以對應的獨熱工作日陣列在第五位置是熱的。
+ **hour** – `[0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]`。

  凌晨 1 點設定在 24 個成員組成的獨熱陣列中。

幾月幾日、分鐘和秒不會進行類別編碼。

如果有問題的總計 `datetime` 範圍僅包含一年內的日期，則不會編碼任何 `year` 陣列。

您可以使用 `imputer` 參數和可用於數值特徵的其中一個策略，來指定插補策略以填入缺失的 `datetime` 值。

## Neptune ML 中的自動特徵編碼
<a name="machine-learning-auto-encoding"></a>

您可以將 `auto` 設定為特徵編碼方法，而不是手動指定要用於圖形中屬性的特徵編碼方法。Neptune ML 接著會嘗試根據其基礎資料類型推斷每個屬性的最佳特徵編碼。

以下是 Neptune ML 在選取適當特徵編碼時使用的一些啟發式法：
+ 如果屬性只有數值，並且可以轉換為數值資料類型，則 Neptune ML 通常會將其編碼為數值。不過，如果內容的唯一值數目小於值總數的 10%，且這些唯一值的基數小於 100，則 Neptune ML 會使用類別編碼。
+ 如果屬性值可以轉換為 `datetime` 類型，則 Neptune ML 將它們編碼為 `datetime` 特徵。
+ 如果屬性值可以強制轉換為布林值 (1/0 或 True /False)，則 Neptune ML 會使用類別編碼。
+ 如果屬性是其中 10% 以上是唯一值的字串，且每個值的平均記號數大於或等於 3，則 Neptune ML 會推斷屬性類型為文字，並自動偵測正在使用的語言。如果偵測到的語言是 [fastText](#machine-learning-fasttext-features) 支援其中一種語言，即英文、中文、北印度文、西班牙語和法文，則 Neptune ML 會使用 `text_fasttext` 來編碼文字。否則，Neptune ML 會使用 [`text_sbert`](#machine-learning-sbert-features)。
+ 如果屬性是未分類為文字特徵的字串，則 Neptune ML 會假定它是類別特徵，並使用類別編碼。
+ 如果每個節點對於推斷為類別特徵的屬性都有自己的唯一值，Neptune ML 會從訓練圖表中捨棄屬性，因為它可能是不會對學習提供資訊的 ID。
+ 如果已知屬性包含有效的 Neptune 分隔符號，例如分號 (「;」)，則 Neptune ML 只能將該屬性視為 `MultiNumerical` 或 `MultiCategorical`。
  + Neptune ML 首先嘗試將值編碼為數值特徵。如果成功，Neptune ML 會使用數值編碼來建立數值向量特徵。
  + 否則，Neptune ML 會將這些值編碼為多重類別。
+ 如果 Neptune ML 無法推斷屬性值的資料類型，Neptune ML 會從訓練圖中捨棄屬性。

# 編輯訓練資料組態檔案
<a name="machine-learning-processing-training-config-file"></a>

Neptune 匯出程序會將 Neptune ML 資料從 Neptune 資料庫叢集匯出至 S3 儲存貯體。它將節點和邊緣分別匯出至 `nodes/` 和 `edges/` 資料夾。根據預設，它也會建立 JSON 訓練資料組態檔案，名為 `training-data-configuration.json`。此檔案包含有關圖形結構描述、其特徵類型、特徵轉換和標準化操作，以及分類或迴歸任務之目標特徵的資訊。

可能有些情況，您想要直接修改組態檔案。這類情況是，您想要變更特徵的處理方式或建構圖形的方式，而不需要在每次您想要針對您要解決的機器學習任務修改其規格時重新執行匯出。

**編輯訓練資料組態檔案**

1. **將檔案下載到您的本機電腦。**

   除非您在傳遞至匯出程序的 `additionalParams/neptune_ml` 參數中指定了一或多個具名工作，否則檔案將具有預設名稱，即 `training-data-configuration.json`。您可以使用類似這樣的 AWS CLI 命令來下載 檔案：

   ```
   aws s3 cp \
     s3://(your Amazon S3 bucket)/(path to your export folder)/training-data-configuration.json \
     ./
   ```

1. **使用文字編輯器編輯檔案。**

1. **上傳修改後的檔案。**使用如下所示的 CLI 命令，將修改過的檔案上傳回您下載的 Amazon S3 AWS 中的相同位置：

   ```
   aws s3 cp \
     training-data-configuration.json \
     s3://(your Amazon S3 bucket)/(path to your export folder)/training-data-configuration.json
   ```

# JSON 訓練資料組態檔案的範例
<a name="machine-learning-processing-training-config-file-example"></a>

以下是描述節點分類任務圖形的範例訓練資料組態檔案：

```
{
  "version" : "v2.0",
  "query_engine" : "gremlin",
  "graph" : [
    {
      "edges" : [
        {
          "file_name" : "edges/(movie)-included_in-(genre).csv",
          "separator" : ",",
          "source" : ["~from", "movie"],
          "relation" : ["", "included_in"],
          "dest" : [ "~to", "genre" ]
        },
        {
          "file_name" : "edges/(user)-rated-(movie).csv",
          "separator" : ",",
          "source" : ["~from", "movie"],
          "relation" : ["rating", "prefixname"], # [prefixname#value]
          "dest" : ["~to", "genre"],
          "features" : [
            {
              "feature" : ["rating", "rating", "numerical"],
              "norm" : "min-max"
            }
          ]
        }
      ],
      "nodes" : [
        {
          "file_name" : "nodes/genre.csv",
          "separator" : ",",
          "node" : ["~id", "genre"],
          "features" : [
            {
              "feature": ["name", "genre", "category"],
              "separator": ";"
            }
          ]
        },
        {
          "file_name" : "nodes/movie.csv",
          "separator" : ",",
          "node" : ["~id", "movie"],
          "features" : [
            {
              "feature": ["title", "title", "word2vec"],
              "language": ["en_core_web_lg"]
            }
          ]
        },
        {
          "file_name" : "nodes/user.csv",
          "separator" : ",",
          "node" : ["~id", "user"],
          "features" : [
            {
              "feature": ["age", "age", "numerical"],
              "norm" : "min-max",
              "imputation": "median",
            },
            {
              "feature": ["occupation", "occupation", "category"],
            }
          ],
          "labels" : [
            {
              "label": ["gender", "classification"],
              "split_rate" : [0.8, 0.2, 0.0]
            }
          ]
        }
      ]
    },
    "warnings" : [ ]
  ]
}
```

# JSON 訓練資料組態檔案的結構
<a name="machine-learning-processing-training-config-file-structure"></a>

訓練組態檔案是指匯出程序儲存在 `nodes/` 和 `edges/` 資料夾中的 CSV 檔案。

`nodes/` 下的每個檔案都會儲存具有相同屬性圖節點標籤之節點的相關資訊。節點檔案中的每一資料行都會儲存節點 ID 或節點屬性。檔案的第一行包含一個標頭，為每一資料行指定 `~id` 或屬性名稱。

`edges/` 下的每個檔案都會儲存具有相同屬性圖邊緣標籤之節點的相關資訊。節點檔案中的每一資料行都會儲存節點 ID、目的地節點 ID 或邊緣屬性。檔案的第一行包含一個標頭，為每一資料行指定 `~from`、`~to` 或屬性名稱。

訓練資料組態檔案具有三個最上層元素：

```
{
  "version" : "v2.0",
  "query_engine" : "gremlin",
  "graph" : [ ... ]
}
```
+ `version` – (字串) 正在使用的組態檔案版本。
+ `query_engine` – (字串) 用於匯出圖形資料的查詢語言。目前，僅「gremlin」是有效的。
+ `graph` – (JSON 陣列) 列出一或多個組態物件，其中包含每個將使用之節點和邊緣的模型參數。

  圖形陣列中的組態物件具有下一節所述的結構。

## `graph` 陣列中列出之組態物件的內容
<a name="machine-learning-graph-training-config-object"></a>

`graph` 陣列中的組態物件可以包含三個最上層節點：

```
    {
      "edges"    : [ ... ],
      "nodes"    : [ ... ],
      "warnings" : [ ... ],
    }
```
+ `edges` – (JSON 物件陣列) 每個 JSON 物件都會指定一組參數，以定義在模型處理和訓練期間將如何處理圖形中的邊緣。這僅會與 Gremlin 引擎搭配使用。
+ `nodes` – (JSON 物件陣列) 每個 JSON 物件都會指定一組參數，以定義在模型處理和訓練期間將如何處理圖形中的節點。這僅會與 Gremlin 引擎搭配使用。
+ `warnings` – (JSON 物件陣列) 每個物件都包含在資料匯出過程中產生的警告。

## `edges` 陣列中列出之邊緣組態物件的內容
<a name="machine-learning-graph-edges-config"></a>

`edges` 陣列中列出的邊緣組態物件可以包含下列最上層欄位：

```
      {
        "file_name" : "(path to a CSV file)",
        "separator" : "(separator character)",
        "source"    : ["(column label for starting node ID)", "(starting node type)"],
        "relation"  : ["(column label for the relationship name)", "(the prefix name for the relationship name)"],
        "dest"      : ["(column label for ending node ID)", "(ending node type)"],
        "features"  : [(array of feature objects)],
        "labels"    : [(array of label objects)]
      }
```
+ **`file_name`** – 字串，其會指定 CSV 檔案的路徑，而此檔案會儲存具有相同屬性圖標籤之邊緣的相關資訊。

  該檔案的第一行包含資料行標籤的標頭行。

  前兩個資料行標籤為 `~from` 和 `~to`。第一個資料行 (`~from` 資料行) 儲存邊緣起始節點的 ID，而第二個資料行 (`~to` 資料行) 儲存邊緣結束節點的 ID。

  標頭行中的其餘資料行標籤會為每個剩餘的資料行指定其值已匯出至該資料行的邊緣屬性名稱。
+ **`separator`** – 字串，其中包含分隔該 CSV 檔案中資料行的分隔符號。
+ **`source`** – JSON 陣列，其中包含兩個指定邊緣起始節點的字串。第一個字串包含起始節點 ID 儲存所在資料行的標頭名稱。第二個字串指定節點類型。
+ **`relation`** – JSON 陣列，其中包含兩個指定邊緣關聯類型的字串。第一個字串包含關聯名稱 (`relname`) 儲存所在資料行的標頭名稱。第二個字串包含關聯名稱 (`prefixname`) 的字首。

  完整的關聯類型由兩個字串組合而成，它們之間有一個連字號，如下所示：`prefixname-relname`。

  如果第一個字串是空的，則所有邊緣都具有相同的關聯類型，即 `prefixname` 字串。
+ **`dest`** – JSON 陣列，其中包含兩個指定邊緣結束節點的字串。第一個字串包含節點 ID 儲存所在資料行的標頭名稱。第二個字串指定節點類型。
+ **`features`** – 屬性值特徵物件的 JSON 陣列。每個屬性值特徵物件包含下列欄位：
  + **feature** – 由三個字串組成的 JSON 陣列。第一個字串包含資料行的標頭名稱，而該資料行包含屬性值。第二個字串包含特徵名稱。第三個字串包含特徵類型。
  + **norm** – (*選用*) 指定要套用至屬性值的標準化方法。

    
+ **`labels`** – 物件的 JSON 陣列。每個物件都會定義邊緣的目標特徵，並指定訓練和驗證階段應採取的邊緣比例。每個物件包含下列欄位：
  + **label** – 由兩個字串組成的 JSON 陣列。第一個字串包含資料行的標頭名稱，而該資料行包含目標特徵屬性值。第二個字串會指定下列其中一個目標任務類型：
    + `"classification"` – 邊緣分類任務。`label` 陣列中第一個字串所識別之資料行中提供的屬性值會被視為類別值。對於邊緣分類任務，`label` 陣列中的第一個字串不能是空的。
    + `"regression"` – 邊緣迴歸任務。`label` 陣列中第一個字串所識別之資料行中提供的屬性值會被視為數值。對於邊緣迴歸任務，`label` 陣列中的第一個字串不能是空的。
    + `"link_prediction"` – 連結預測任務。不需要任何屬性值。對於連結預測任務，會忽略 `label` 陣列中的第一個字串。
  + **`split_rate`** – JSON 陣列，其中包含三個介於零和一之間的數字，這些數字加起來最多為一，並代表訓練、驗證和測試階段將分別使用的節點比例估計值。可以定義此欄位或 `custom_split_filenames`，但不能同時定義這兩者。請參閱 [split\$1rate](machine-learning-neptune_ml-targets.md#machine-learning-property-graph-neptune_ml-targets-split_rate)。
  + **`custom_split_filenames`** – JSON 物件，其會指定用來定義訓練、驗證和測試母體之檔案的名稱。可以定義此欄位或 `split_rate`，但不能同時定義這兩者。如需詳細資訊，請參閱[自訂訓練-驗證-測試比例](#machine-learning-custom-stages-splits)。

## `nodes` 陣列中列出之節點組態物件的內容
<a name="machine-learning-graph-nodes-config"></a>

`nodes` 陣列中列出的節點組態物件可以包含下列欄位：

```
      {
        "file_name" : "(path to a CSV file)",
        "separator" : "(separator character)",
        "node"      : ["(column label for the node ID)", "(node type)"],
        "features"  : [(feature array)],
        "labels"    : [(label array)],
      }
```
+ **`file_name`** – 字串，其會指定 CSV 檔案的路徑，而此檔案會儲存具有相同屬性圖標籤之節點的相關資訊。

  該檔案的第一行包含資料行標籤的標頭行。

  第一個資料行標籤是 `~id`，且第一個資料行 (`~id` 資料行) 會儲存節點 ID。

  標頭行中的其餘資料行標籤會為每個剩餘的資料行指定其值已匯出至該資料行的節點屬性名稱。
+ **`separator`** – 字串，其中包含分隔該 CSV 檔案中資料行的分隔符號。
+ **`node`** – 包含兩個字串的 JSON 陣列。第一個字串包含儲存節點 ID 之資料行的標頭名稱。第二個字串指定圖形中的節點類型，該類型對應至節點的屬性圖標籤。
+ **`features`** – 節點特徵物件的 JSON 陣列。請參閱 [列示在節點或邊緣之 `features` 陣列中的特徵物件內容](#machine-learning-graph-node-features-config)。
+ **`labels`** – 節點標籤物件的 JSON 陣列。請參閱 [節點 `labels` 陣列中列出之節點標籤物件的內容](#machine-learning-graph-node-labels-config)。

## 列示在節點或邊緣之 `features` 陣列中的特徵物件內容
<a name="machine-learning-graph-node-features-config"></a>

節點 `features` 陣列中列出的節點特徵物件可以包含下列最上層欄位：
+ **`feature`** – 由三個字串組成的 JSON 陣列。第一個字串包含資料行的標頭名稱，而該資料行包含特徵的屬性值。第二個字串包含特徵名稱。

  第三個字串包含特徵類型。有效的特徵類型列示在 [功能的類型欄位可能值](machine-learning-neptune_ml-features.md#machine-learning-neptune_ml-feature-types) 中。
+ **`norm`** – 數值特徵需要此欄位。它會指定要在數值上使用的標準化方法。有效值為 `"none"`、`"min-max"` 和「standard」。如需詳細資訊，請參閱 [標準欄位](machine-learning-neptune_ml-features.md#machine-learning-neptune_ml-features-norm)。
+ **`language`** – 語言欄位會指定文字屬性值中使用的語言。它的用法取決於文字編碼方法：
  + 對於 [`text_fasttext`](machine-learning-feature-encoding.md#machine-learning-fasttext-features) 編碼，此欄位是必要的，且必須指定下列其中一種語言：
    + `en` (英文)
    + `zh` (中文)
    + `hi` (北印度文)
    + `es` (西班牙文)
    + `fr` (法文)

    不過，`text_fasttext` 一次無法處理多種語言。
  + 對於 [`text_sbert`](machine-learning-feature-encoding.md#machine-learning-fasttext-features) 編碼，不會使用此欄位，因為 SBERT 編碼是多語系的。
  + 對於 [`text_word2vec`](machine-learning-feature-encoding.md#machine-learning-word2vec-features) 編碼，此欄位是選用的，因為 `text_word2vec` 僅支援英文。如果存在，它必須指定英文模型的名稱：

    ```
    "language" : "en_core_web_lg"
    ```
  + 對於 [`tfidf`](machine-learning-feature-encoding.md#machine-learning-tfidf-features) 編碼，不會使用此欄位。
+ **`max_length`** – 此欄位是 [`text_fasttext`](machine-learning-feature-encoding.md#machine-learning-fasttext-features) 特徵的選用欄位，其中指定將編碼之輸入文字特徵中的記號數目上限。在到達 `max_length` 之後，會忽略輸入文字。例如，將 max\$1length 設定為 128，表示將忽略文字序列中第 128 個之後的任何記號：
+ **`separator`** – 此欄位可選擇性地與 `category`、`numerical` 和 `auto` 特徵搭配使用。它會指定一個字元，其可以用來將屬性值分成多個類別值或數值。

  請參閱 [分隔符號欄位](machine-learning-neptune_ml-features.md#machine-learning-neptune_ml-features-separator)。
+ **`range`** – `bucket_numerical` 特徵需要此欄位。它會指定要分成儲存貯體的數值範圍。

  請參閱 [範圍欄位](machine-learning-neptune_ml-features.md#machine-learning-neptune_ml-features-range)。
+ **`bucket_cnt`** – `bucket_numerical` 特徵需要此欄位。它會指定由 `range` 參數定義的數值範圍應分成的儲存貯體數目。

  請參閱 [Neptune ML 中的儲存貯體數值特徵](machine-learning-feature-encoding.md#machine-learning-bucket_numerical-features)。
+ **`slide_window_size`** – 此欄位可選擇性地與 `bucket_numerical` 特徵搭配使用，以將值指派給多個儲存貯體。

  請參閱 [slide\$1window\$1size 欄位](machine-learning-neptune_ml-features.md#machine-learning-neptune_ml-features-slide_window_size)。
+ **`imputer`** – 此欄位可選擇性地與 `numerical`、`bucket_numerical` 和 `datetime` 特徵搭配使用，以提供填入缺失值的插補技術。支援的插補技術為 `"mean"`、`"median"` 和 `"most_frequent"`。

  請參閱 [imputer 欄位](machine-learning-neptune_ml-features.md#machine-learning-neptune_ml-features-imputer)。
+ **`max_features`** – `text_tfidf` 特徵可選擇性地使用此欄位，來指定要編碼的字詞數上限。

  請參閱 [max\$1features 欄位](machine-learning-neptune_ml-features.md#machine-learning-neptune_ml-features-max_features)。
+ **`min_df`** – `text_tfidf` 特徵可選擇性地使用此欄位，來指定要編碼之字詞的文件頻率下限

  請參閱 [min\$1df 欄位](machine-learning-neptune_ml-features.md#machine-learning-neptune_ml-features-min_df)。
+ **`ngram_range`** – `text_tfidf` 特徵可選擇性地使用此欄位，來指定哪個範圍或多少單字或記號要被視為要編碼的潛在個別字詞

  請參閱 [ngram\$1range 欄位](machine-learning-neptune_ml-features.md#machine-learning-neptune_ml-features-ngram_range)。
+ **`datetime_parts`** – `datetime` 特徵可選擇性地使用此欄位，來指定日期時間值的哪些部分要進行類別編碼。

  請參閱 [datetime\$1parts 欄位](machine-learning-neptune_ml-features.md#machine-learning-neptune_ml-features-datetime_parts)。

## 節點 `labels` 陣列中列出之節點標籤物件的內容
<a name="machine-learning-graph-node-labels-config"></a>

節點 `labels` 陣列中列出的標籤物件會定義節點目標特徵，並會指定訓練、驗證和測試階段將使用的節點比例。每個物件可以包含下列欄位：

```
      {
        "label"      : ["(column label for the target feature property value)", "(task type)"],
        "split_rate" : [(training proportion), (validation proportion), (test proportion)],
        "custom_split_filenames" : {"train": "(training file name)", "valid": "(validation file name)", "test": "(test file name)"},
        "separator"  : "(separator character for node-classification category values)",
      }
```
+ **`label`** – 包含兩個字串的 JSON 陣列。第一個字串包含資料行的標頭名稱，而該資料行會儲存特徵的屬性值。第二個字串指定目標任務類型，其可以是：
  + `"classification"` – 節點分類任務。所指定資料行中的屬性值用來建立類別特徵。
  + `"regression"` – 節點迴歸任務。所指定資料行中的屬性值用來建立數值特徵。
+ **`split_rate`** – JSON 陣列，其中包含三個介於零和一之間的數字，這些數字加起來最多為一，並代表訓練、驗證和測試階段將分別使用的節點比例估計值。請參閱 [split\$1rate](machine-learning-neptune_ml-targets.md#machine-learning-property-graph-neptune_ml-targets-split_rate)。
+ **`custom_split_filenames`** – JSON 物件，其會指定用來定義訓練、驗證和測試母體之檔案的名稱。可以定義此欄位或 `split_rate`，但不能同時定義這兩者。如需詳細資訊，請參閱[自訂訓練-驗證-測試比例](#machine-learning-custom-stages-splits)。
+ **`separator`** – 包含分隔符號的字串，此分隔符號會分隔分類任務的類別特徵值。

**注意**  
如果未對邊緣和節點兩者提供標籤物件，則會自動假設任務為連結預測，且邊緣會隨機分割成 90% 用於訓練，10% 用於驗證。

## 自訂訓練-驗證-測試比例
<a name="machine-learning-custom-stages-splits"></a>

根據預設，Neptune ML 會使用 `split_rate` 參數，以使用此參數中定義的比例，將圖形隨機分割成訓練、驗證和測試母體。若要更精確地控制在這些不同母體中使用哪些實體，可以建立明確定義它們的檔案，然後[可以編輯訓練資料組態檔案](machine-learning-processing-training-config-file.md)，將這些索引檔案對應至母體。此對應是由 JSON 物件針對訓練組態檔案中的 [`custom_split_filesnames`](#custom_split_filenames) 索引鍵所指定。如果使用此選項，則必須為 `train` 和 `validation` 索引鍵提供檔案名稱，而對於 `test` 索引鍵則是選用的。

這些檔案的格式應符合 [Gremlin 資料格式](bulk-load-tutorial-format-gremlin.md#bulk-load-tutorial-format-gremlin-systemheaders)。特別是，對於節點層級任務，每個檔案應包含其 `~id` 標頭列出節點 ID 的資料行，而對於邊緣層級任務，檔案應分別指定 `~from` 和 `~to`，以指示邊緣的來源和目的地節點。這些檔案必須放置在與用於資料處理之匯出資料相同的 Amazon S3 位置 (請參閱：[`outputS3Path`](export-parameters.md#export-parameters-outputS3Path))。

對於屬性分類或迴歸任務，這些檔案可以選擇性地定義機器學習任務的標籤。在此情況下，檔案必須具有一個屬性資料行，其標頭名稱與[訓練資料組態檔案中定義的](#machine-learning-graph-node-labels-config)相同。如果在匯出的節點和邊緣檔案以及自訂分割檔案中都定義了屬性標籤，則會優先考慮自訂分割檔案。

# 使用 Neptune ML 訓練模型
<a name="machine-learning-on-graphs-model-training"></a>

在處理了您從 Neptune 匯出以用於模型訓練的資料之後，您可以使用如下的 `curl` (或 `awscurl`) 命令啟動模型訓練工作：

```
curl \
  -X POST https://(your Neptune endpoint)/ml/modeltraining
  -H 'Content-Type: application/json' \
  -d '{
        "id" : "(a unique model-training job ID)",
        "dataProcessingJobId" : "(the data-processing job-id of a completed job)",
        "trainModelS3Location" : "s3://(your Amazon S3 bucket)/neptune-model-graph-autotrainer"
      }'
```

如何使用此命令的詳細資訊會在 [modeltraining 指令](machine-learning-api-modeltraining.md) 中加以說明，伴隨如何取得執行中工作狀態、如何停止執行中工作，以及如何列出所有執行中工作的相關資訊。

您也可以提供一個 `previousModelTrainingJobId`，使用來自已完成 Neptune ML 模型訓練工作的資訊，以在新的訓練工作中加速超參數搜尋。在[對新圖形資料進行模型重新訓練](machine-learning-overview-evolving-data-incremental.md#machine-learning-overview-model-retraining)期間，以及在[對相同圖形資料進行增量訓練](machine-learning-overview-evolving-data-incremental.md#machine-learning-overview-incremental)期間，這樣做很有用。使用像這樣的命令：

```
curl \
  -X POST https://(your Neptune endpoint)/ml/modeltraining
  -H 'Content-Type: application/json' \
  -d '{
        "id" : "(a unique model-training job ID)",
        "dataProcessingJobId" : "(the data-processing job-id of a completed job)",
        "trainModelS3Location" : "s3://(your Amazon S3 bucket)/neptune-model-graph-autotrainer"
        "previousModelTrainingJobId" : "(the model-training job-id of a completed job)"
      }'
```

您可以提供 `customModelTrainingParameters` 物件，在 Neptune ML 訓練基礎結構上訓練自己的模型實作，如下所示：

```
curl \
  -X POST https://(your Neptune endpoint)/ml/modeltraining
  -H 'Content-Type: application/json' \
  -d '{
        "id" : "(a unique model-training job ID)",
        "dataProcessingJobId" : "(the data-processing job-id of a completed job)",
        "trainModelS3Location" : "s3://(your Amazon S3 bucket)/neptune-model-graph-autotrainer"
        "modelName": "custom",
        "customModelTrainingParameters" : {
          "sourceS3DirectoryPath": "s3://(your Amazon S3 bucket)/(path to your Python module)",
          "trainingEntryPointScript": "(your training script entry-point name in the Python module)",
          "transformEntryPointScript": "(your transform script entry-point name in the Python module)"
        }
      }'
```



如需詳細資訊，例如有關如何取得執行中工作的狀態、如何停止執行中工作，以及如何列出所有執行中工作，請參閱 [modeltraining 指令](machine-learning-api-modeltraining.md)。如需如何實作並使用自訂模型的相關資訊，請參閱 [Neptune ML 中的自訂模型](machine-learning-custom-models.md)。

**Topics**
+ [Amazon Neptune ML 中的模型和模型訓練](machine-learning-models-and-training.md)
+ [在 Neptune ML 中自訂模型超參數組態](machine-learning-customizing-hyperparams.md)
+ [模型訓練最佳實務](machine-learning-improve-model-performance.md)

# Amazon Neptune ML 中的模型和模型訓練
<a name="machine-learning-models-and-training"></a>

Neptune ML 會使用圖形神經網路 (GNN) 為各種機器學習任務建立模型。圖形神經網路已被證明可為圖形機器學習任務取得最先進的結果，並且在從圖形結構化資料中擷取資訊模式方面非常出色。

## Neptune ML 中的圖形神經網路 (GNN)
<a name="machine-learning-gnns"></a>

圖形神經網路 (GNN) 屬於一系列神經網路，它們透過考慮附近節點的結構和特徵來計算節點表示法。GNN 補充了其他不是很適合圖形資料的傳統機器學習和神經網路方法。

GNN 用來解決機器學習任務，例如節點分類和迴歸 (預測節點的屬性)，以及邊緣分類和迴歸 (預測邊緣的屬性) 或連結預測 (預測圖形中的兩個節點是否應該連接)。

一般來說，將 GNN 用於機器學習任務涉及兩個階段：
+ 編碼階段，其中 GNN 會計算圖形中每個節點的 d 維向量。這些向量也稱為*表示法*或*嵌入*。
+ 解碼階段，其中會根據編碼的表示法做出預測。

對於節點分類和迴歸，節點表示法可以直接用於分類和迴歸任務。對於邊緣分類和迴歸，邊緣上事件節點的節點表示法會用作分類或迴歸的輸入。對於連結預測，計算邊緣可能性分數的方式為使用一對節點表示法和一個邊緣類型表示法。

[Deep Graph Library (DGL)](https://www.dgl.ai/) 可為這些任務促進 GNN 的有效定義和訓練。

不同的 GNN 模型在訊息傳遞的構想下得到了統一。在此檢視中，圖形中節點的表示法是使用節點鄰居的表示法 (訊息)，以及節點的初始表示法來計算。在 Neptune ML 中，節點的初始表示法是從擷取自其節點屬性的特徵衍生的，或是可學習的，並且取決於節點的身分。

Neptune ML 還提供了選項，讓您串連節點特徵和可學習節點表示法，以充當原始節點表示法。

對於 Neptune ML 中涉及圖形與節點屬性的各種任務，我們會使用[關聯式圖形卷積網路](https://arxiv.org/abs/1703.06103) (R-GCN) 來執行編碼階段。R-GCN 是 GNN 架構，非常適合具有多個節點和邊緣類型的圖形 (這些圖形稱為異質圖)。

R-GCN 網絡由固定數量的層組成，一個接一個地堆疊。R-GCN 的每一層都會使用其可學習模型參數來彙總資訊，而這些資訊來自節點的鄰近 1 躍點鄰域。由於後續層會使用前一層的輸出表示法做為輸入，因此影響節點最終嵌入之圖形鄰域的半徑取決於 R-GCN 網路的層數 (`num-layer`)。

例如，這表示雙層網路使用的資訊來自兩個躍點之外的節點。

若要深入了解 GNN，請參閱[圖形神經網路的全面調查](https://arxiv.org/abs/1901.00596)。[如需 Deep Graph Library (DGL) 的詳細資訊，請造訪 DGL 網頁](https://www.dgl.ai/)。如需有關使用 DGL 搭配 GNN 的實作教學課程，請參閱[使用 Deep Graph Library 學習圖形神經網路](https://www.amazon.science/videos-webinars/learning-graph-neural-networks-with-deep-graph-library)。

## 訓練圖形神經網路
<a name="machine-learning-gnn-training"></a>

在機器學習中，取得模型以了解如何對任務做出良好預測的程序稱為模型訓練。通常執行此操作的方式為指定要最佳化的特定目標，以及用來執行此最佳化的演算法。

此程序也會用於訓練 GNN，以了解下游任務的合適表示法。我們會針對該任務建立目標函數，而該任務會在模型訓練期間最小化。[例如，對於節點分類，我們會使用 [CrosssentroPyLoss](https://pytorch.org/docs/stable/generated/torch.nn.CrossEntropyLoss.html) 做為目標，這會懲罰錯誤分類，而對於節點迴歸，我們會將 MeanSquareError](https://pytorch.org/docs/stable/generated/torch.nn.MSELoss.html) 降至最低。

目標通常是一個損失函數，其會取得特定資料點的模型預測，並將它們與該資料點的基準真相值進行比較。它會傳回損失值，其會顯示模型預測的偏差程度。訓練程序的目標是將損失降到最低，並確保模型預測接近基準真相。

深度學習中用於訓練程序的最佳化演算法通常是梯度下降的變體。在 Neptune ML 中，我們會使用 [Adam](https://arxiv.org/pdf/1412.6980.pdf)，這是一種演算法，用於隨機目標函數的一階梯度型最佳化，而這些函數是以低階時刻的自適應估計為基礎。

雖然模型訓練程序會嘗試確保學到的模型參數接近目標函數的最小值，但模型的整體效能也取決於模型的*超參數*，而這些超參數是訓練演算法未學習的模型設定。例如，學到的節點表示法 (`num-hidden`) 的維數是影響模型效能的超參數。因此，在機器學習中，執行超參數最佳化 (HPO) 來選擇合適的超參數是很常見的。

Neptune ML 使用 SageMaker AI 超參數調校任務來啟動具有不同超參數組態的多個模型訓練執行個體，以嘗試尋找一系列超參數設定的最佳模型。請參閱 [在 Neptune ML 中自訂模型超參數組態](machine-learning-customizing-hyperparams.md)。

## Neptune ML 中的知識圖譜嵌入模型
<a name="machine-learning-kg-embedding"></a>

知識圖譜 (KG) 是編碼不同實體 (節點) 及其關聯 (邊緣) 之相關資訊的圖形。在 Neptune ML 中，當圖形不包含節點屬性，只包含與其他節點的關聯時，預設會套用知識圖譜嵌入模型以執行連結預測。雖然, R-GCN 模型與可學習嵌入也可以透過將模型類型指定為 `"rgcn"` 來用於這些圖形,但知識圖譜嵌入模型更簡單，且被設計為對大型知識圖譜的學習表示法有效。

知識圖譜嵌入模型用於連結預測任務，以預測完成三重 `(h, r, t)` 的節點或關聯，其中 `h` 是來源節點、`r` 是關聯類型，而 `t` 是目的地節點。

在 Neptune ML 中實作的知識圖譜嵌入模型是 `distmult`、`transE` 和 `rotatE`。若要深入了解知識圖譜嵌入模型，請參閱 [DGL-KE](https://github.com/awslabs/dgl-ke)。

## 在 Neptune ML 中訓練自訂模型
<a name="machine-learning-training-custom-models"></a>

Neptune ML 可讓您針對特定案例定義和實作自己的自訂模型。如需如何實作自訂模型，以及如何使用 Neptune ML 基礎結構來訓練該模型的相關資訊，請參閱 [Neptune ML 中的自訂模型](machine-learning-custom-models.md)。

# 在 Neptune ML 中自訂模型超參數組態
<a name="machine-learning-customizing-hyperparams"></a>

當您啟動 Neptune ML 模型訓練工作時，Neptune ML 會自動使用從先前[資料處理](machine-learning-on-graphs-processing.md)工作推斷出的資訊。它使用資訊來產生超參數組態範圍，用於建立 [SageMaker AI 超參數調校任務](https://docs.aws.amazon.com/sagemaker/latest/dg/automatic-model-tuning-how-it-works.html)，以訓練任務的多個模型。如此一來，您就不必為要訓練的模型指定很長的超參數值清單。相反，根據任務類型、圖形類型和調校工作設定來選取模型超參數範圍和預設值。

不過，您也可以修改資料處理工作所產生的 JSON 組態檔，來覆寫預設超參數組態並提供自訂超參數。

使用 Neptune ML [modelTraining API](machine-learning-api-modeltraining.md)，您可以控制數個高階超參數調校工作設定，例如 `maxHPONumberOfTrainingJobs`、`maxHPOParallelTrainingJobs` 和 `trainingInstanceType`。若要對模型超參數進行更精細的控制，您可以自訂資料處理工作所產生的 `model-HPO-configuration.json` 檔案。此檔案會儲存在您針對處理工作輸出所指定的 Amazon S3 位置。

您可以下載此檔案、進行編輯以覆寫預設的超參數組態，然後將其上傳回相同的 Amazon S3 位置。請不要變更檔案名稱，編輯時請小心遵循這些指示。

若要從 S3 下載檔案：

```
aws s3 cp \
  s3://(bucket name)/(path to output folder)/model-HPO-configuration.json \
  ./
```

完成編輯後，請將檔案上傳回原來的位置：

```
aws s3 cp \
  model-HPO-configuration.json \
  s3://(bucket name)/(path to output folder)/model-HPO-configuration.json
```

## `model-HPO-configuration.json` 檔案的結構
<a name="machine-learning-hyperparams-file-structure"></a>

`model-HPO-configuration.json` 檔案會指定要訓練的模型、機器學習 `task_type`，以及對於各種模型訓練執行應變動或固定的超參數。

超參數會分類為屬於不同層，這些層表示調用超參數調校工作時給與超參數的優先順序：
+ 第 1 層超參數具有最高優先順序。如果您將 `maxHPONumberOfTrainingJobs` 設定為小於 10 的值，則只會調校第 1 層超參數，其餘的則採取預設值。
+ 第 2 層超參數的優先順序較低，因此，如果對於調校工作，您有總數超過 10 個，但少於 50 個的訓練工作，則會同時調校第 1 層和第 2 層超參數。
+ 僅在您有總數超過 50 個的訓練工作時，第 3 層超參數才會與第 1 層和第 2 層一起進行調校。
+ 最後，固定的超參數完全不會進行調校，並且始終採取其預設值。

### `model-HPO-configuration.json` 檔案的範例
<a name="machine-learning-hyperparams-file-sample"></a>

以下是範例 `model-HPO-configuration.json` 檔案：

```
{
  "models": [
    {
      "model": "rgcn",
      "task_type": "node_class",
      "eval_metric": {
        "metric": "acc"
      },
      "eval_frequency": {
          "type":  "evaluate_every_epoch",
          "value":  1
      },
      "1-tier-param": [
        {
            "param": "num-hidden",
            "range": [16, 128],
            "type": "int",
            "inc_strategy": "power2"
        },
        {
          "param": "num-epochs",
          "range": [3,30],
          "inc_strategy": "linear",
          "inc_val": 1,
          "type": "int",
          "node_strategy": "perM"
        },
        {
          "param": "lr",
          "range": [0.001,0.01],
          "type": "float",
          "inc_strategy": "log"
        }
      ],
      "2-tier-param": [
        {
          "param": "dropout",
          "range": [0.0,0.5],
          "inc_strategy": "linear",
          "type": "float",
          "default": 0.3
        },
        {
          "param": "layer-norm",
          "type": "bool",
          "default": true
        }
      ],
      "3-tier-param": [
        {
          "param": "batch-size",
          "range": [128, 4096],
          "inc_strategy": "power2",
          "type": "int",
          "default": 1024
        },
        {
          "param": "fanout",
          "type": "int",
          "options": [[10, 30],[15, 30], [15, 30]],
          "default": [10, 15, 15]
        },
        {
          "param": "num-layer",
          "range": [1, 3],
          "inc_strategy": "linear",
          "inc_val": 1,
          "type": "int",
          "default": 2
        },
        {
          "param": "num-bases",
          "range": [0, 8],
          "inc_strategy": "linear",
          "inc_val": 2,
          "type": "int",
          "default": 0
        }
      ],
      "fixed-param": [
        {
          "param": "concat-node-embed",
          "type": "bool",
          "default": true
        },
        {
          "param": "use-self-loop",
          "type": "bool",
          "default": true
        },
        {
          "param": "low-mem",
          "type": "bool",
          "default": true
        },
        {
          "param": "l2norm",
          "type": "float",
          "default": 0
        }
      ]
    }
  ]
}
```

### `model-HPO-configuration.json` 檔案的元素
<a name="machine-learning-hyperparams-file-elements"></a>

此檔案包含一個 JSON 物件，其中包含名為 `models` 的單一最上層陣列，該陣列包含單一模型組態物件。自訂檔案時，請確定 `models` 陣列中只有一個模型組態物件。如果您的檔案包含多個模型組態物件，調校工作將會失敗並出現警告。

模型組態物件包含下列最上層元素：
+ **`model`** – (*字串*) 要訓練的模型類型 (**請勿修改**)。有效的值如下：
  + `"rgcn"` – 這是節點分類和迴歸任務以及異質連結預測任務的預設值。
  + `"transe"` – 這是 KGE 連結預測任務的預設值。
  + `"distmult"` – 這是 KGE 連結預測任務的替代模型類型。
  + `"rotate"` – 這是 KGE 連結預測任務的替代模型類型。

  規則是不要直接修改 `model` 值，因為不同的模型類型通常具有截然不同的適用超參數，這可能會在訓練工作開始之後導致剖析錯誤。

  若要變更模型類型，請使用 [modelTraining API](machine-learning-api-modeltraining.md#machine-learning-api-modeltraining-create-job) 中的 `modelName` 參數，而不是在 `model-HPO-configuration.json` 檔案中變更它。

  變更模型類型並進行精細超參數變更的方法是，為您要使用的模型複製預設模型組態範本，然後將其貼入 `model-HPO-configuration.json` 檔案中。如果推斷的任務類型支援多個模型，則在與 `model-HPO-configuration.json` 檔案相同的 Amazon S3 位置中會有一個名為 `hpo-configuration-templates` 的資料夾。此資料夾包含適用於任務之其他模型的所有預設超參數組態。

  例如，如果您想要將 `KGE` 連結預測任務的模型和超參數組態從預設 `transe` 模型變更為 `distmult` 模型，只需將 `hpo-configuration-templates/distmult.json` 檔案內容貼入 `model-HPO-configuration.json` 檔案中，然後視需要編輯超參數即可。
**注意**  
如果您在 `modelTraining` API 中設定 `modelName` 參數，同時變更 `model-HPO-configuration.json` 檔案中的 `model` 和超參數規格，且這些規格不同，則 `model-HPO-configuration.json` 檔案中的 `model` 值優先採用，且會忽略 `modelName` 值。
+ **`task_type`**   –   (*字串*) 由資料處理工作推斷或直接傳遞至資料處理工作的機器學習任務類型 (**請勿修改**)。有效的值如下：
  + `"node_class"`
  + `"node_regression"`
  + `"link_prediction"`

  資料處理工作會推斷任務類型，方法是檢查匯出的資料集和資料集屬性所產生的訓練工作組態檔案，以取得資料集的屬性。

  此值不得變更。如果您想要訓練不同的任務，則需要[執行新的資料處理工作](machine-learning-on-graphs-processing.md)。如果 `task_type` 值不是您預期的值，您應該檢查資料處理工作的輸入，以確定它們是正確的。這包括 `modelTraining` API 的參數，以及資料匯出程序所產生的訓練工作組態檔案中的參數。
+ **`eval_metric`** – (*字串*) 評估指標應用於評估模型效能，以及用於跨 HPO 執行選取效能最佳的模型。有效的值如下：
  + `"acc"` – 標準分類正確性。這是單一標籤分類任務的預設值，除非在資料處理期間發現不平衡的標籤，在此情況下，預設值為 `"F1"`。
  + `"acc_topk"` – 正確標籤位列排名最高 **`k`** 預測的次數。您也可以透過慱入 `topk` 做為額外索引鍵來設定值 **`k`**。
  + `"F1"` – [F1 分數](https://en.wikipedia.org/wiki/F-score)。
  + `"mse"` – 迴歸任務的[均方誤差指標](https://en.wikipedia.org/wiki/Mean_squared_error)。
  + `"mrr"` – [平均倒數排名指標](https://en.wikipedia.org/wiki/Mean_reciprocal_rank)。
  + `"precision"` – 模型精確度，計算方式為真正陽性與預測陽性之比：`= true-positives / (true-positives + false-positives)`。
  + `"recall"` – 模型回收，計算方式為真正陽性與實際陽性之比：`= true-positives / (true-positives + false-negatives)`。
  + `"roc_auc"` – [ROC 曲線](https://en.wikipedia.org/wiki/Receiver_operating_characteristic)下方的區域。這是多標籤分類的預設值。

  例如，若要將指標變更為 `F1`，請變更 `eval_metric` 值，如下所示：

  ```
  "  eval_metric": {
      "metric": "F1",
    },
  ```

  或者，若要將指標變更為 `topk` 正確性分數，您將變更 `eval_metric`，如下所示：

  ```
    "eval_metric": {
      "metric": "acc_topk",
      "topk": 2
    },
  ```
+ **`eval_frequency`** – (*物件*) 指定在訓練期間應檢查驗證集上模型效能的頻率。根據驗證效能，可以接著啟動提前停止，並儲存最佳模型。

  `eval_frequency` 物件包含兩個元素，即 `"type"` 和 `"value"`。例如：

  ```
    "eval_frequency": {
      "type":  "evaluate_every_pct",
      "value":  0.1
    },
  ```

  有效的 `type` 值如下：
  + **`evaluate_every_pct`** – 指定每個評估要完成的訓練百分比。

    對於 `evaluate_every_pct`，`"value"` 欄位包含一個介於零與一之間的浮點數，表示該百分比。

    
  + **`evaluate_every_batch`** – 指定每個評估要完成的訓練批次數目。

    對於 `evaluate_every_batch`，`"value"` 欄位包含表示該批次計數的整數。
  + **`evaluate_every_epoch`** – 指定每個評估的 epoch 數目，其中新 epoch 從午夜開始。

    對於 `evaluate_every_epoch`，`"value"` 欄位包含表示該 epoch 計數的整數。

  `eval_frequency` 的預設設定如下：

  ```
    "eval_frequency": {
      "type":  "evaluate_every_epoch",
      "value":  1
    },
  ```
+ **`1-tier-param`** – (*必要*) 第 1 層超參數的陣列。

  如果您不想要調校任何超參數，則可以將此設定為空陣列。這不會影響 SageMaker AI 超參數調校任務啟動的訓練任務總數。其只是意味著所有的訓練作業 (如果超過 1 個，但少於 10 個) 將搭配相同的一組超參數執行。

  另一方面，如果您想要以同等重要的方式處理所有可調校的超參數，則可以將所有的超參數放在這個陣列中。
+ **`2-tier-param`** – (*必要*) 第 2 層超參數的陣列。

  僅在 `maxHPONumberOfTrainingJobs` 具有大於 10 的值時，才會調校這些參數。否則，它們會固定為預設值。

  如果您的訓練預算最多為 10 個訓練工作，或者因為任何其他原因而不想要第 2 層超參數，但是您想要調校所有可調校的超參數，則可以將此設定為空陣列。
+ **`3-tier-param`** – (*必要*) 第 3 層超參數的陣列。

  僅在 `maxHPONumberOfTrainingJobs` 具有大於 50 的值時，才會調校這些參數。否則，它們會固定為預設值。

  如果您不想要第 3 層超參數，則可以將此設定為空陣列。
+ **`fixed-param`** – (*必要*) 固定超參數的陣列，這些超參數僅採取其預設值，且在不同的訓練工作中不會有所變動。

  如果想要改變所有超參數，您可以將其設定為空陣列，然後將 `maxHPONumberOfTrainingJobs` 的值設定為足以改變所有層的大小，或使所有超參數成為第 1 層。

代表 `1-tier-param`、`2-tier-param`、`3-tier-param` 和 `fixed-param` 中每個超參數的 JSON 物件包含下列元素：
+ **`param`** – (*字串*) 超參數的名稱 (**請勿變更**)。

  請參閱 [Neptune ML 中有效的超參數名稱清單](#machine-learning-hyperparams-list)。
+ **`type`** – (*字串*) 超參數類型 (**請勿變更**)。

  有效類型為：`bool`、`int` 和 `float`。
+ **`default`** – (*字串*) 超參數的預設值。

  您可以設定新的預設值。

可調校的超參數也可以包含下列元素：
+ **`range`** – (*陣列*) 連續可調校超參數的範圍。

  這應該是具有兩個值的陣列，即範圍的最小值和最大值 (`[min, max]`)。
+ **`options`** – (*陣列*) 類別可調校超參數的選項。

  這個陣列應該包含所有要考慮的選項：

  ```
    "options" : [value1, value2, ... valuen]
  ```
+ **`inc_strategy`** – (*字串*) 連續可調校超參數範圍的增量變更類型 (**請勿變更**)。

  有效值為 `log`、`linear` 和 `power2`。這僅在設定了範圍索引鍵時才適用。

  修改此選項可能會導致未使用完整範圍的超參數進行調校。
+ **`inc_val`** – (*浮動*) 連續增量對連續可調校超參數的差異量 (**請勿變更**)。

  這僅在設定了範圍索引鍵時才適用。

  修改此選項可能會導致未使用完整範圍的超參數進行調校。
+ **`node_strategy`** – (*字串*) 表示此超參數的有效範圍應根據圖形中的節點數目而變更 (**請勿變更**)。

  有效值為 `"perM"` (每百萬)、`"per10M"` (每千萬) 和 `"per100M"` (每億)。

  不是變更此值，而是變更 `range`。
+ **`edge_strategy`** – (*字串*) 表示此超參數的有效範圍應根據圖形中的邊緣數目而變更 (**請勿變更**)。

  有效值為 `"perM"` (每百萬)、`"per10M"` (每千萬) 和 `"per100M"` (每億)。

  不是變更此值，而是變更 `range`。

### Neptune ML 中所有超參數的清單
<a name="machine-learning-hyperparams-list"></a>

下列清單包含可在 Neptune ML 中任何位置針對任何模型類型和任務設定的所有超參數。因為它們並非全部適用於每種模型類型，所以請務必只針對您正在使用的模型設定 `model-HPO-configuration.json` 檔案中出現在範本的超參數。
+ **`batch-size`** – 在一個正向傳遞中使用之目標節點的批次大小。*類型*：`int`。

  將此值設定為更大的值可能會導致 GPU 執行個體訓練時出現記憶體問題。
+ **`concat-node-embed`** – 指示是否透過串連節點處理的特徵與可學習的初始節點嵌入來取得節點的初始表示法，以便增加模型的表達能力。*類型*：`bool`。
+ **`dropout`** – 套用至退出層的退出機率。*類型*：`float`。

  
+ **`edge-num-hidden`** – 邊緣特徵模組的隱藏層大小或單位數量。僅在 `use-edge-features` 設為 `True` 時才使用。*類型*：浮動。
+ **`enable-early-stop`** – 切換是否使用提前停止功能。*類型*：`bool`。*預設*︰`true`。

  使用此布林參數來關閉提前停止功能。
+ **`fanout`** – 鄰近取樣期間要為目標節點取樣的鄰近節點數。*類型*：`int`。

  此值與 `num-layers` 緊密結合，並且應始終位於相同的超參數層中。這是因為您可以為每個潛在的 GNN 層指定扇出。

  因為這個超參數可能會造成模型效能發生很大變化，所以其應該固定或設定為第 2 層或第 3 層超參數。將其設定為更大的值可能會導致 GPU 執行個體訓練時出現記憶體問題。
+ **`gamma`** – 分數函數中的邊距值。*類型*：`float`。

  這僅適用於 `KGE` 連結預測模型。
+ **`l2norm`** – 最佳化工具中使用的權重衰減值，該值會對權重施加 L2 標準化懲罰。*類型*：`bool`。
+ **`layer-norm`** – 指示是否要對 `rgcn` 模型使用層標準化。*類型*：`bool`。
+ **`low-mem`** – 指示是否以犧牲速度為代價，使用關聯訊息傳遞函數的低記憶體實作。*類型*：`bool`。

  
+ **`lr`** – 學習率。*類型*：`float`。

  這應該設為第 1 層超參數。
+ **`neg-share`** – 在連結預測中，指示正取樣邊緣是否可以共用負邊緣取樣。*類型*：`bool`。
+ **`num-bases`** – `rgcn` 模型中基礎分解的基數。使用小於圖形中邊緣類型數目的 `num-bases` 值，做為 `rgcn` 模型的正規化器。*類型*：`int`。
+ **`num-epochs`** – 要執行之訓練的 epoch 數量。*類型*：`int`。

  一個 epoch 是通過圖形的完整訓練。
+ **`num-hidden`** – 隱藏層大小或單位數量。*類型*：`int`。

  這也會設定無特徵節點的初始嵌入大小。

  在沒有減少 `batch-size` 的情況下將此值設定為更大的值可能會導致 GPU 執行個體訓練時出現記憶體用光問題。
+ **`num-layer`** – 模型中 GNN 層的數量。*類型*：`int`。

  此值與扇出參數緊密結合，並且應該在同一超參數層中設定扇出之後出現。

  因為此值可能會造成模型效能發生很大變化，所以其應該固定或設定為第 2 層或第 3 層超參數。
+ **`num-negs`** – 在連結預測中，每個正樣本的負樣本數量。*類型*：`int`。
+ **`per-feat-name-embed`** – 指示是否在組合特徵之前透過獨立轉換來嵌入每個特徵。*類型*：`bool`。

  當設定為 `true` 時，在串連節點的所有轉換特徵並進一步轉換為 `num_hidden` 維度之前，將每個節點的每個特徵獨立轉換為固定維度大小。

  當設定為 `false` 時，會串連特徵，而不會進行任何特徵特定的轉換。
+ **`regularization-coef`** – 在連結預測中，正規化損失的係數。*類型*：`float`。
+ **`rel-part`** – 指示是否使用關聯分割區進行 `KGE` 連結預測。*類型*：`bool`。
+ **`sparse-lr`** – 可學習節點嵌入的學習率。*類型*：`float`。

  可學習的初始節點嵌入用於沒有特徵或設定 `concat-node-embed` 時的節點。稀疏可學習節點嵌入層的參數會使用個別的最佳化工具進行訓練，該最佳化工具可以具有個別的學習率。
+ **`use-class-weight`** – 指示是否針對不平衡的分類任務套用類別權重。如果設定為 `true`，則會使用標籤計數來設定每個類別標籤的權重。*類型*：`bool`。
+ **`use-edge-features`** – 指示是否要在訊息傳遞期間使用邊緣特徵。如果設定為 `true`，則對於具有特徵的邊緣類型，會將自訂邊緣特徵模組新增至 RGCN 層。*類型*：`bool`。
+ **`use-self-loop`** – 指示是否要在訓練 `rgcn` 模型時包含自我迴圈。*類型*：`bool`。
+ **`window-for-early-stop`** – 控制要平均的最新驗證分數，以決定是否要提前停止。預設值為 3。type=int。另請參閱[提前停止 Neptune ML 中的模型訓練程序](machine-learning-improve-model-performance.md#machine-learning-model-training-early-stop)。*類型*：`int`。*預設*︰`3`。

  請參閱 。

## 在 Neptune ML 中自訂超參數
<a name="machine-learning-hyperparams-editing"></a>

當您編輯 `model-HPO-configuration.json` 檔案時，以下是最常進行的變更種類：
+ 編輯 `range` 超參數的最小值和/或最大值。
+ 將超參數設定為固定值，方法是將該超參數移至 `fixed-param` 區段，並將其預設值設定為您想要其採取的固定值。
+ 變更超參數的優先順序，方法是將該超參數置於特定層中、編輯其範圍，並確定已適當地設定其預設值。

# 模型訓練最佳實務
<a name="machine-learning-improve-model-performance"></a>

您可以採取一些措施來改善 Neptune ML 模型的效能。

## 選擇正確的節點屬性
<a name="machine-learning-before-exporting-data-choose-property"></a>

並非圖形中的所有屬性都有意義或與您的機器學習任務相關。在資料匯出期間，應排除任何不相關的屬性。

以下是一些最佳實務：
+ 使用領域專家來協助評估特徵的重要性，以及使用它們進行預測的可行性。
+ 移除您確定是多餘或無關的特徵，以減少資料中的干擾和不重要的相關性。
+ 在建置模型時進行迭代。在進行時調整特徵、特徵組合和調校目標。

Amazon Machine Learning 開發人員指南中的[特徵處理](https://docs.aws.amazon.com/machine-learning/latest/dg/feature-processing.html)為與 Neptune ML 相關的特徵處理提供其他指導方針。

## 處理異常值資料點
<a name="machine-learning-before-exporting-data-outliers"></a>

異常值是與剩餘資料明顯不同的資料點。資料異常值可能會破壞或誤導訓練程序，導致訓練時間更長或模型準確度降低。除非它們真的很重要，否則您應該在匯出資料之前消除異常值。

## 移除重複的節點和邊緣
<a name="machine-learning-before-exporting-data-remove-duplicates"></a>

儲存在 Neptune 的圖形可能具有重複的節點或邊緣。這些冗餘元素將為 ML 模型訓練帶來干擾。在匯出資料之前消除重複的節點或邊緣。

## 調校圖形結構
<a name="machine-learning-before-exporting-data-tune-graph"></a>

匯出圖形時，您可以變更特徵的處理方式及圖形的建構方式，以改善模型效能。

以下是一些最佳實務：
+ 當邊緣屬性具有邊緣類別的意義時，在某些情況下，值得將其轉換為邊緣類型。
+ 用於數值屬性的預設標準化政策是 `min-max`，但在某些情況下，其他標準化政策效果更好。您可以預先處理屬性並變更標準化政策，如 [`model-HPO-configuration.json` 檔案的元素](machine-learning-customizing-hyperparams.md#machine-learning-hyperparams-file-elements) 中所述。
+ 匯出程序會根據屬性類型自動產生特徵類型。例如，它會將 `String` 屬性視為類別特徵，並將 `Float` 和 `Int` 屬性視為數值特徵。如果需要的話，您可在匯出後修改特徵類型 (請參閱 [`model-HPO-configuration.json` 檔案的元素](machine-learning-customizing-hyperparams.md#machine-learning-hyperparams-file-elements))。

## 調校超參數範圍和預設值
<a name="machine-learning-before-exporting-data-change-hpo"></a>

資料處理操作會從圖形推斷超參數組態範圍。如果產生的模型超參數範圍和預設值不適用於圖形資料，您可以編輯 HPO 組態檔案，以建立您自己的超參數調校策略。

以下是一些最佳實務：
+ 當圖形變大時，預設隱藏的維度大小可能不夠大，無法包含所有資訊。您可以變更 `num-hidden` 超參數來控制隱藏的維度大小。
+ 對於知識圖譜嵌入（KGE）模型，您可能想要根據圖形結構和預算變更正在使用的特定模型。

  `TrainsE` 模型在處理一對多 (1-N)、多對一 (N-1) 和多對多 (N-N) 關係時遇到困難。`DistMult` 模型在處理對稱關係時遇到困難。`RotatE` 擅長建模各種關係，但在訓練期間比 `TrainsE` 和 `DistMult` 更昂貴。
+ 在某些情況下，當節點識別和節點特徵資訊都很重要時，您應該使用 ``concat-node-embed`` 告知 Neptune ML 模型，透過將節點的特徵與初始嵌入串連來取得節點的初始表示法。
+ 當您對某些超參數取得相當好的效能時，可以根據這些結果調整超參數搜尋空間。

## 提前停止 Neptune ML 中的模型訓練程序
<a name="machine-learning-model-training-early-stop"></a>

提前停止可大幅縮短模型訓練執行時間和相關聯成本，而不會降低模型效能。它還可以防止模型在訓練資料上過度擬合。

提前停止取決於驗證集效能的定期測量。最初，效能隨著訓練的進行而改善，但是當模型開始過度擬合時，效能會再次開始下降。提前停止功能會識別模型開始過度擬合的點，並在該點停止模型訓練。

Neptune ML 會監控驗證指標呼叫，並將最新的驗證指標與最後 **`n`** 個評估所得到的驗證指標平均值進行比較，其中 **`n`** 是使用 `window-for-early-stop` 參數設定的數字。一旦驗證指標比該平均值差，Neptune ML 就會停止模型訓練並儲存迄今的最佳模型。

您可以使用下列參數控制提前停止：
+ **`window-for-early-stop`** – 此參數的值為整數，其指定在決定提前停止時要平均的最新驗證分數。預設值為 `3`。
+ **`enable-early-stop`** – 使用此布林參數來關閉提前停止功能。依預設，其值為 `true`。

## 提前停止 Neptune ML 中的 HPO 程序
<a name="machine-learning-HPO-early-stop"></a>

Neptune ML 中的提前停止功能也會使用 SageMaker AI HPO 暖啟動功能，停止與其他訓練任務相比效能不佳的訓練任務。這也可以降低成本並提高 HPO 的品質。

如需此運作方式的描述，請參閱[執行暖啟動超參數調校工作](https://docs.aws.amazon.com/sagemaker/latest/dg/automatic-model-tuning-warm-start.html)。

暖啟動可讓您將從先前訓練工作中學到的資訊傳遞給後續訓練工作，並提供了兩個明顯的優勢：
+ 首先，先前訓練工作的結果是用來選取好的超參數組合，以在新的調校工作中進行搜尋。
+ 其次，它允許提前停止存取更多的模型執行，從而減少調校時間。

此功能會在 Neptune ML 中自動啟用，並可讓您在模型訓練時間與效能之間取得平衡。如果您對目前模型的效能感到滿意，則可以使用該模型。否則，您會執行更多由於先前執行結果而暖啟動的 HPO，以便探索更好的模型。

## 取得專業支援服務
<a name="machine-learning-before-exporting-data-get-support"></a>

AWS 提供專業支援服務，協助您解決 Neptune 專案機器學習的問題。如果您遇到困難，請尋求 [AWS 支援](https://aws.amazon.com/premiumsupport/)。

# 使用訓練後的模型來產生新的模型成品
<a name="machine-learning-model-transform"></a>

使用 Neptune ML 模型轉換命令，您可以使用預先訓練的模型參數計算模型成品，例如在處理後的圖形資料上進行節點嵌入。

## 用於增量推論的模型轉換
<a name="machine-learning-model-transform-incremental"></a>

在[增量模型推論工作流程](machine-learning-overview-evolving-data-incremental.md#machine-learning-overview-incremental)中，於處理了您從 Neptune 匯出的更新圖形資料之後，您可以使用如下的 curl (或 awscurl) 命令啟動模型轉換工作：

```
curl \
  -X POST https://(your Neptune endpoint)/ml/modeltransform
  -H 'Content-Type: application/json' \
  -d '{
        "id" : "(a unique model-training job ID)",
        "dataProcessingJobId" : "(the data-processing job-id of a completed job)",
        "mlModelTrainingJobId": "(the ML model training job-id)",
        "modelTransformOutputS3Location" : "s3://(your Amazon S3 bucket)/neptune-model-transform/"
      }'
```

然後，您可以將此工作的 ID 傳遞至 create-endpoints API 呼叫，以建立新端點，或使用此工作產生的新模型成品更新現有端點。這可讓新的或更新的端點，為更新的圖形資料提供模型預測。

## 任何訓練工作的模型轉換
<a name="machine-learning-model-transform-any-job"></a>

您也可以提供 `trainingJobName` 參數，為 Neptune ML 模型訓練期間啟動的任何 SageMaker AI 訓練任務產生模型成品。由於 Neptune ML 模型訓練任務可能會啟動許多 SageMaker AI 訓練任務，因此可讓您靈活地根據任何這些 SageMaker AI 訓練任務建立推論端點。

例如：

```
curl \
  -X POST https://(your Neptune endpoint)/ml/modeltransform
  -H 'Content-Type: application/json' \
  -d '{
        "id" : "(a unique model-training job ID)",
        "trainingJobName" : "(name a completed SageMaker AI training job)",
        "modelTransformOutputS3Location" : "s3://(your Amazon S3 bucket)/neptune-model-transform/"
      }'
```

如果原始訓練工作是針對使用者提供的自訂模型，您必須在調用模型轉換時包含 `customModelTransformParameters` 物件。如需如何實作並使用自訂模型的相關資訊，請參閱 [Neptune ML 中的自訂模型](machine-learning-custom-models.md)。

**注意**  
`modeltransform` 命令一律會針對該訓練的最佳 SageMaker AI 訓練任務執行模型轉換。

如需模型轉換工作的詳細資訊，請參閱 [modeltransform 命令](machine-learning-api-modeltransform.md)。

# Neptune ML 中模型訓練產生的成品
<a name="machine-learning-model-artifacts"></a>

在模型訓練之後，Neptune ML 會使用最佳訓練模型參數，來產生啟動推論端點並提供模型預測所需的模型成品。這些成品由訓練任務封裝，並存放在最佳 SageMaker AI 訓練任務的 Amazon S3 輸出位置。

以下各節描述了各種任務的模型成品中包含什麼內容，以及模型轉換命令如何使用預先存在的訓練模型，即使在新的圖形資料上也能產生成品。

## 針對不同任務產生的成品
<a name="machine-learning-task-artifacts"></a>

訓練程序所產生的模型成品內容取決於目標機器學習任務：

****
+ **節點分類與迴歸** – 對於節點屬性預測，成品包括模型參數、來自 [GNN 編碼器](machine-learning-models-and-training.md#machine-learning-gnns)的節點嵌入、訓練圖中節點的模型預測，以及推論端點的一些組態檔案。在節點分類和節點迴歸任務中，會針對訓練期間存在的節點預先計算模型預測，以減少查詢延遲。
+ **邊緣分類和迴歸** – 對於邊緣屬性預測，成品還包含模型參數和節點嵌入。模型解碼器的參數對於推論尤為重要，因為我們會透過將模型解碼器套用至邊緣的來源和目標頂點嵌入，來計算邊緣分類或邊緣迴歸預測。
+ **連結預測** – 對於連結預測，除了針對邊緣屬性預測產生的成品外，也會包含 DGL 圖形作為成品，因為連結預測需要訓練圖才能執行預測。連結預測的目標是預測可能與來源頂點結合的目的地頂點，以形成圖形中特定類型的邊緣。為了執行此操作，來源頂點的節點嵌入和學到的邊緣類型表示法會與所有可能目的地頂點的節點嵌入結合，以產生每個目的地頂點的邊緣可能性分數。然後，對分數進行排序以排名潛在的目的地頂點並傳回頂級候選者。

對於每個任務類型，來自 DGL 的圖形神經網路模型權重會儲存在模型成品中。除了使用預先計算的預測和嵌入 (*直推式推論*) 來減少延遲之外，這還可讓 Neptune ML 在圖形變更時計算全新的模型輸出 (*歸納推論*)。

## 產生新的模型成品
<a name="machine-learning-task-artifacts"></a>

Neptune ML 中於模型訓練之後產生的模型成品會直接繫結至訓練程序。這意味著預先計算的嵌入和預測僅存在於原始訓練圖中的實體。雖然 Neptune ML 端點的歸納推論模式可以即時計算新實體的預測，但是您可能想要在新實體上產生批次預測，而不需要查詢端點。

對於已新增至圖形的新實體，為了取得其批次模型預測，需要針對新圖形資料重新計算新的模型成品。這是使用 `modeltransform` 命令來完成的。當您只想要批次預測而不設定端點時，或者當您想要產生所有預測，以便可以將其寫回圖形時，請使用 `modeltransform` 命令。

由於模型訓練會在訓練程序結束時隱含地執行模型轉換，因此訓練工作一律會在訓練圖資料上重新計算模型成品。不過，`modeltransform` 命令也可以在未用於訓練模型的圖形資料上計算模型成品。為此，必須使用與原始圖形資料相同的特徵編碼來處理新的圖形資料，並且必須遵守相同的圖形結構描述。

您可以達成此目標，方法是首先建立新的資料處理工作 (這是在原始訓練圖資料上執行的資料處理工作的複製)，接著在新的圖形資料上執行它 (請參閱 [處理 Neptune ML 的更新圖形資料](machine-learning-on-graphs-processing.md#machine-learning-on-graphs-processing-updated))。然後，使用新的 `dataProcessingJobId` 和舊的 `modelTrainingJobId` 呼叫 `modeltransform` 命令，以在更新的圖形資料上重新計算模型成品。

對於節點屬性預測，節點嵌入和預測會在新的圖形資料上重新計算，即使是原始訓練圖中存在的節點也是如此。

對於邊緣屬性預測和連結預測，也會重新計算節點嵌入，並會類似地覆蓋任何現有的節點嵌入。為了重新計算節點嵌入，Neptune ML 會將從先前訓練的模型中學到的 GNN 編碼器套用至具有其新特徵之新圖形資料的節點。

對於沒有特徵的節點，會重複使用從原始模型訓練中學到的初始表現法。對於沒有特徵且不存在於原始訓練圖中的新節點，Neptune ML 會將其表示法初始化為該節點類型 (存在於原始訓練圖中) 學到的初始節點表示法的平均值。如果您有許多沒有特徵的新節點，這可能會導致模型預測的效能下降，因為它們都會初始化為該節點類型的平均初始嵌入。

如果您的模型是在 `concat-node-embed` 設定為 true 的情況下進行訓練，則會透過串連節點特徵與可學習的初始表示法來建立初始節點表示法。因此，對於更新的圖形，新節點的初始節點表示法也會使用平均初始節點嵌入，與新的節點特徵串連。

此外，目前不支援節點刪除。如果已在更新的圖形中移除節點，則必須在更新的圖形資料上重新訓練模型。

重新計算模型成品會在新圖形上重複使用學到的模型參數，並且僅應在新圖形與舊圖形非常相似時才進行。如果您的新圖形不夠相似，則您需要重新訓練模型，才能在新圖形資料上取得類似的模型效能。構成足夠相似的內容取決於圖形資料的結構，但根據經驗法則，如果您的新資料與原始訓練圖形資料不同之處超過 10-20%，則您應該重新訓練模型。

對於所有節點都有特徵的圖形，會套用閾值的較高端 (20% 不同)，但對於許多節點沒有特徵，且新增至圖形的新節點沒有屬性的圖形，則較低端 (10% 不同) 甚至可能太高。

如需模型轉換工作的詳細資訊，請參閱 [modeltransform 命令](machine-learning-api-modeltransform.md)。

# Neptune ML 中的自訂模型
<a name="machine-learning-custom-models"></a>

**注意**  
Neptune ML 自訂模型支援依賴較舊版本的 Python 3。若要建立和執行具有up-to-date相依性的自訂 GNN 模型，請使用 [ SageMaker 上的 GraphStorm](https://graphstorm.readthedocs.io/en/v0.3.1/cli/model-training-inference/distributed/sagemaker.html)。  
自訂模型目前不支援[即時歸納推論](machine-learning-overview-evolving-data.md#inductive-vs-transductive-inference)。

Neptune ML 可讓您使用 Python 定義自己的自訂模型實作。您可以使用 Neptune ML 基礎結構訓練和部署自訂模型，就像對內建模型所做一樣，然後使用它們透過圖形查詢取得預測。

您可以遵循 [Neptune ML 工具組範例](https://github.com/awslabs/neptuneml-toolkit/tree/main/examples/custom-models/)，並使用 Neptune ML 工具組中提供的模型元件，開始在 Python 中實作您自己的自訂模型。下列各節將詳細說明。

**Contents**
+ [Neptune ML 中自訂模型的概觀](machine-learning-custom-model-overview.md)
  + [何時在 Neptune ML 中使用自訂模型](machine-learning-custom-model-overview.md#machine-learning-custom-models-when-to-use)
  + [在 Neptune ML 中開發和使用自訂模型的工作流程](machine-learning-custom-model-overview.md#machine-learning-custom-model-workflow)
+ [Neptune ML 中的自訂模型開發](machine-learning-custom-model-development.md)
  + [Neptune ML 中的自訂模型訓練指令碼開發](machine-learning-custom-model-development.md#machine-learning-custom-model-training-script)
  + [Neptune ML 中的自訂模型轉換指令碼開發](machine-learning-custom-model-development.md#machine-learning-custom-model-transform-script)
  + [Neptune ML 中的自訂 `model-hpo-configuration.json` 檔案](machine-learning-custom-model-development.md#machine-learning-custom-model-hpo-configuration-file)
  + [在 Neptune ML 中對您的自訂模型實作進行本機測試](machine-learning-custom-model-development.md#machine-learning-custom-model-testing)

# Neptune ML 中自訂模型的概觀
<a name="machine-learning-custom-model-overview"></a>

## 何時在 Neptune ML 中使用自訂模型
<a name="machine-learning-custom-models-when-to-use"></a>

Neptune ML 的內建模型會處理 Neptune ML 支援的所有標準任務，但是在有些情況，您可能想要對特定任務的模型進行更精細的控制，或者需要自訂模型訓練程序。例如，自訂模型適用於下列情況：
+ 對於非常大文字模型的文字特徵，必須在 GPU 上執行其特徵編碼。
+ 您想要使用自己的自訂圖形神經網路（GNN）模型，這是在 Deep Graph Library (DGL) 中開發的模型。
+ 您想要使用表格式模型或整體模型進行節點分類和迴歸。

## 在 Neptune ML 中開發和使用自訂模型的工作流程
<a name="machine-learning-custom-model-workflow"></a>

Neptune ML 中的自訂模型支援旨在無縫整合至現有的 Neptune ML 工作流程。它的運作方式是在 Neptune ML 基礎結構上的來源模組中執行自訂程式碼，以訓練模型。如同內建模式一樣，Neptune ML 會自動啟動 SageMaker AI HyperParameter 調校任務，並根據評估指標選取最佳模型。然後，它會使用來源模組中提供的實作來產生模型成品進行部署。

自訂模型的資料匯出、訓練組態和資料預先處理與內建模型相同。

在資料預先處理之後，您就可以反覆且以互動方式使用 Python，來開發並測試您的自訂模型實作。當您的模型已準備好生產時，您可以將產生的 Python 模組上傳到 Amazon S3，如下所示：

```
aws s3 cp --recursive (source path to module) s3://(bucket name)/(destination path for your module)
```

然後，您可以使用一般[預設](machine-learning-overview.md#machine-learning-overview-starting-workflow)或[增量](machine-learning-overview-evolving-data-incremental.md#machine-learning-overview-incremental)資料工作流程，將模型部署至生產環境，但有一些差異。

對於使用自訂模型的模型訓練，您必須將 `customModelTrainingParameters` JSON 物件提供給 Neptune ML 模型訓練 API，以確保使用您的自訂程式碼。`customModelTrainingParameters` 物件中的欄位如下所示：
+ **`sourceS3DirectoryPath`** – (*必要*) 此路徑通往實作您模型之 Python 模組所在的 Amazon S3 位置。這必須指向有效的現有 Amazon S3 位置，其中至少包含訓練指令碼、轉換指令碼和 `model-hpo-configuration.json` 檔案。
+ **`trainingEntryPointScript`** – (*選用*) 指令碼模組中的進入點名稱，該指令碼會執行模型訓練，並接受超參數作為命令列引數 (包括固定的超參數)。

  *預設*︰`training.py`。
+ **`transformEntryPointScript`** – (*選用*) 指令碼模組中的進入點名稱，該指令碼應在識別了超參數搜尋中的最佳模型之後執行，以計算模型部署所需的模型成品。它應該能夠在沒有命令列參數的情況下執行。

  *預設*︰`transform.py`。

例如：

```
curl \
  -X POST https://(your Neptune endpoint)/ml/modeltraining
  -H 'Content-Type: application/json' \
  -d '{
        "id" : "(a unique model-training job ID)",
        "dataProcessingJobId" : "(the data-processing job-id of a completed job)",
        "trainModelS3Location" : "s3://(your Amazon S3 bucket)/neptune-model-graph-autotrainer"
        "modelName": "custom",
        "customModelTrainingParameters" : {
          "sourceS3DirectoryPath": "s3://(your Amazon S3 bucket)/(path to your Python module)",
          "trainingEntryPointScript": "(your training script entry-point name in the Python module)",
          "transformEntryPointScript": "(your transform script entry-point name in the Python module)"
        }
      }'
```

同樣地，若要啟用自訂模型轉換，您必須將 `customModelTransformParameters` JSON 物件提供給 Neptune ML 模型轉換 API，其欄位值與訓練工作中儲存的模型參數相容。`customModelTransformParameters` 物件包含下列欄位：
+ **`sourceS3DirectoryPath`** – (*必要*) 此路徑通往實作您模型之 Python 模組所在的 Amazon S3 位置。這必須指向有效的現有 Amazon S3 位置，其中至少包含訓練指令碼、轉換指令碼和 `model-hpo-configuration.json` 檔案。
+ **`transformEntryPointScript`** – (*選用*) 指令碼模組中的進入點名稱，該指令碼應在識別了超參數搜尋中的最佳模型之後執行，以計算模型部署所需的模型成品。它應該能夠在沒有命令列參數的情況下執行。

  *預設*︰`transform.py`。

例如：

```
curl \
  -X POST https://(your Neptune endpoint)/ml/modeltransform
  -H 'Content-Type: application/json' \
  -d '{
        "id" : "(a unique model-training job ID)",
        "trainingJobName" : "(name of a completed SageMaker AI training job)",
        "modelTransformOutputS3Location" : "s3://(your Amazon S3 bucket)/neptune-model-transform/"
        "customModelTransformParameters" : {
          "sourceS3DirectoryPath": "s3://(your Amazon S3 bucket)/(path to your Python module)",
          "transformEntryPointScript": "(your transform script entry-point name in the Python module)"
        }
      }'
```

# Neptune ML 中的自訂模型開發
<a name="machine-learning-custom-model-development"></a>

開始自訂模型開發的好方法是，遵循 [Neptune ML 工具組範例](https://github.com/awslabs/neptuneml-toolkit/tree/main/examples/custom-models/introduction)來建構和撰寫訓練模組。Neptune ML 工具組也會在 [modelzoo](https://github.com/awslabs/neptuneml-toolkit/tree/main/src/neptuneml_toolkit/modelzoo) 中實作模組化圖形 ML 模型元件，您可以堆疊並使用這些元件來建立自訂模型。

此外，此工具組還提供公用程式函數，協助您在模型訓練和模型轉換期間產生必要的成品。您可以在自訂實作中匯入此 Python 套件。此工具組中提供的任何函數或模組也可在 Neptune ML 訓練環境中使用。

如果您的 Python 模組有額外的外部相依性，則您可以透過在模組的目錄中建立 `requirements.txt` 檔案，來包含這些額外的相依性。然後，會在訓練指令碼執行之前安裝 `requirements.txt` 檔案中列出的套件。

實作自訂模型的 Python 模組至少需要包含以下內容：
+ 訓練指令碼進入點
+ 轉換指令碼進入點
+ `model-hpo-configuration.json` 檔案

## Neptune ML 中的自訂模型訓練指令碼開發
<a name="machine-learning-custom-model-training-script"></a>

您的自訂模型訓練指令碼應該是可執行的 Python 指令碼，例如 Neptune ML 工具組的 [https://github.com/awslabs/neptuneml-toolkit/blob/main/examples/custom-models/introduction/movie-lens-rgcn/node-class/src/train.py](https://github.com/awslabs/neptuneml-toolkit/blob/main/examples/custom-models/introduction/movie-lens-rgcn/node-class/src/train.py) 範例。它必須接受超參數名稱和值作為命令列參數。在模型訓練期間，會從 `model-hpo-configuration.json` 檔案取得超參數名稱。超參數值會落在有效的超參數範圍內 (如果超參數是可調校的話)，或採取預設的超參數值 (如果無法調校的話)。

您的訓練指令碼會使用如下所示的語法在 SageMaker AI 訓練執行個體上執行：

```
python3 (script entry point) --(1st parameter) (1st value) --(2nd parameter) (2nd value) (...)
```

對於所有工作，除了您指定的超參數之外，Neptune ML AutoTrainer 還會將數個必要的參數傳送至您的訓練指令碼，而且您的指令碼必須能夠處理這些額外的參數，才能正常運作。

這些額外的必要參數會因任務而有所不同：

**若是節點分類或節點迴歸**
+ **`task`** – Neptune ML 內部使用的任務類型。對於節點分類，這是 `node_class`，對於節點迴歸，它是 `node_regression`。
+ **`model`** – Neptune ML 內部使用的模組名稱，在此情況下，該模組為 `custom`。
+ **`name`** – Neptune ML 內部使用的任務名稱，在此情況下該任務是 `node_class-custom` (用於節點分類)，以及 `node_regression-custom` (用於節點迴歸)。
+ **`target_ntype`** – 用於分類或迴歸的節點類型名稱。
+ **`property`** – 用於分類或迴歸的節點屬性名稱。

**若是連結預測**
+ **`task`** – Neptune ML 內部使用的任務類型。對於連結預測，這是 `link_predict`。
+ **`model`** – Neptune ML 內部使用的模組名稱，在此情況下，該模組為 `custom`。
+ **`name`** – Neptune ML 內部使用的任務名稱，在此情況下，該任務為 `link_predict-custom`。

**若是邊緣分類或邊緣迴歸**
+ **`task`** – Neptune ML 內部使用的任務類型。對於邊緣分類，這是 `edge_class`，對於邊緣迴歸，它是 `edge_regression`。
+ **`model`** – Neptune ML 內部使用的模組名稱，在此情況下，該模組為 `custom`。
+ **`name`** – Neptune ML 內部使用的任務名稱，在此情況下該任務是 `edge_class-custom` (用於邊緣分類)，以及 `edge_regression-custom` (用於邊緣迴歸)。
+ **`target_etype`** – 用於分類或迴歸的邊緣類型名稱。
+ **`property`** – 用於分類或迴歸的邊緣屬性名稱。

您的指令碼應該儲存模型參數，以及訓練結束時將需要的任何其他成品。

您可以使用 Neptune ML 工具組公用程式函數，來判斷所處理圖形資料的位置、應儲存模型參數的位置，以及訓練執行個體上可用的 GPU 裝置。如需如何使用這些公用程式函數的範例，請參閱 [train.py](https://github.com/awslabs/neptuneml-toolkit/blob/main/examples/custom-models/introduction/movie-lens-rgcn/node-class/src/train.py) 範例訓練指令碼。

## Neptune ML 中的自訂模型轉換指令碼開發
<a name="machine-learning-custom-model-transform-script"></a>

需要轉換指令碼，才能利用 Neptune ML [增量工作流程](machine-learning-overview-evolving-data-incremental.md#machine-learning-overview-incremental)，在不重新訓練模型的情況下，對不斷發展的圖形進行模型推論。即使模型部署所需的所有成品都是由訓練指令碼產生，但如果您想要在不重新訓練模型的情況下產生更新的模型，您仍然需要提供轉換指令碼。

**注意**  
自訂模型目前不支援[即時歸納推論](machine-learning-overview-evolving-data.md#inductive-vs-transductive-inference)。

您的自訂模型轉換指令碼應該是可執行的 Python 指令碼，例如 Neptune ML 工具組的 [transform.py](https://github.com/awslabs/neptuneml-toolkit/blob/main/examples/custom-models/introduction/movie-lens-rgcn/node-class/src/transform.py) 範例指令碼。因為這個指令碼是在模型訓練期間調用，沒有命令列引數，所以指令碼接受的任何命令列引數都必須具有預設值。

指令碼在 SageMaker AI 訓練執行個體上執行，語法如下：

```
python3 (your transform script entry point)
```

您的轉換指令碼將需要各項資訊，例如：
+ 所處理圖形資料的位置。
+ 儲存模型參數的位置，以及應儲存新模型成品的位置。
+ 可在執行個體上使用的裝置。
+ 已產生最佳模型的超參數。

這些輸入是使用指令碼可呼叫的 Neptune ML 公用程式函數來取得。如需如何執行此操作的範例，請參閱工具組的範例 [transform.py](https://github.com/awslabs/neptuneml-toolkit/blob/main/examples/custom-models/introduction/movie-lens-rgcn/node-class/src/transform.py) 指令碼。

指令碼應儲存節點嵌入、節點 ID 對應，以及每項任務的模型部署所需的任何其他成品。如需不同 Neptune ML 任務所需之模型成品的詳細資訊，請參閱[模型成品文件](machine-learning-model-artifacts.md)。

## Neptune ML 中的自訂 `model-hpo-configuration.json` 檔案
<a name="machine-learning-custom-model-hpo-configuration-file"></a>

`model-hpo-configuration.json` 檔案會針對您的自訂模型定義超參數。它的[格式](machine-learning-customizing-hyperparams.md)同於與 Neptune ML 內建模型搭配使用的 `model-hpo-configuration.json` 檔案，而且優先於 Neptune ML 自動產生並上傳到所處理資料位置的版本。

將新的超參數新增至您的模型時，您也必須為此檔案中的超參數新增一個項目，以便該超參數會傳遞至您的訓練指令碼。

如果您想要超參數可調校，則必須為這個超參數提供範圍，並將其設定為 `tier-1`、`tier-2`、或 `tier-3` 參數。如果設定的訓練工作總數允許調整其層中的超參數，則會調整超參數。對於不可調校的參數，您必須提供預設值，並將超參數新增至檔案的 `fixed-param` 區段。如需如何執行此操作的範例，請參閱工具組的[範例 `model-hpo-configuration.json` 檔案](https://github.com/awslabs/neptuneml-toolkit/blob/main/examples/custom-models/introduction/movie-lens-rgcn/node-class/src/model-hpo-configuration.json)範例。

您還必須提供指標定義，SageMaker AI HyperParameter 最佳化任務將用於評估訓練的候選模型。若要這樣做，您可以將 `eval_metric` JSON 物件新增至 `model-hpo-configuration.json` 檔案，如下所示：

```
"eval_metric": {
  "tuning_objective": {
      "MetricName": "(metric_name)",
      "Type": "Maximize"
  },
  "metric_definitions": [
    {
      "Name": "(metric_name)",
      "Regex": "(metric regular expression)"
    }
  ]
},
```

`eval_metric` 物件中的`metric_definitions`陣列會列出您希望 SageMaker AI 從訓練執行個體擷取的每個指標的指標定義物件。每個指標定義物件都有一個 `Name` 索引鍵，可讓您提供指標的名稱 (例如「accuracy」、「f1」等)。`Regex` 索引鍵可讓您提供一個規則表達式字串，與該特定指標在訓練日誌中列印的方式相符。如需如何定義指標的詳細資訊，請參閱 [SageMaker AI HyperParameter 調校頁面](https://docs.aws.amazon.com/sagemaker/latest/dg/automatic-model-tuning-define-metrics.html)。

然後，`eval_metric` 中的 `tuning_objective` 物件可讓您指定 `metric_definitions` 中的哪個指標應用作評估指標，做為超參數最佳化的目標指標。`MetricName` 的值必須與 `metric_definitions` 內其中一個定義中 `Name` 的值相符。`Type` 的值應該是「Maximize」或「Minimize」，取決於是否應將指標解譯為更大更好 (例如「accuracy」) 或更少更好 (例如「mean-squared-error」)。

`model-hpo-configuration.json` 檔案的此區段中的錯誤可能會導致 Neptune ML 模型訓練 API 任務失敗，因為 SageMaker AI HyperParameter 調校任務將無法選取最佳模型。

## 在 Neptune ML 中對您的自訂模型實作進行本機測試
<a name="machine-learning-custom-model-testing"></a>

您可以使用 Neptune ML 工具組 Conda 環境，在本機執行程式碼，以便測試並驗證您的模型。如果您是在 Neptune 筆記本執行個體上進行開發，則此 Conda 環境將預先安裝在 Neptune 筆記本執行個體執行個體上。如果您是在不同的執行個體上進行開發，則需要遵循 Neptune ML 工具組中的[本機設定指示](https://github.com/awslabs/neptuneml-toolkit#local-installation)。

當您呼叫[模型訓練 API](machine-learning-api-modeltraining.md) 時，Conda 環境會準確地重現模型將在其中執行的環境。所有範例訓練指令碼和轉換指令碼都可讓您傳遞命令列 `--local` 旗標，在本機環境中執行指令碼，進行輕鬆的偵錯。在開發自己的模型時，這是一個很好的做法，因為它可以讓您以互動方式並反覆測試模型實作。在 Neptune ML 生產訓練環境中進行模型訓練期間，會省略此參數。

# 建立要查詢的推論端點
<a name="machine-learning-on-graphs-inference-endpoint"></a>

推論端點可讓您查詢模型訓練程序所建構的特定模型。端點會附加至屬於給定類型且訓練程序能夠產生的最佳表現模型。然後，端點能夠接受來自 Neptune 的 Gemlin 查詢，並傳回該模型對查詢中輸入的預測。在您建立了推論端點之後，它會保持作用中狀態，直到您將其刪除為止。

## 管理 Neptune ML 的推論端點
<a name="machine-learning-on-graphs-endpoint-managing"></a>

在您從 Neptune 匯出的資料上完成了模型訓練之後，您可以使用 `curl` (或 `awscurl`) 命令建立推論端點，如下所示：

```
curl \
  -X POST https://(your Neptune endpoint)/ml/endpoints
  -H 'Content-Type: application/json' \
  -d '{
        "id" : "(a unique ID for the new endpoint)",
        "mlModelTrainingJobId": "(the model-training job-id of a completed job)"
      }'
```

您也可以從完成的模型轉換工作所建立的模型建立推論端點，方式大致相同：

```
curl \
  -X POST https://(your Neptune endpoint)/ml/endpoints
  -H 'Content-Type: application/json' \
  -d '{
        "id" : "(a unique ID for the new endpoint)",
        "mlModelTransformJobId": "(the model-transform job-id of a completed job)"
      }'
```

如何使用這些命令的詳細資訊會在 [endpoints 命令](machine-learning-api-endpoints.md) 加以說明，其中還有如何取得端點狀態、如何刪除端點，以及如何列出所有推論端點的相關資訊。

# Neptune ML 中的推論查詢
<a name="machine-learning-inference-queries"></a>

您可以使用 Gremlin 或 SPARQL，查詢 Neptune ML 推論端點。不過，目前僅 Gemlin 查詢支援[即時歸納推論](machine-learning-overview-evolving-data.md#inductive-vs-transductive-inference)。

# Neptune ML 中的 Gremlin 推論查詢
<a name="machine-learning-gremlin-inference-queries"></a>

如 [Neptune ML 功能](machine-learning.md#machine-learning-capabilities) 中所述，Neptune ML 支援可以執行下列各種推論任務的訓練模型：
+ **節點分類** – 預測頂點屬性的類別特徵。
+ **節點迴歸** – 預測頂點的數值屬性。
+ **邊緣分類** – 預測邊緣屬性的類別特徵。
+ **邊緣迴歸** – 預測邊緣的數值屬性。
+ **連結預測** – 鑑於來源節點和傳出邊緣預測目的地節點，或鑑於目的地節點和傳入邊緣指定來源節點。

我們可以透過使用 [GroupLens Research](https://grouplens.org/datasets/movielens/) 所提供的 [MovieLens 100k 資料集](https://grouplens.org/datasets/movielens/100k/)的範例來說明這些不同的任務。此資料集由電影、使用者和使用者對電影的評分組成，我們從中建立了一個屬性圖，如下所示：

![\[使用 MovieLens 100k 資料集的範例影片屬性圖\]](http://docs.aws.amazon.com/zh_tw/neptune/latest/userguide/images/movie_property_graph_example.png)


**節點分類**：在上述資料集中，`Genre` 是由邊緣 `included_in` 連線至頂點類型 `Movie` 的頂點類型。但是，如果我們調整資料集，使 `Genre` 成為頂點類型 `Movie` 的[類別](https://en.wikipedia.org/wiki/Categorical_variable)特徵，則為新增至我們知識圖譜的新電影推斷 `Genre` 的問題可以使用節點分類模型來解決。

**節點迴歸**：如果我們考慮頂點類型 `Rating`，它具有 `timestamp` 和 `score` 等屬性，則為 `Rating` 推斷數值 `Score` 的問題可以使用節點迴歸模型來解決。

**邊緣分類**：同樣地，對於 `Rated` 邊緣，如果我們有一個屬性 `Scale` 可以具有 `Love`、`Like`、`Dislike`、`Neutral`、`Hate` 其中一個值，則為新電影/評分的 `Rated` 邊緣推斷 `Scale` 的問題可以使用邊緣分類模型來解決。

**邊緣迴歸**：同樣地，對於相同的 `Rated` 邊緣，如果我們有一個屬性 `Score` 保留評分的數值，則這可以從邊緣迴歸模型推斷出來。

**連結預測**：尋找最有可能對給定電影評分的前十名使用者，或尋找給定使用者最有可能評分的前十部電影之類的問題屬於連結預測。

**注意**  
對於 Neptune ML 使用案例，我們有一組非常豐富的筆記本，旨在讓您實際了解每個使用案例。當您使用 Neptune [ML CloudFormation 範本建立 Neptune](machine-learning-quick-start.md) ML 叢集時，您可以建立這些筆記本和 Neptune 叢集。這些筆記本也可以在 [github](https://github.com/aws/graph-notebook/tree/main/src/graph_notebook/notebooks/04-Machine-Learning) 上取得。

**Topics**
+ [Gremlin 推論查詢中使用的 Neptune ML 述詞](machine-learning-gremlin-inference-query-predicates.md)
+ [Neptune ML 中的 Gremlin 節點分類查詢](machine-learning-gremlin-vertex-classification-queries.md)
+ [Neptune ML 中的 Gremlin 節點迴歸查詢](machine-learning-gremlin-vertex-regression-queries.md)
+ [Neptune ML 中的 Gremlin 邊緣分類查詢](machine-learning-gremlin-edge-classification-queries.md)
+ [Neptune ML 中的 Gremlin 邊緣迴歸查詢](machine-learning-gremlin-edge-regression.md)
+ [在 Neptune ML 中使用連結預測模型進行 Gremlin 連結預測查詢](machine-learning-gremlin-link-prediction-queries.md)
+ [Neptune ML Gremlin 推論查詢的例外狀況清單](machine-learning-gremlin-exceptions.md)

# Gremlin 推論查詢中使用的 Neptune ML 述詞
<a name="machine-learning-gremlin-inference-query-predicates"></a>

## `Neptune#ml.deterministic`
<a name="machine-learning-gremlin-inference-neptune-ml-deterministic-predicate"></a>

這個述詞是針對歸納推論查詢的選項，也就是，針對包含 [`Neptune#ml.inductiveInference`](#machine-learning-gremlin-inference-neptune-ml-inductiveInference) 述詞的查詢。

使用歸納推斷時，Neptune 引擎會建立適當的子圖來評估訓練後的 GNN 模型，而這個子圖的需求取決於最終模型的參數。尤其，`num-layer` 參數會決定來自目標節點或邊緣的周遊躍點數目，而 `fanouts` 參數則會指定要在每個躍點上取樣的鄰近項目數 (請參閱 [HPO 參數](machine-learning-customizing-hyperparams.md))。

根據預設，歸納推論查詢會在非確定性模式下執行，其中 Neptune 會隨機建置鄰域。在進行預測時，這種正常的隨機鄰近項目抽樣有時會導致不同的預測。

當您在歸納推論查詢中包含 `Neptune#ml.deterministic` 時，Neptune 引擎會嘗試以確定性的方式對鄰近項目進行取樣，以便相同查詢的多次調用，每次都會傳回相同的結果。不過，不能保證結果是完全確定的，因為對分散式系統的基礎圖形和成品的變更仍然可能會引起波動。

您可以在查詢中包含 `Neptune#ml.deterministic` 述詞，如下所示：

```
.with("Neptune#ml.deterministic")
```

如果包含 `Neptune#ml.deterministic` 述詞的查詢中未同時包含 `Neptune#ml.inductiveInference`，則只需將其忽略即可。

## `Neptune#ml.disableInductiveInferenceMetadataCache`
<a name="machine-learning-gremlin-disableInductiveInferenceMetadataCache-predicate"></a>

這個述詞是針對歸納推論查詢的選項，也就是，針對包含 [`Neptune#ml.inductiveInference`](#machine-learning-gremlin-inference-neptune-ml-inductiveInference) 述詞的查詢。

對於歸納推論查詢，Neptune 會使用儲存在 Amazon S3 中的中繼資料檔案，以在建立鄰域時決定躍點數和扇出數。Neptune 通常會快取此模型中繼資料，以避免重複從 Amazon S3 擷取檔案。可在查詢中包含 `Neptune#ml.disableInductiveInferenceMetadataCache` 述詞來停用快取。雖然 Neptune 直接從 Amazon S3 擷取中繼資料可能較慢，但當 SageMaker AI 端點在重新訓練或轉換後更新且快取過時時，此功能非常有用。

您可以在查詢中包含 `Neptune#ml.disableInductiveInferenceMetadataCache` 述詞，如下所示：

```
.with("Neptune#ml.disableInductiveInferenceMetadataCache")
```

以下是查詢範例在 Jupyter 筆記本中的可能樣子：

```
%%gremlin
g.with("Neptune#ml.endpoint", "ep1")
 .with("Neptune#ml.iamRoleArn", "arn:aws:iam::123456789012:role/NeptuneMLRole")
 .with("Neptune#ml.disableInductiveInferenceMetadataCache")
 .V('101').properties("rating")
 .with("Neptune#ml.regression")
 .with("Neptune#ml.inductiveInference")
```

## `Neptune#ml.endpoint`
<a name="machine-learning-gremlin-inference-neptune-ml-endpoint-predicate"></a>

`Neptune#ml.endpoint` 述詞會在 `with()` 步驟中用來指定推論端點 (如有必要)：

```
 .with("Neptune#ml.endpoint", "the model's SageMaker AI inference endpoint")
```

您可以透過端點 `id` 或其 URL 來識別端點。例如：

```
 .with( "Neptune#ml.endpoint", "node-classification-movie-lens-endpoint" )
```

或者：

```
 .with( "Neptune#ml.endpoint", "https://runtime.sagemaker.us-east-1.amazonaws.com/endpoints/node-classification-movie-lens-endpoint/invocations" )
```

**注意**  
如果您將 Neptune 資料庫叢集參數群組中的 [`neptune_ml_endpoint` 參數](machine-learning-cluster-setup.md#machine-learning-set-inference-endpoint-cluster-parameter)設定為端點 `id` 或 URL，則不需要在每個查詢中包含 `Neptune#ml.endpoint` 述詞。

## `Neptune#ml.iamRoleArn`
<a name="machine-learning-gremlin-inference-neptune-ml-iamRoleArn-predicate"></a>

`Neptune#ml.iamRoleArn` 會視需要在`with()`步驟中使用，以指定 SageMaker AI 執行 IAM 角色的 ARN：

```
 .with("Neptune#ml.iamRoleArn", "the ARN for the SageMaker AI execution IAM role")
```

如需如何建立 SageMaker AI 執行 IAM 角色的資訊，請參閱 [建立自訂 NeptuneSageMakerIAMRole 角色](machine-learning-manual-setup.md#ml-manual-setup-sm-role)。

**注意**  
如果您在 Neptune 資料庫叢集參數群組中[將 `neptune_ml_iam_role` 參數](machine-learning-cluster-setup.md#machine-learning-enabling-create-param-group)設定為 SageMaker AI 執行 IAM 角色的 ARN，則不需要在每個查詢中包含`Neptune#ml.iamRoleArn`述詞。

## Neptune\$1ml.inductiveInference
<a name="machine-learning-gremlin-inference-neptune-ml-inductiveInference"></a>

預設會在 Gremlin 中啟用直推式推論。若要進行[即時直推式推論](machine-learning-overview-evolving-data.md#inductive-vs-transductive-inference)查詢，請包含如下 `Neptune#ml.inductiveInference` 述詞：

```
.with("Neptune#ml.inductiveInference")
```

如果您的圖形是動態的，歸納推論通常是最佳選擇，但是如果您的圖形是靜態的，則直推式推論更快、更有效率。

## `Neptune#ml.limit`
<a name="machine-learning-gremlin-inference-neptune-ml-limit-predicate"></a>

`Neptune#ml.limit` 述詞可以選擇性地限制每個實體傳回的結果數量：

```
 .with( "Neptune#ml.limit", 2 )
```

根據預設，限制為 1，但可以設定的數量上限為 100。

## `Neptune#ml.threshold`
<a name="machine-learning-gremlin-inference-neptune-ml-threshold-predicate"></a>

`Neptune#ml.threshold` 述詞可以選擇性地建立結果分數的截止閾值：

```
 .with( "Neptune#ml.threshold", 0.5D )
```

這可讓您捨棄分數低於指定閾值的所有結果。

## `Neptune#ml.classification`
<a name="machine-learning-gremlin-inference-neptune-ml-classification-predicate"></a>

`Neptune#ml.classification` 述詞會連接到 `properties()` 步驟，以確定需要從節點分類模型的 SageMaker AI 端點擷取屬性：

```
 .properties( "property key of the node classification model" ).with( "Neptune#ml.classification" )
```

## `Neptune#ml.regression`
<a name="machine-learning-gremlin-inference-neptune-ml-regression-predicate"></a>

`Neptune#ml.regression` 述詞會連接到 `properties()` 步驟，以確定需要從節點迴歸模型的 SageMaker AI 端點擷取屬性：

```
 .properties( "property key of the node regression model" ).with( "Neptune#ml.regression" )
```

## `Neptune#ml.prediction`
<a name="machine-learning-gremlin-inference-neptune-ml-prediction-predicate"></a>

`Neptune#ml.prediction` 述詞會附加到 `in()` 和 `out()` 步驟，以確定這是連結預測查詢：

```
 .in("edge label of the link prediction model").with("Neptune#ml.prediction").hasLabel("target node label")
```

## `Neptune#ml.score`
<a name="machine-learning-gremlin-inference-neptune-ml-score-predicate"></a>

`Neptune#ml.score` 述詞用於 Gemlin 節點或邊緣分類查詢中，以擷取機器學習可信度分數。`Neptune#ml.score` 述詞應該與 `properties()` 步驟中的查詢述詞一起傳遞，以取得節點或邊緣分類查詢的 ML 可信度分數。

您可以在節點分類區段中找到包含[其他節點分類範例](machine-learning-gremlin-vertex-classification-queries.md#machine-learning-gremlin-node-class-other-queries)的[節點分類範例，以及邊緣](machine-learning-gremlin-edge-classification-queries.md)分類範例。

# Neptune ML 中的 Gremlin 節點分類查詢
<a name="machine-learning-gremlin-vertex-classification-queries"></a>

對於 Neptune ML 中的 Gremlin 節點分類：
+ 模型根據頂點的一個屬性進行訓練。這個屬性的唯一值集被稱為節點類別集，或者簡稱為類別。
+ 頂點屬性的節點類別屬性值可從節點分類模型中推斷出來。這在此屬性尚未附加至頂點時很有用。
+ 為了從節點分類模型中擷取一個或多個類別，您需要使用 `with()` 步驟搭配述詞 `Neptune#ml.classification` 來設定 `properties()` 步驟。如果輸出格式是頂點屬性，則輸出格式與您所期望的格式相似。

**注意**  
節點分類僅會使用字串屬性值。這表示不支援數值屬性值 (例如 `0` 或 `1`)，儘管字串等同於 `"0"` 和 `"1"`。同樣地，布林屬性值 `true` 和 `false` 不起作用，但 `"true"` 和 `"false"` 可以。

以下是範例節點分類查詢：

```
g.with( "Neptune#ml.endpoint","node-classification-movie-lens-endpoint" )
 .with( "Neptune#ml.iamRoleArn","arn:aws:iam::0123456789:role/sagemaker-role" )
 .with( "Neptune#ml.limit", 2 )
 .with( "Neptune#ml.threshold", 0.5D )
 .V( "movie_1", "movie_2", "movie_3" )
 .properties("genre").with("Neptune#ml.classification")
```

此查詢的輸出如下所示：

```
==>vp[genre->Action]
==>vp[genre->Crime]
==>vp[genre->Comedy]
```

在上述查詢中，`V()` 和 `properties()` 步驟的使用方式如下：

`V()` 步驟包含您要從節點分類模型中擷取其類別的頂點集：

```
 .V( "movie_1", "movie_2", "movie_3" )
```

`properties()` 步驟包含模型訓練時根據的索引鍵，而且具有 `.with("Neptune#ml.classification")` 指示這是節點分類 ML 推論查詢。

`properties().with("Neptune#ml.classification")` 步驟中目前不支援多個內容索引鍵。例如，下列查詢會導致例外狀況：

```
g.with("Neptune#ml.endpoint", "node-classification-movie-lens-endpoint")
 .with("Neptune#ml.iamRoleArn","arn:aws:iam::0123456789:role/sagemaker-role")
 .V( "movie_1", "movie_2", "movie_3" )
 .properties("genre", "other_label").with("Neptune#ml.classification")
```

如需特定錯誤訊息，請參閱 [Neptune ML 例外狀況清單](machine-learning-gremlin-exceptions.md)。

`properties().with("Neptune#ml.classification")` 步驟可與下列任一步驟搭配使用：
+ `value()`
+ `value().is()`
+ `hasValue()`
+ `has(value,"")`
+ `key()`
+ `key().is()`
+ `hasKey()`
+ `has(key,"")`
+ `path()`

## 其他節點分類查詢
<a name="machine-learning-gremlin-node-class-other-queries"></a>

如果推論端點和對應的 IAM 角色都已儲存在您的資料庫叢集參數群組中，則節點分類查詢可以簡單的如下所示：

```
g.V("movie_1", "movie_2", "movie_3").properties("genre").with("Neptune#ml.classification")
```

您可以使用 `union()` 步驟，在查詢中混合頂點屬性和類別：

```
g.with("Neptune#ml.endpoint","node-classification-movie-lens-endpoint")
 .with("Neptune#ml.iamRoleArn","arn:aws:iam::0123456789:role/sagemaker-role")
 .V( "movie_1", "movie_2", "movie_3" )
 .union(
   properties("genre").with("Neptune#ml.classification"),
   properties("genre")
 )
```

您也可以建立無限制的查詢，如下所示：

```
g.with("Neptune#ml.endpoint","node-classification-movie-lens-endpoint")
 .with("Neptune#ml.iamRoleArn","arn:aws:iam::0123456789:role/sagemaker-role")
 .V()
 .properties("genre").with("Neptune#ml.classification")
```

您可以使用 `select()` 步驟搭配 `as()` 步驟來擷取節點類別以及頂點：

```
g.with("Neptune#ml.endpoint","node-classification-movie-lens-endpoint")
 .with("Neptune#ml.iamRoleArn","arn:aws:iam::0123456789:role/sagemaker-role")
 .V( "movie_1", "movie_2", "movie_3" ).as("vertex")
 .properties("genre").with("Neptune#ml.classification").as("properties")
 .select("vertex","properties")
```

您也可以根據節點類別篩選，如下列範例所示：

```
g.with("Neptune#ml.endpoint", "node-classification-movie-lens-endpoint")
 .with("Neptune#ml.iamRoleArn","arn:aws:iam::0123456789:role/sagemaker-role")
 .V( "movie_1", "movie_2", "movie_3" )
 .properties("genre").with("Neptune#ml.classification")
 .has(value, "Horror")

g.with("Neptune#ml.endpoint","node-classification-movie-lens-endpoint")
 .with("Neptune#ml.iamRoleArn","arn:aws:iam::0123456789:role/sagemaker-role")
 .V( "movie_1", "movie_2", "movie_3" )
 .properties("genre").with("Neptune#ml.classification")
 .has(value, P.eq("Action"))

g.with("Neptune#ml.endpoint","node-classification-movie-lens-endpoint")
 .with("Neptune#ml.iamRoleArn","arn:aws:iam::0123456789:role/sagemaker-role")
 .V( "movie_1", "movie_2", "movie_3" )
 .properties("genre").with("Neptune#ml.classification")
 .has(value, P.within("Action", "Horror"))
```

您可以使用 `Neptune#ml.score` 述詞，取得節點分類可信度分數：

```
 g.with("Neptune#ml.endpoint","node-classification-movie-lens-endpoint")
 .with("Neptune#ml.iamRoleArn","arn:aws:iam::0123456789:role/sagemaker-role")
 .V( "movie_1", "movie_2", "movie_3" )
 .properties("genre", "Neptune#ml.score").with("Neptune#ml.classification")
```

回應看起來像這樣：

```
==>vp[genre->Action]
==>vp[Neptune#ml.score->0.01234567]
==>vp[genre->Crime]
==>vp[Neptune#ml.score->0.543210]
==>vp[genre->Comedy]
==>vp[Neptune#ml.score->0.10101]
```

## 在節點分類查詢中使用歸納推論
<a name="machine-learning-gremlin-node-class-inductive"></a>

假設您要在 Jupyter 筆記本中將新節點新增至現有圖形，如下所示：

```
%%gremlin
g.addV('label1').property(id,'101').as('newV')
 .V('1').as('oldV1')
 .V('2').as('oldV2')
 .addE('eLabel1').from('newV').to('oldV1')
 .addE('eLabel2').from('oldV2').to('newV')
```

您接著可以使用歸納推論查詢，取得反映了新節點的類型和可信度分數：

```
%%gremlin
g.with("Neptune#ml.endpoint", "nc-ep")
 .with("Neptune#ml.iamRoleArn", "arn:aws:iam::123456789012:role/NeptuneMLRole")
 .V('101').properties("genre", "Neptune#ml.score")
 .with("Neptune#ml.classification")
 .with("Neptune#ml.inductiveInference")
```

不過，如果您執行了多次查詢，則可能會得到有些不同的結果：

```
# First time
==>vp[genre->Action]
==>vp[Neptune#ml.score->0.12345678]

# Second time
==>vp[genre->Action]
==>vp[Neptune#ml.score->0.21365921]
```

你可以使相同的查詢具有確定性：

```
%%gremlin
g.with("Neptune#ml.endpoint", "nc-ep")
 .with("Neptune#ml.iamRoleArn", "arn:aws:iam::123456789012:role/NeptuneMLRole")
 .V('101').properties("genre", "Neptune#ml.score")
 .with("Neptune#ml.classification")
 .with("Neptune#ml.inductiveInference")
 .with("Neptune#ml.deterministic")
```

在這種情況下，每次結果將大致相同：

```
# First time
==>vp[genre->Action]
==>vp[Neptune#ml.score->0.12345678]
# Second time
==>vp[genre->Action]
==>vp[Neptune#ml.score->0.12345678]
```

# Neptune ML 中的 Gremlin 節點迴歸查詢
<a name="machine-learning-gremlin-vertex-regression-queries"></a>

節點迴歸類似於節點分類，不同之處在於從每個節點的迴歸模型推斷出的值是數值。您可以使用與節點分類相同的 Gremlin 查詢進行節點迴歸，但以下差異除外：
+ 同樣，在 Neptune ML 中，節點指的是頂點。
+ `properties()` 步驟接受形式 `properties().with("Neptune#ml.regression")` 而不是 `properties().with("Neptune#ml.classification")`。
+ `"Neptune#ml.limit`" 和 `"Neptune#ml.threshold"` 述詞不適用。
+ 根據值進行篩選時，您必須指定一個數值。

以下是範例頂點分類查詢：

```
g.with("Neptune#ml.endpoint","node-regression-movie-lens-endpoint")
 .with("Neptune#ml.iamRoleArn", "arn:aws:iam::0123456789:role/sagemaker-role")
 .V("movie_1","movie_2","movie_3")
 .properties("revenue").with("Neptune#ml.regression")
```

您可以根據使用迴歸模型推斷出的值進行篩選，如下列範例所示：

```
g.with("Neptune#ml.endpoint","node-regression-movie-lens-endpoint")
 .with("Neptune#ml.iamRoleArn","arn:aws:iam::0123456789:role/sagemaker-role")
 .V("movie_1","movie_2","movie_3")
 .properties("revenue").with("Neptune#ml.regression")
 .value().is(P.gte(1600000))

g.with("Neptune#ml.endpoint","node-regression-movie-lens-endpoint")
 .with("Neptune#ml.iamRoleArn","arn:aws:iam::0123456789:role/sagemaker-role")
 .V("movie_1","movie_2","movie_3")
 .properties("revenue").with("Neptune#ml.regression")
 .hasValue(P.lte(1600000D))
```

## 在節點迴歸查詢中使用歸納推論
<a name="machine-learning-gremlin-node-regress-inductive"></a>

假設您要在 Jupyter 筆記本中將新節點新增至現有圖形，如下所示：

```
%%gremlin
g.addV('label1').property(id,'101').as('newV')
 .V('1').as('oldV1')
 .V('2').as('oldV2')
 .addE('eLabel1').from('newV').to('oldV1')
 .addE('eLabel2').from('oldV2').to('newV')
```

然後，您可以使用歸納推論查詢，來取得考慮到新節點的評分：

```
%%gremlin
g.with("Neptune#ml.endpoint", "nr-ep")
 .with("Neptune#ml.iamRoleArn", "arn:aws:iam::123456789012:role/NeptuneMLRole")
 .V('101').properties("rating")
 .with("Neptune#ml.regression")
 .with("Neptune#ml.inductiveInference")
```

因為查詢不具確定性，所以如果根據鄰域多次執行該查詢，其可能會傳回有些不同的結果：

```
# First time
==>vp[rating->9.1]

# Second time
==>vp[rating->8.9]
```

如果需要更一致的結果，您可以使查詢具有確定性：

```
%%gremlin
g.with("Neptune#ml.endpoint", "nc-ep")
 .with("Neptune#ml.iamRoleArn", "arn:aws:iam::123456789012:role/NeptuneMLRole")
 .V('101').properties("rating")
 .with("Neptune#ml.regression")
 .with("Neptune#ml.inductiveInference")
 .with("Neptune#ml.deterministic")
```

現在每次結果都會大致相同：

```
# First time
==>vp[rating->9.1]

# Second time
==>vp[rating->9.1]
```

# Neptune ML 中的 Gremlin 邊緣分類查詢
<a name="machine-learning-gremlin-edge-classification-queries"></a>

對於 Neptune ML 中的 Gremlin 邊緣分類：
+ 模型根據邊緣的一個屬性進行訓練。這個屬性的唯一值集被稱為類別集。
+ 邊緣的類別屬性值可從邊緣分類模型推斷出來，這在此屬性尚未附加至邊緣時很有用。
+ 為了從邊緣分類模型中擷取一個或多個類別，您需要使用 `with()` 步驟搭配述詞 `"Neptune#ml.classification"` 來設定 `properties()` 步驟。如果輸出格式是邊緣邊緣屬性，則輸出格式與您所期望的格式相似。

**注意**  
邊緣分類僅會使用字串屬性值。這表示不支援數值屬性值 (例如 `0` 或 `1`)，儘管字串等同於 `"0"` 和 `"1"`。同樣地，布林屬性值 `true` 和 `false` 不起作用，但 `"true"` 和 `"false"` 可以。

以下是邊緣分類查詢的範例，其會使用 `Neptune#ml.score` 述詞請求可信度分數：

```
g.with("Neptune#ml.endpoint","edge-classification-movie-lens-endpoint")
 .with("Neptune#ml.iamRoleArn","arn:aws:iam::0123456789:role/sagemaker-role")
 .E("relationship_1","relationship_2","relationship_3")
 .properties("knows_by", "Neptune#ml.score").with("Neptune#ml.classification")
```

回應看起來像這樣：

```
==>p[knows_by->"Family"]
==>p[Neptune#ml.score->0.01234567]
==>p[knows_by->"Friends"]
==>p[Neptune#ml.score->0.543210]
==>p[knows_by->"Colleagues"]
==>p[Neptune#ml.score->0.10101]
```

## Gremlin 邊緣分類查詢的語法
<a name="machine-learning-gremlin-edge-classification-syntax"></a>

對於簡單圖形，其中 `User` 是前端和尾端節點，且 `Relationship` 是連線它們的邊緣，範例邊緣分類查詢如下：

```
g.with("Neptune#ml.endpoint","edge-classification-social-endpoint")
 .with("Neptune#ml.iamRoleArn","arn:aws:iam::0123456789:role/sagemaker-role")
 .E("relationship_1","relationship_2","relationship_3")
 .properties("knows_by").with("Neptune#ml.classification")
```

此查詢的輸出如下所示：

```
==>p[knows_by->"Family"]
==>p[knows_by->"Friends"]
==>p[knows_by->"Colleagues"]
```

在上述查詢中，`E()` 和 `properties()` 步驟的使用方式如下：
+ `E()` 步驟包含您要從邊緣分類模型中擷取其類別的邊緣集：

  ```
  .E("relationship_1","relationship_2","relationship_3")
  ```
+ `properties()` 步驟包含模型訓練時根據的索引鍵，而且具有 `.with("Neptune#ml.classification")` 指示這是邊緣分類 ML 推論查詢。

`properties().with("Neptune#ml.classification")` 步驟中目前不支援多個內容索引鍵。例如，下列查詢會導致擲出例外狀況：

```
g.with("Neptune#ml.endpoint","edge-classification-social-endpoint")
 .with("Neptune#ml.iamRoleArn","arn:aws:iam::0123456789:role/sagemaker-role")
 .E("relationship_1","relationship_2","relationship_3")
 .properties("knows_by", "other_label").with("Neptune#ml.classification")
```

如需特定錯誤訊息，請參閱 [Neptune ML Gremlin 推論查詢的例外狀況清單](machine-learning-gremlin-exceptions.md)。

`properties().with("Neptune#ml.classification")` 步驟可與下列任一步驟搭配使用：
+ `value()`
+ `value().is()`
+ `hasValue()`
+ `has(value,"")`
+ `key()`
+ `key().is()`
+ `hasKey()`
+ `has(key,"")`
+ `path()`

## 在邊緣分類查詢中使用歸納推論
<a name="machine-learning-gremlin-edge-class-inductive"></a>

假設您要在 Jupyter 筆記本中將新邊緣新增至現有圖形，如下所示：

```
%%gremlin
g.V('1').as('fromV')
.V('2').as('toV')
.addE('eLabel1').from('fromV').to('toV').property(id, 'e101')
```

然後，您可以使用歸納推論查詢，來取得考慮到新邊緣的範圍：

```
%%gremlin
g.with("Neptune#ml.endpoint", "ec-ep")
 .with("Neptune#ml.iamRoleArn", "arn:aws:iam::123456789012:role/NeptuneMLRole")
 .E('e101').properties("scale", "Neptune#ml.score")
 .with("Neptune#ml.classification")
 .with("Neptune#ml.inductiveInference")
```

因為查詢不具確定性，所以如果根據隨機鄰域多次執行該查詢，結果將會有些不同：

```
# First time
==>vp[scale->Like]
==>vp[Neptune#ml.score->0.12345678]

# Second time
==>vp[scale->Like]
==>vp[Neptune#ml.score->0.21365921]
```

如果需要更一致的結果，您可以使查詢具有確定性：

```
%%gremlin
g.with("Neptune#ml.endpoint", "ec-ep")
 .with("Neptune#ml.iamRoleArn", "arn:aws:iam::123456789012:role/NeptuneMLRole")
 .E('e101').properties("scale", "Neptune#ml.score")
 .with("Neptune#ml.classification")
 .with("Neptune#ml.inductiveInference")
 .with("Neptune#ml.deterministic")
```

現在，每次執行查詢時，結果都會或多或少相同：

```
# First time
==>vp[scale->Like]
==>vp[Neptune#ml.score->0.12345678]

# Second time
==>vp[scale->Like]
==>vp[Neptune#ml.score->0.12345678]
```

# Neptune ML 中的 Gremlin 邊緣迴歸查詢
<a name="machine-learning-gremlin-edge-regression"></a>

邊緣迴歸類似於邊緣分類，不同之處在於從 ML 模型推斷出的值是數值。對於邊緣迴歸，Neptune ML 支援與分類相同的查詢。

需要注意的要點如下：
+ 您必須使用 ML 述詞 `"Neptune#ml.regression"`，針對此使用案例設定 `properties()` 步驟。
+ `"Neptune#ml.limit"` 和 `"Neptune#ml.threshold"` 述詞不適用於此使用案例。
+ 如需根據值進行過濾，您需要將該值指定為數值。

## Gremlin 邊緣迴歸查詢的語法
<a name="machine-learning-gremlin-edge-regression-syntax"></a>

對於簡單圖形，其中 `User` 是前端節點、`Movie` 是尾端節點，以及 `Rated` 是連接它們的邊緣，以下是一個範例邊緣迴歸查詢，其會尋找邊緣 `Rated` 的數值評分值，在這裡稱為分數：

```
g.with("Neptune#ml.endpoint","edge-regression-movie-lens-endpoint")
 .with("Neptune#ml.iamRoleArn","arn:aws:iam::0123456789:role/sagemaker-role")
 .E("rating_1","rating_2","rating_3")
 .properties("score").with("Neptune#ml.regression")
```

您也可以根據從 ML 迴歸模型推斷出的值進行篩選。對於由 `"rating_1"`、`"rating_2"` 和 `"rating_3"` 所識別的現有 `Rated` 邊緣 (從 `User` 到 `Movie`)，其中這些評分不存在邊緣屬性 `Score`，您可以使用如下查詢來推斷邊緣的 `Score`，其中它大於或等於 9：

```
g.with("Neptune#ml.endpoint","edge-regression-movie-lens-endpoint")
 .with("Neptune#ml.iamRoleArn","arn:aws:iam::0123456789:role/sagemaker-role")
 .E("rating_1","rating_2","rating_3")
 .properties("score").with("Neptune#ml.regression")
 .value().is(P.gte(9))
```

## 在邊緣迴歸查詢中使用歸納推論
<a name="machine-learning-gremlin-edge-regression-inductive"></a>

假設您要在 Jupyter 筆記本中將新邊緣新增至現有圖形，如下所示：

```
%%gremlin
g.V('1').as('fromV')
.V('2').as('toV')
.addE('eLabel1').from('fromV').to('toV').property(id, 'e101')
```

然後，您可以使用歸納推論查詢，來取得考慮到新邊緣的分數：

```
%%gremlin
g.with("Neptune#ml.endpoint", "er-ep")
 .with("Neptune#ml.iamRoleArn", "arn:aws:iam::123456789012:role/NeptuneMLRole")
 .E('e101').properties("score")
 .with("Neptune#ml.regression")
 .with("Neptune#ml.inductiveInference")
```

因為查詢不具確定性，所以如果根據隨機鄰域多次執行該查詢，結果將會有些不同：

```
# First time
==>ep[score->96]

# Second time
==>ep[score->91]
```

如果需要更一致的結果，您可以使查詢具有確定性：

```
%%gremlin
g.with("Neptune#ml.endpoint", "er-ep")
 .with("Neptune#ml.iamRoleArn", "arn:aws:iam::123456789012:role/NeptuneMLRole")
 .E('e101').properties("score")
 .with("Neptune#ml.regression")
 .with("Neptune#ml.inductiveInference")
 .with("Neptune#ml.deterministic")
```

現在，每次執行查詢時，結果都會或多或少相同：

```
# First time
==>ep[score->96]

# Second time
==>ep[score->96]
```

# 在 Neptune ML 中使用連結預測模型進行 Gremlin 連結預測查詢
<a name="machine-learning-gremlin-link-prediction-queries"></a>

連結預測模型可以解決如下問題：
+ **前端節點預測**：鑑於頂點和邊緣類型，該頂點可能從哪些頂點連結？
+ **尾端節點預測**：鑑於頂點和邊緣標籤，該頂點可能連結至哪些頂點？

**注意**  
Neptune ML 中尚未支援邊緣預測。

對於下面範例，考慮其中頂點 `User` 和 `Movie` 是由邊緣 `Rated` 連結的簡單圖形。

以下是範例前端節點預測查詢，用來預測最有可能評分電影 (`"movie_1"`、`"movie_2"` 和 `"movie_3"`) 的前五名使用者：

```
g.with("Neptune#ml.endpoint","node-prediction-movie-lens-endpoint")
 .with("Neptune#ml.iamRoleArn","arn:aws:iam::0123456789:role/sagemaker-role")
 .with("Neptune#ml.limit", 5)
 .V("movie_1", "movie_2", "movie_3")
 .in("rated").with("Neptune#ml.prediction").hasLabel("user")
```

以下是用於尾端節點預測的類似查詢，用來預測使用者 `"user_1"` 可能評分的前五名電影：

```
g.with("Neptune#ml.endpoint","node-prediction-movie-lens-endpoint")
 .with("Neptune#ml.iamRoleArn","arn:aws:iam::0123456789:role/sagemaker-role")
 .V("user_1")
 .out("rated").with("Neptune#ml.prediction").hasLabel("movie")
```

邊緣標籤和預測的頂點標籤都是必要的。如果省略其中一個，則會擲出例外狀況。例如，以下查詢沒有預測的頂點標籤，其會擲回例外狀況：

```
g.with("Neptune#ml.endpoint","node-prediction-movie-lens-endpoint")
 .with("Neptune#ml.iamRoleArn","arn:aws:iam::0123456789:role/sagemaker-role")
 .V("user_1")
 .out("rated").with("Neptune#ml.prediction")
```

同樣地，沒有邊緣標籤的下列查詢也會擲回例外狀況：

```
g.with("Neptune#ml.endpoint","node-prediction-movie-lens-endpoint")
 .with("Neptune#ml.iamRoleArn","arn:aws:iam::0123456789:role/sagemaker-role")
 .V("user_1")
 .out().with("Neptune#ml.prediction").hasLabel("movie")
```

如需這些例外狀況傳回的特定錯誤訊息，請參閱 [Neptune ML 例外狀況清單](machine-learning-gremlin-exceptions.md)。

## 其他連結預測查詢
<a name="machine-learning-gremlin-other-link-prediction-queries"></a>

您可以使用 `select()` 步驟搭配 `as(`) 步驟，以同時輸出預測的頂點與輸入頂點：

```
g.with("Neptune#ml.endpoint","node-prediction-movie-lens-endpoint")
 .with("Neptune#ml.iamRoleArn","arn:aws:iam::0123456789:role/sagemaker-role")
 .V("movie_1").as("source")
 .in("rated").with("Neptune#ml.prediction").hasLabel("user").as("target")
 .select("source","target")

g.with("Neptune#ml.endpoint","node-prediction-movie-lens-endpoint")
 .with("Neptune#ml.iamRoleArn","arn:aws:iam::0123456789:role/sagemaker-role")
 .V("user_1").as("source")
 .out("rated").with("Neptune#ml.prediction").hasLabel("movie").as("target")
 .select("source","target")
```

您可以進行無限制查詢，如下所示：

```
g.with("Neptune#ml.endpoint","node-prediction-movie-lens-endpoint")
 .with("Neptune#ml.iamRoleArn","arn:aws:iam::0123456789:role/sagemaker-role")
 .V("user_1")
 .out("rated").with("Neptune#ml.prediction").hasLabel("movie")

g.with("Neptune#ml.endpoint","node-prediction-movie-lens-endpoint")
 .with("Neptune#ml.iamRoleArn","arn:aws:iam::0123456789:role/sagemaker-role")
 .V("movie_1")
 .in("rated").with("Neptune#ml.prediction").hasLabel("user")
```

## 在連結預測查詢中使用歸納推論
<a name="machine-learning-gremlin-link-predict-inductive"></a>

假設您要在 Jupyter 筆記本中將新節點新增至現有圖形，如下所示：

```
%%gremlin
g.addV('label1').property(id,'101').as('newV1')
 .addV('label2').property(id,'102').as('newV2')
 .V('1').as('oldV1')
 .V('2').as('oldV2')
 .addE('eLabel1').from('newV1').to('oldV1')
 .addE('eLabel2').from('oldV2').to('newV2')
```

然後，您可以使用歸納推論查詢來預測前端節點，同時考慮到新節點：

```
%%gremlin
g.with("Neptune#ml.endpoint", "lp-ep")
 .with("Neptune#ml.iamRoleArn", "arn:aws:iam::123456789012:role/NeptuneMLRole")
 .V('101').out("eLabel1")
 .with("Neptune#ml.prediction")
 .with("Neptune#ml.inductiveInference")
 .hasLabel("label2")
```

結果：

```
==>V[2]
```

同樣地，您可以使用歸納推論查詢來預測尾端節點，同時考慮到新節點：

```
%%gremlin
g.with("Neptune#ml.endpoint", "lp-ep")
 .with("Neptune#ml.iamRoleArn", "arn:aws:iam::123456789012:role/NeptuneMLRole")
 .V('102').in("eLabel2")
 .with("Neptune#ml.prediction")
 .with("Neptune#ml.inductiveInference")
 .hasLabel("label1")
```

結果：

```
==>V[1]
```

# Neptune ML Gremlin 推論查詢的例外狀況清單
<a name="machine-learning-gremlin-exceptions"></a>

 這是執行 Neptune ML Gremlin 推論查詢時可能發生的例外狀況完整清單。這些例外狀況涵蓋一系列問題，從指定 IAM 角色或端點的問題，到每個查詢的 ML 推論查詢數量不受支援的 Gremlin 步驟和限制。每個項目都包含描述問題的詳細訊息。
+ **`BadRequestException`** – 無法載入所提供角色的憑證。

  *訊息*：`Unable to load credentials for role: the specified IAM Role ARN.`
+ **`BadRequestException`**   –   指定的 IAM 角色無權叫用 SageMaker AI 端點。

  *訊息*：`User: the specified IAM Role ARN is not authorized to perform: sagemaker:InvokeEndpoint on resource: the specified endpoint.`
+ **`BadRequestException`** – 指定的端點不存在。

  *訊息*：`Endpoint the specified endpoint not found.`
+ **`InternalFailureException`** – 無法從 Amazon S3 擷取 Neptune ML 即時歸納推論中繼資料。

  *訊息*：`Unable to fetch Neptune ML - Real-Time Inductive Inference metadata from S3. Check the permissions of the S3 bucket or if the Neptune instance can connect to S3.`
+ **`InternalFailureException`** – Neptune ML 無法在 Amazon S3 中找到用於即時歸納推論的中繼資料檔案。

  *訊息*：`Neptune ML cannot find the metadata file for Real-Time Inductive Inference in S3.`
+ **`InvalidParameterException`** – 指定的端點在語法上無效。

  *訊息*：`Invalid endpoint provided for external service query.`
+ **`InvalidParameterException`** – 指定的 SageMaker 執行 IAM 角色 ARN 在語法上無效。

  *訊息*：`Invalid IAM role ARN provided for external service query.`
+ **`InvalidParameterException`** – 在查詢的 `properties()` 步驟中指定多個屬性索引鍵。

  *訊息*：`ML inference queries are currently supported for one property key.`
+ **`InvalidParameterException`** – 在查詢中指定多個邊緣標籤。

  *訊息*：`ML inference are currently supported only with one edge label.`
+ **`InvalidParameterException`** – 在查詢中指定多個頂點標籤限制條件。

  *訊息*：`ML inference are currently supported only with one vertex label constraint.`
+ **`InvalidParameterException`** – `Neptune#ml.classification` 和 `Neptune#ml.regression` 述詞都存在於相同的查詢中。

  *訊息*：`Both regression and classification ML predicates cannot be specified in the query.`
+ **`InvalidParameterException`** – 已在連結預測查詢的 `in()` 或 `out()` 步驟中指定多個邊緣標籤。

  *訊息*：`ML inference are currently supported only with one edge label.`
+ **`InvalidParameterException`** – 已使用 Neptune\$1ml.score 指定多個屬性索引鍵。

  *訊息*：`Neptune ML inference queries are currently supported for one property key and one Neptune#ml.score property key.`
+ **`MissingParameterException`** – 未在查詢中指定端點，或未將其指定為資料庫叢集參數。

  *訊息*：`No endpoint provided for external service query.`
+ **``MissingParameterException**   –   未在查詢中指定 SageMaker AI 執行 IAM 角色，或將其指定為資料庫叢集參數。

  *訊息*：`No IAM role ARN provided for external service query.`
+ **`MissingParameterException`** – 查詢中的 `properties()` 步驟遺失內容索引鍵。

  *訊息*：`Property key needs to be specified using properties() step for ML inference queries.`
+ **`MissingParameterException`** – 未在連結預測查詢的 `in()` 或 `out()` 步驟中指定任何邊緣標籤。

  *訊息*：`Edge label needs to be specified while using in() or out() step for ML inference queries.`
+ **`MissingParameterException`** – 未使用 Neptune\$1ml.score 指定屬性索引鍵。

  *訊息*：`Property key needs to be specified along with Neptune#ml.score property key while using the properties() step for Neptune ML inference queries.`
+ **`UnsupportedOperationException`** – `both()` 步驟用於連結預測查詢中。

  *訊息*：`ML inference queries are currently not supported with both() step.`
+ **`UnsupportedOperationException`** – 未在 `has()` 步驟以及連結預測查詢中的 `in()` 或 `out()` 步驟中指定預測的頂點標籤。

  *訊息*：`Predicted vertex label needs to be specified using has() step for ML inference queries.`
+ **`UnsupportedOperationException`** – 未最佳化的步驟目前不支援 Gremlin ML 歸納推論查詢。

  *訊息*：`Neptune ML - Real-Time Inductive Inference queries are currently not supported with Gremlin steps which are not optimized for Neptune. Check the Neptune User Guide for a list of Neptune-optimized steps.`
+ **`UnsupportedOperationException`** – `repeat` 步驟內目前不支援 Neptune ML 推論查詢。

  *訊息*：`Neptune ML inference queries are currently not supported inside a repeat step.`
+ **`UnsupportedOperationException`** – 每個 Grinlin 查詢目前不支援多個 Neptune ML 推論查詢。

  *訊息*：`Neptune ML inference queries are currently supported only with one ML inference query per gremlin query.`

# Neptune ML 中的 SPARQL 推論查詢
<a name="machine-learning-sparql-inference-queries"></a>

Neptune ML 會將 RDF 圖形對應到屬性圖，對 ML 任務進行建模。目前，它支援下列使用案例：
+ **物件分類** – 預測物件的類別特徵。
+ **物件迴歸** – 預測物件的數值屬性。
+ **物件預測** – 預測獲給與主旨和關係的物件。
+ **主旨預測** – 預測獲給與物件和關係的物件。

**注意**  
Neptune ML 不支援主旨分類和迴歸使用案例搭配 SPARQL。

# SPARQL 推論查詢中使用的 Neptune ML 述詞
<a name="machine-learning-sparql-inference-query-predicates"></a>

下列述詞與 SPARQL 推論搭配使用：

## `neptune-ml:timeout` 述詞
<a name="machine-learning-sparql-inference-predicates-timeout"></a>

針對與遠端伺服器的連線指定逾時。不應與查詢請求逾時混淆，這是伺服器滿足請求所需的時間量上限。

請注意，如果在 `neptune-ml:timeout` 述詞指定的服務逾時發生之前發生查詢逾時，也會取消服務連線。

## `neptune-ml:outputClass` 述詞
<a name="machine-learning-sparql-inference-predicates-outputClass"></a>

`neptune-ml:outputClass` 述詞僅用來定義所預測物件的類別進行物件預測，或定義所預測主旨的類別進行主旨預測。

## `neptune-ml:outputScore` 述詞
<a name="machine-learning-sparql-inference-predicates-outputScore"></a>

`neptune-ml:outputScore` 述詞是正數，代表機器學習模型輸出正確的可能性。

## `neptune-ml:modelType` 述詞
<a name="machine-learning-sparql-inference-predicates-modelType"></a>

`neptune-ml:modelType` 述詞指定正在訓練的機器學習模型類型：
+ `OBJECT_CLASSIFICATION`
+ `OBJECT_REGRESSION`
+ `OBJECT_PREDICTION`
+ `SUBJECT_PREDICTION`

## `neptune-ml:input` 述詞
<a name="machine-learning-sparql-inference-predicates-input"></a>

`neptune-ml:input` 述詞是指用作 Neptune ML 輸入的 URI 清單。

## `neptune-ml:output` 述詞
<a name="machine-learning-sparql-inference-predicates-output"></a>

`neptune-ml:output` 述詞是指繫結集的清單，而 Neptune ML 會在這些繫結中傳回結果。

## `neptune-ml:predicate` 述詞
<a name="machine-learning-sparql-inference-predicates-predicate"></a>

`neptune-ml:predicate` 述詞的使用方式會有所不同，取決於正在執行的任務：
+ 對於**物件或主旨預測**：定義述詞的類型 (邊緣或關係類型)。
+ 對於**物件分類和迴歸**：定義要預測的常值 (屬性)。

## `neptune-ml:batchSize` 述詞
<a name="machine-learning-sparql-inference-predicates-batchSize"></a>

`neptune-ml:batchSize` 指定遠端服務呼叫的輸入大小。

# SPARQL 物件分類範例
<a name="machine-learning-sparql-inference-object-classification"></a>

對於 Neptune ML 中的 SPARQL 物件分類，模型會根據其中一個述詞值進行訓練。在該述詞尚未與給定主旨一起存在時，這很有用。

只能使用物件分類模型推斷類別述詞值。

下列查詢試圖為類型 `foaf:Person` 的所有輸入預測 <http://www.example.org/team> 述詞值：

```
SELECT * WHERE { ?input a foaf:Person .
  SERVICE neptune-ml:inference {
    neptune-ml:config neptune-ml:modelType 'OBJECT_CLASSIFICATION' ;
                      neptune-ml:input ?input ;
                      neptune-ml:predicate <http://www.example.org/team> ;
                      neptune-ml:output ?output .
  }
}
```

此查詢可以自訂如下：

```
SELECT * WHERE { ?input a foaf:Person .
  SERVICE neptune-ml:inference {
    neptune-ml:config neptune-ml:endpoint 'node-prediction-account-balance-endpoint' ;
                      neptune-ml:iamRoleArn 'arn:aws:iam::0123456789:role/sagemaker-role' ;

                      neptune-ml:batchSize "40"^^xsd:integer ;
                      neptune-ml:timeout "1000"^^xsd:integer ;

                      neptune-ml:modelType 'OBJECT_CLASSIFICATION' ;
                      neptune-ml:input ?input ;
                      neptune-ml:predicate <http://www.example.org/team> ;
                      neptune-ml:output ?output .
  }
}
```

# SPARQL 物件迴歸範例
<a name="machine-learning-sparql-inference-object-regression"></a>

物件迴歸類似於物件分類，不同之處在於從每個節點的迴歸模型推斷出一個數值述詞值。如同物件分類一般，您可以將相同的 SPARQL 查詢用於物件迴歸，但 `the Neptune#ml.limit` 與 `Neptune#ml.threshold` 述詞不適用。

下列查詢試圖為類型 `foaf:Person` 的所有輸入預測 <http://www.example.org/accountbalance> 述詞值：

```
SELECT * WHERE { ?input a foaf:Person .
  SERVICE neptune-ml:inference {
    neptune-ml:config neptune-ml:modelType 'OBJECT_REGRESSION' ;
                      neptune-ml:input ?input ;
                      neptune-ml:predicate <http://www.example.org/accountbalance> ;
                      neptune-ml:output ?output .
  }
}
```

此查詢可以自訂如下：

```
SELECT * WHERE { ?input a foaf:Person .
  SERVICE neptune-ml:inference {
    neptune-ml:config neptune-ml:endpoint 'node-prediction-account-balance-endpoint' ;
                      neptune-ml:iamRoleArn 'arn:aws:iam::0123456789:role/sagemaker-role' ;

                      neptune-ml:batchSize "40"^^xsd:integer ;
                      neptune-ml:timeout "1000"^^xsd:integer ;

                      neptune-ml:modelType 'OBJECT_REGRESSION' ;
                      neptune-ml:input ?input ;
                      neptune-ml:predicate <http://www.example.org/accountbalance> ;
                      neptune-ml:output ?output .
  }
}
```

# SPARQL 物件預測範例
<a name="machine-learning-sparql-inference-object-prediction"></a>

「物件預測」**會預測給定主旨和述詞的物件值。

下列物件預測查詢試圖預測類型 `foaf:Person` 的輸入會喜歡什麼電影：

```
?x a foaf:Person .
?x   <http://www.example.org/likes> ?m .
?m a <http://www.example.org/movie> .

## Query
SELECT * WHERE { ?input a foaf:Person .
  SERVICE neptune-ml:inference {
    neptune-ml:config neptune-ml:modelType 'OBJECT_PREDICTION' ;
                      neptune-ml:input ?input ;
                      neptune-ml:predicate <http://www.example.org/likes> ;
                      neptune-ml:output ?output ;
                      neptune-ml:outputClass <http://www.example.org/movie> .
  }
}
```

查詢本身可以自訂如下：

```
SELECT * WHERE { ?input a foaf:Person .
  SERVICE neptune-ml:inference {
    neptune-ml:config neptune-ml:endpoint 'node-prediction-user-movie-prediction-endpoint' ;
                      neptune-ml:iamRoleArn 'arn:aws:iam::0123456789:role/sagemaker-role' ;

                      neptune-ml:limit "5"^^xsd:integer ;
                      neptune-ml:batchSize "40"^^xsd:integer ;
                      neptune-ml:threshold "0.1"^^xsd:double ;
                      neptune-ml:timeout "1000"^^xsd:integer ;
                      neptune-ml:outputScore ?score ;

                      neptune-ml:modelType 'OBJECT_PREDICTION' ;
                      neptune-ml:input ?input ;
                      neptune-ml:predicate <http://www.example.org/likes> ;
                      neptune-ml:output ?output ;
                      neptune-ml:outputClass <http://www.example.org/movie> .
  }
}
```

# SPARQL 主旨預測範例
<a name="machine-learning-sparql-inference-subject-prediction"></a>

*主旨預測*會預測指定述詞和物件的主旨。

例如，下列查詢預測誰 (類型 `foaf:User`) 將觀看給定的電影：

```
SELECT * WHERE { ?input (a foaf:Movie) .
    SERVICE neptune-ml:inference {
        neptune-ml:config neptune-ml:modelType 'SUBJECT_PREDICTION' ;
                          neptune-ml:input ?input ;
                          neptune-ml:predicate <http://aws.amazon.com/neptune/csv2rdf/object_Property/rated> ;
                          neptune-ml:output ?output ;
                          neptune-ml:outputClass <http://aws.amazon.com/neptune/csv2rdf/class/User> ;        }
}
```

# Neptune ML SPARQL 推論查詢的例外狀況清單
<a name="machine-learning-sparql-exceptions"></a>

****
+ **`BadRequestException`** – *訊息*：`The SERVICE http://aws.amazon.com/neptune/vocab/v01/services/ml#inference expects at least 1 value for the parameter (parameter name), found zero.`
+ **`BadRequestException`** – *訊息*：`The SERVICE http://aws.amazon.com/neptune/vocab/v01/services/ml#inference expects at most 1 value for the parameter (parameter name), found (a number) values.`
+ **`BadRequestException`** – *訊息*：`Invalid predicate (predicate name) provided for external service http://aws.amazon.com/neptune/vocab/v01/services/ml#inference query.`
+ **`BadRequestException`** – *訊息*：`The SERVICE http://aws.amazon.com/neptune/vocab/v01/services/ml#inference expects the predicate (predicate name) to be defined`。
+ **`BadRequestException`** – *訊息*：`The SERVICE http://aws.amazon.com/neptune/vocab/v01/services/ml#inference expects the value of (parameter) (parameter name) to be a variable, found: (type)"`
+ **`BadRequestException`** – *訊息*：`The SERVICE http://aws.amazon.com/neptune/vocab/v01/services/ml#inference expects the input (parameter name) to be a constant, found: (type)`。
+ **`BadRequestException`** – *訊息*：`The SERVICE http://aws.amazon.com/neptune/vocab/v01/services/ml#inference is expected to return only 1 value`。
+ **`BadRequestException`** – *訊息*：`"The SERVICE http://aws.amazon.com/neptune/vocab/v01/services/ml#inference only allows StatementPatternNodes`。
+ **`BadRequestException`** – *訊息*：`The SERVICE http://aws.amazon.com/neptune/vocab/v01/services/ml#inference does not allow the predicate (predicate name)`。
+ **`BadRequestException`** – *訊息*：`The SERVICE http://aws.amazon.com/neptune/vocab/v01/services/ml#inference predicates cannot be variables, found: (type)`。
+ **`BadRequestException`** – *訊息*：`The SERVICE http://aws.amazon.com/neptune/vocab/v01/services/ml#inference predicates are expected to be part of the namespace (namespace name), found: (namespace name)`。

# Neptune ML 管理 API 參考
<a name="machine-learning-api-reference"></a>

**Contents**
+ [dataprocessing 命令](machine-learning-api-dataprocessing.md)
  + [建立資料處理工作](machine-learning-api-dataprocessing.md#machine-learning-api-dataprocessing-create-job)
  + [取得工作狀態](machine-learning-api-dataprocessing.md#machine-learning-api-dataprocessing-get-job-status)
  + [停止工作](machine-learning-api-dataprocessing.md#machine-learning-api-dataprocessing-stop-job)
  + [列出任務](machine-learning-api-dataprocessing.md#machine-learning-api-dataprocessing-list-jobs)
+ [modeltraining 指令](machine-learning-api-modeltraining.md)
  + [建立模型訓練工作](machine-learning-api-modeltraining.md#machine-learning-api-modeltraining-create-job)
  + [取得工作狀態](machine-learning-api-modeltraining.md#machine-learning-api-modeltraining-get-job-status)
  + [停止工作](machine-learning-api-modeltraining.md#machine-learning-api-modeltraining-stop-job)
  + [列出任務](machine-learning-api-modeltraining.md#machine-learning-api-modeltraining-list-jobs)
+ [modeltransform 命令](machine-learning-api-modeltransform.md)
  + [建立模型轉換工作](machine-learning-api-modeltransform.md#machine-learning-api-modeltransform-create-job)
  + [取得工作狀態](machine-learning-api-modeltransform.md#machine-learning-api-modeltransform-get-job-status)
  + [停止工作](machine-learning-api-modeltransform.md#machine-learning-api-modeltransform-stop-job)
  + [列出任務](machine-learning-api-modeltransform.md#machine-learning-api-modeltransform-list-jobs)
+ [endpoints 命令](machine-learning-api-endpoints.md)
  + [若為推論端點](machine-learning-api-endpoints.md#machine-learning-api-endpoints-create-job)
  + [取得端點狀態](machine-learning-api-endpoints.md#machine-learning-api-endpoints-get-endpoint-status)
  + [刪除端點](machine-learning-api-endpoints.md#machine-learning-api-endpoints-delete-endpoint)
  + [列出推論端點](machine-learning-api-endpoints.md#machine-learning-api-endpoints-list-endpoints)
+ [例外狀況](machine-learning-api-exceptions.md)

# 使用 `dataprocessing` 命令進行資料處理
<a name="machine-learning-api-dataprocessing"></a>

您可以使用 Neptune ML `dataprocessing` 命令來建立資料處理工作、檢查其狀態、停止該工作，或列出所有作用中的資料處理工作。

## 使用 Neptune ML `dataprocessing` 命令建立資料處理工作
<a name="machine-learning-api-dataprocessing-create-job"></a>

用於建立新工作的典型 Neptune ML `dataprocessing` 命令如下所示：

```
curl \
  -X POST https://(your Neptune endpoint)/ml/dataprocessing \
  -H 'Content-Type: application/json' \
  -d '{
        "inputDataS3Location" : "s3://(Amazon S3 bucket name)/(path to your input folder)",
        "id" : "(a job ID for the new job)",
        "processedDataS3Location" : "s3://(S3 bucket name)/(path to your output folder)"
      }'
```

要啟動增量重新處理的命令如下所示：

```
curl \
  -X POST https://(your Neptune endpoint)/ml/dataprocessing \
  -H 'Content-Type: application/json' \
  -d '{
        "inputDataS3Location" : "s3://(Amazon S3 bucket name)/(path to your input folder)",
        "id" : "(a job ID for this job)",
        "processedDataS3Location" : "s3://(S3 bucket name)/(path to your output folder)"
        "previousDataProcessingJobId" : "(the job ID of a previously completed job to update)"
}'
```

**用於建立 `dataprocessing` 工作的參數**
+ **`id`** – (*選用*) 新工作的唯一識別符。

  *類型*：字串 *預設值*：自動產生的 UUID。
+ **`previousDataProcessingJobId`** – (*選用*) 在舊版資料上執行且已完成之資料處理工作的工作 ID。

  *類型*：字串 *預設值*：*none*。

  *注意*：使用此項進行增量資料處理，以在圖形資料變更時更新模型 (但在資料已遭刪除時不適用)。
+ **`inputDataS3Location`**   – (*必要*) 您希望 SageMaker AI 下載執行資料處理任務所需資料之 Amazon S3 位置的 URI。

  *類型*：字串
+ **`processedDataS3Location`**   – (*必要*) 您希望 SageMaker AI 儲存資料處理任務結果的 Amazon S3 位置的 URI。

  *類型*：字串
+ **`sagemakerIamRoleArn`**   – (*選用*) SageMaker AI 執行的 IAM 角色 ARN。

  *類型*：字串 *注意*：這必須列示在您的資料庫叢集參數群組中，否則會發生錯誤。
+ **`neptuneIamRoleArn`**   – (*選用*) SageMaker AI 可擔任以代表您執行任務之 IAM 角色的 Amazon Resource Name (ARN)。

  *類型*：字串 *注意*：這必須列示在您的資料庫叢集參數群組中，否則會發生錯誤。
+ **`processingInstanceType`** – (*選用*) 資料處理期間所使用的 ML 執行個體類型。它的記憶體應該大到足以保留處理後的資料集。

  *類型*：字串 *預設值*：最小的 `ml.r5` 類型，其記憶體十倍於磁碟上所匯出圖形資料的大小。

  *注意*：Neptune ML 可以自動選取執行個體類型。請參閱 [選取執行個體進行資料處理](machine-learning-on-graphs-instance-selection.md#machine-learning-on-graphs-processing-instance-size)。
+ **`processingInstanceVolumeSizeInGB`** – (*選用*) 處理執行個體的磁碟區大小。輸入資料和處理後的資料都會儲存在磁碟上，因此磁碟區大小必須大到足以保留這兩個資料集。

  *類型*：整數。*預設*︰`0`。

  *注意*：如果未指定或指定 0，Neptune ML 會根據資料大小自動選擇磁碟區大小。
+ **`processingTimeOutInSeconds`** – (*選用*) 資料處理工作的逾時 (以秒為單位)。

  *類型*：整數。*預設值*：`86,400` (1 天)。
+ **`modelType`** – (*選用*) Neptune ML 目前支援的兩種模型類型之一：異質圖形模型 (`heterogeneous`) 和知識圖譜 (`kge`)。

  *類型*：字串 *預設值*：*none*。

  *注意*：如果未指定，Neptune ML 會根據資料自動選擇模型類型。
+ **`configFileName`** – (*選用*) 描述如何載入所匯出圖形資料進行訓練的資料規格檔案。Neptune 匯出工具組會自動產生此檔案。

  *類型*：字串 *預設*︰`training-data-configuration.json`。
+ **`subnets`** – (*選用*) Neptune VPC 中子網路的 ID。

  *類型*：字串清單。*預設值*：*none*。
+ **`securityGroupIds`** – (*選用*) VPC 安全群組 ID。

  *類型*：字串清單。*預設值*：*none*。
+ **`volumeEncryptionKMSKey`**   – (*選用*) SageMaker AI 用來加密連接至執行處理任務之 ML 運算執行個體之儲存磁碟區上的資料之 AWS Key Management Service (AWS KMS) 金鑰。

  *類型*：字串 *預設值*：*none*。
+ **`enableInterContainerTrafficEncryption`** – (*選用*) 在訓練或超參數調校工作中啟用或停用容器間流量加密。

  *類型*：布林值。*預設值*：*true*。
**注意**  
`enableInterContainerTrafficEncryption` 參數僅適用於[引擎版本 1.2.0.2.R3](engine-releases-1.2.0.2.R3.md)。
+ **`s3OutputEncryptionKMSKey`**   – (*選用*) SageMaker AI 用來加密訓練任務輸出的 AWS Key Management Service (AWS KMS) 金鑰。

  *類型*：字串 *預設值*：*none*。

## 使用 Neptune ML `dataprocessing` 命令取得資料處理工作的狀態
<a name="machine-learning-api-dataprocessing-get-job-status"></a>

工作狀態的範例 Neptune ML `dataprocessing` 命令如下所示：

```
curl -s \
  "https://(your Neptune endpoint)/ml/dataprocessing/(the job ID)" \
  | python -m json.tool
```

**`dataprocessing` 工作狀態的參數**
+ **`id`** – (*必要*) 資料處理工作的唯一識別符。

  *類型*：字串
+ **`neptuneIamRoleArn`**   – (*選用*) IAM 角色的 ARN，提供對 SageMaker AI 和 Amazon S3 資源的 Neptune 存取權。

  *類型*：字串 *注意*：這必須列示在您的資料庫叢集參數群組中，否則會發生錯誤。

## 使用 Neptune ML `dataprocessing` 命令停止資料處理工作
<a name="machine-learning-api-dataprocessing-stop-job"></a>

用於停止工作的範例 Neptune ML `dataprocessing` 命令如下所示：

```
curl -s \
  -X DELETE "https://(your Neptune endpoint)/ml/dataprocessing/(the job ID)"
```

或如下所示：

```
curl -s \
  -X DELETE "https://(your Neptune endpoint)/ml/dataprocessing/(the job ID)?clean=true"
```

**`dataprocessing` 停止工作的參數**
+ **`id`** – (*必要*) 資料處理工作的唯一識別符。

  *類型*：字串
+ **`neptuneIamRoleArn`**   – (*選用*) IAM 角色的 ARN，提供對 SageMaker AI 和 Amazon S3 資源的 Neptune 存取權。

  *類型*：字串 *注意*：這必須列示在您的資料庫叢集參數群組中，否則會發生錯誤。
+ **`clean`** – (*選用*) 此旗標指定在工作停止時應刪除所有 Amazon S3 成品。

  *類型*：布林值。*預設*︰`FALSE`。

## 使用 Neptune ML `dataprocessing` 命令列出作用中的資料處理工作
<a name="machine-learning-api-dataprocessing-list-jobs"></a>

用於列出作用中工作的範例 Neptune ML `dataprocessing` 命令如下所示：

```
curl -s "https://(your Neptune endpoint)/ml/dataprocessing"
```

或如下所示：

```
curl -s "https://(your Neptune endpoint)/ml/dataprocessing?maxItems=3"
```

**`dataprocessing` 列出工作的參數**
+ **`maxItems`** – (*選用*) 要傳回的項目數上限。

  *類型*：整數。*預設*︰`10`。*允許的最大值*：`1024`。
+ **`neptuneIamRoleArn`**   – (*選用*) IAM 角色的 ARN，提供對 SageMaker AI 和 Amazon S3 資源的 Neptune 存取權。

  *類型*：字串 *注意*：這必須列示在您的資料庫叢集參數群組中，否則會發生錯誤。

# 使用 `modeltraining` 命令進行模型訓練
<a name="machine-learning-api-modeltraining"></a>

您可以使用 Neptune ML `modeltraining` 命令來建立模型訓練工作、檢查其狀態、停止該工作，或列出所有作用中的模型訓練工作。

## 使用 Neptune ML `modeltraining` 命令建立模型訓練工作
<a name="machine-learning-api-modeltraining-create-job"></a>

用於建立全新工作的 Neptune ML `modeltraining` 命令如下所示：

```
curl \
  -X POST https://(your Neptune endpoint)/ml/modeltraining
  -H 'Content-Type: application/json' \
  -d '{
        "id" : "(a unique model-training job ID)",
        "dataProcessingJobId" : "(the data-processing job-id of a completed job)",
        "trainModelS3Location" : "s3://(your Amazon S3 bucket)/neptune-model-graph-autotrainer"
      }'
```

用於為增量模型訓練建立更新工作的 Neptune ML `modeltraining` 命令如下所示：

```
curl \
  -X POST https://(your Neptune endpoint)/ml/modeltraining
  -H 'Content-Type: application/json' \
  -d '{
        "id" : "(a unique model-training job ID)",
        "dataProcessingJobId" : "(the data-processing job-id of a completed job)",
        "trainModelS3Location" : "s3://(your Amazon S3 bucket)/neptune-model-graph-autotrainer"
        "previousModelTrainingJobId" : "(the job ID of a completed model-training job to update)",
      }'
```

透過使用者提供的自訂模型實作建立新工作的 Neptune ML `modeltraining` 命令如下所示：

```
curl \
  -X POST https://(your Neptune endpoint)/ml/modeltraining
  -H 'Content-Type: application/json' \
  -d '{
        "id" : "(a unique model-training job ID)",
        "dataProcessingJobId" : "(the data-processing job-id of a completed job)",
        "trainModelS3Location" : "s3://(your Amazon S3 bucket)/neptune-model-graph-autotrainer"
        "modelName": "custom",
        "customModelTrainingParameters" : {
          "sourceS3DirectoryPath": "s3://(your Amazon S3 bucket)/(path to your Python module)",
          "trainingEntryPointScript": "(your training script entry-point name in the Python module)",
          "transformEntryPointScript": "(your transform script entry-point name in the Python module)"
        }
      }'
```

**用於建立 `modeltraining` 工作的參數**
+ **`id`** – (*選用*) 新工作的唯一識別符。

  *類型*：字串 *預設值*：自動產生的 UUID。
+ **`dataProcessingJobId`** – (*必要*) 已完成資料處理工作的工作 ID，該工作已建立訓練將使用的資料。

  *類型*：字串
+ **`trainModelS3Location`** – (*必要*) Amazon S3 中要儲存模型成品的位置。

  *類型*：字串
+ **`previousModelTrainingJobId`** – (*選用*) 已完成模型訓練工作的工作 ID，您想要根據更新的資料以增量方式更新此工作。

  *類型*：字串 *預設值*：*none*。
+ **`sagemakerIamRoleArn`**   – (*選用*) SageMaker AI 執行的 IAM 角色 ARN。

  *類型*：字串 *注意*：這必須列示在您的資料庫叢集參數群組中，否則會發生錯誤。
+ **`neptuneIamRoleArn`**   – (*選用*) IAM 角色的 ARN，提供對 SageMaker AI 和 Amazon S3 資源的 Neptune 存取權。

  *類型*：字串 *注意*：這必須列示在您的資料庫叢集參數群組中，否則會發生錯誤。
+ **`modelName`** – (*選用*) 用於訓練的模型類型。根據預設，ML 模型會是自動以資料處理中使用的 `modelType` 為基礎，但您可以在這裡指定不同的模型類型。

  *類型*：字串 *預設值*：`rgcn` 用於異質圖和 `kge` 用於知識圖譜。*有效值*：若為異質圖：`rgcn`。若為 `kge` 圖形：`transe`、`distmult` 或 `rotate`。若為自訂模型實作：`custom`。
+ **`baseProcessingInstanceType`** – (*選用*) 用於準備和管理 ML 模型訓練的 ML 執行個體類型。

  *類型*：字串 *注意*：這是根據記憶體需求選擇的 CPU 執行個體，用於處理訓練資料和模型。請參閱 [選取執行個體進行模型訓練和模型轉換](machine-learning-on-graphs-instance-selection.md#machine-learning-on-graphs-training-transform-instance-size)。
+ **`trainingInstanceType`** – (*選用*) 用於模型訓練的 ML 執行個體類型。所有 Neptune ML 模型都支援 CPU、GPU 和多 GPU 訓練。

  *類型*：字串 *預設*︰`ml.p3.2xlarge`。

  *注意*：選擇適合訓練的執行個體類型取決於工作類型、圖形大小和您的預算。請參閱 [選取執行個體進行模型訓練和模型轉換](machine-learning-on-graphs-instance-selection.md#machine-learning-on-graphs-training-transform-instance-size)。
+ **`trainingInstanceVolumeSizeInGB`** – (*選用*) 訓練執行個體的磁碟區大小。輸入資料和輸出模型都會儲存在磁碟上，因此磁碟區大小必須大到足以保留這兩個資料集。

  *類型*：整數。*預設*︰`0`。

  *備註*：如果未指定或指定 0，Neptune ML 會根據資料處理步驟中產生的建議選取磁碟區大小。請參閱 [選取執行個體進行模型訓練和模型轉換](machine-learning-on-graphs-instance-selection.md#machine-learning-on-graphs-training-transform-instance-size)。
+ **`trainingTimeOutInSeconds`** – (*選用*) 訓練工作的逾時 (以秒為單位)。

  *類型*：整數。*預設值*：`86,400` (1 天)。
+ **`maxHPONumberOfTrainingJobs`** – 要對超參數調校工作啟動的訓練工作總數上限。

  *類型*：整數。*預設*︰`2`。

  *注意*：Neptune ML 會自動調校機器學習模型的超參數。若要取得效能良好的模型，請至少使用 10 個工作 (換句話說，將 `maxHPONumberOfTrainingJobs` 設為 10)。一般來說，調校執行越多，結果越好。
+ **`maxHPOParallelTrainingJobs`** – 要對超參數調校工作啟動的並行訓練工作數目上限。

  *類型*：整數。*預設*︰`2`。

  *注意*：您可以執行的並行工作數目受制於訓練執行個體上可用的資源。
+ **`subnets`** – (*選用*) Neptune VPC 中子網路的 ID。

  *類型*：字串清單。*預設值*：*none*。
+ **`securityGroupIds`** – (*選用*) VPC 安全群組 ID。

  *類型*：字串清單。*預設值*：*none*。
+ **`volumeEncryptionKMSKey`**   – (*選用*) SageMaker AI 用來加密連接至執行訓練任務之 ML 運算執行個體之儲存磁碟區上的資料之 AWS Key Management Service (AWS KMS) 金鑰。

  *類型*：字串 *預設值*：*none*。
+ **`s3OutputEncryptionKMSKey`**   – (*選用*) SageMaker AI 用來加密處理任務輸出的 AWS Key Management Service (AWS KMS) 金鑰。

  *類型*：字串 *預設值*：*none*。
+ **`enableInterContainerTrafficEncryption`** – (*選用*) 在訓練或超參數調校工作中啟用或停用容器間流量加密。

  *類型*：布林值。*預設值*：*true*。
**注意**  
`enableInterContainerTrafficEncryption` 參數僅適用於[引擎版本 1.2.0.2.R3](engine-releases-1.2.0.2.R3.md)。
+ **`enableManagedSpotTraining`** – (*選用*) 使用 Amazon Elastic Compute Cloud Spot 執行個體，將訓練機器學習模型的成本最佳化。如需詳細資訊，請參閱 [Amazon SageMaker 中的受管 SageMaker 訓練](https://docs.aws.amazon.com/sagemaker/latest/dg/model-managed-spot-training.html)。

  *類型*：布林值。*預設值*：*false*。
+ **`customModelTrainingParameters`** – (*選用*) 自訂模型訓練的組態。這是具有下列欄位的 JSON 物件：
  + **`sourceS3DirectoryPath`** – (*必要*) 此路徑通往實作您模型之 Python 模組所在的 Amazon S3 位置。這必須指向有效的現有 Amazon S3 位置，其中至少包含訓練指令碼、轉換指令碼和 `model-hpo-configuration.json` 檔案。
  + **`trainingEntryPointScript`** – (*選用*) 指令碼模組中的進入點名稱，該指令碼會執行模型訓練，並接受超參數作為命令列引數 (包括固定的超參數)。

    *預設*︰`training.py`。
  + **`transformEntryPointScript`** – (*選用*) 指令碼模組中的進入點名稱，該指令碼應在識別了超參數搜尋中的最佳模型之後執行，以計算模型部署所需的模型成品。它應該能夠在沒有命令列參數的情況下執行。

    *預設*︰`transform.py`。
+ **`maxWaitTime`** – (*選用*) 使用 Spot 執行個體來執行模型訓練時，要等待的時間上限 (以秒為單位)。應大於 `trainingTimeOutInSeconds`。

  *類型*：整數。

## 使用 Neptune ML `modeltraining` 命令取得模型訓練工作的狀態
<a name="machine-learning-api-modeltraining-get-job-status"></a>

工作狀態的範例 Neptune ML `modeltraining` 命令如下所示：

```
curl -s \
  "https://(your Neptune endpoint)/ml/modeltraining/(the job ID)" \
  | python -m json.tool
```

**`modeltraining` 工作狀態的參數**
+ **`id`** – (*必要*) 模型訓練工作的唯一識別符。

  *類型*：字串
+ **`neptuneIamRoleArn`**   – (*選用*) IAM 角色的 ARN，提供對 SageMaker AI 和 Amazon S3 資源的 Neptune 存取權。

  *類型*：字串 *注意*：這必須列示在您的資料庫叢集參數群組中，否則會發生錯誤。

## 使用 Neptune ML `modeltraining` 命令停止模型訓練工作
<a name="machine-learning-api-modeltraining-stop-job"></a>

用於停止工作的範例 Neptune ML `modeltraining` 命令如下所示：

```
curl -s \
  -X DELETE "https://(your Neptune endpoint)/ml/modeltraining/(the job ID)"
```

或如下所示：

```
curl -s \
  -X DELETE "https://(your Neptune endpoint)/ml/modeltraining/(the job ID)?clean=true"
```

**`modeltraining` 停止工作的參數**
+ **`id`** – (*必要*) 模型訓練工作的唯一識別符。

  *類型*：字串
+ **`neptuneIamRoleArn`**   – (*選用*) IAM 角色的 ARN，提供對 SageMaker AI 和 Amazon S3 資源的 Neptune 存取權。

  *類型*：字串 *注意*：這必須列示在您的資料庫叢集參數群組中，否則會發生錯誤。
+ **`clean`** – (*選用*) 此旗標指定在工作停止時應刪除所有 Amazon S3 成品。

  *類型*：布林值。*預設*︰`FALSE`。

## 使用 Neptune ML `modeltraining` 命令列出作用中的模型訓練工作
<a name="machine-learning-api-modeltraining-list-jobs"></a>

用於列出作用中工作的範例 Neptune ML `modeltraining` 命令如下所示：

```
curl -s "https://(your Neptune endpoint)/ml/modeltraining" | python -m json.tool
```

或如下所示：

```
curl -s "https://(your Neptune endpoint)/ml/modeltraining?maxItems=3" | python -m json.tool
```

**`modeltraining` 列出工作的參數**
+ **`maxItems`** – (*選用*) 要傳回的項目數上限。

  *類型*：整數。*預設*︰`10`。*允許的最大值*：`1024`。
+ **`neptuneIamRoleArn`**   – (*選用*) IAM 角色的 ARN，提供對 SageMaker AI 和 Amazon S3 資源的 Neptune 存取權。

  *類型*：字串 *注意*：這必須列示在您的資料庫叢集參數群組中，否則會發生錯誤。

# 使用 `modeltransform` 命令進行模型轉換
<a name="machine-learning-api-modeltransform"></a>

您可以使用 Neptune ML `modeltransform` 命令來建立模型轉換工作、檢查其狀態、停止該工作，或列出所有作用中的模型轉換工作。

## 使用 Neptune ML `modeltransform` 命令建立模型轉換工作
<a name="machine-learning-api-modeltransform-create-job"></a>

用於建立增量轉換工作而不需模型重新訓練的 Neptune ML `modeltransform` 命令如下所示：

```
curl \
  -X POST https://(your Neptune endpoint)/ml/modeltransform
  -H 'Content-Type: application/json' \
  -d '{
        "id" : "(a unique model-transform job ID)",
        "dataProcessingJobId" : "(the job-id of a completed data-processing job)",
        "mlModelTrainingJobId" : "(the job-id of a completed model-training job)",
        "modelTransformOutputS3Location" : "s3://(your Amazon S3 bucket)/neptune-model-transform"
      }'
```

從已完成的 SageMaker AI 訓練任務建立任務的 Neptune ML `modeltransform`命令如下所示：

```
curl \
  -X POST https://(your Neptune endpoint)/ml/modeltransform
  -H 'Content-Type: application/json' \
  -d '{
        "id" : "(a unique model-transform job ID)",
        "trainingJobName" : "(name of a completed SageMaker AI training job)",
        "modelTransformOutputS3Location" : "s3://(your Amazon S3 bucket)/neptune-model-transform",
        "baseProcessingInstanceType" : ""
      }'
```

用於建立一個工作，使用自訂模型實作的 Neptune ML `modeltransform` 命令如下所示：

```
curl \
  -X POST https://(your Neptune endpoint)/ml/modeltransform
  -H 'Content-Type: application/json' \
  -d '{
        "id" : "(a unique model-training job ID)",
        "trainingJobName" : "(name of a completed SageMaker AI training job)",
        "modelTransformOutputS3Location" : "s3://(your Amazon S3 bucket)/neptune-model-transform/"
        "customModelTransformParameters" : {
          "sourceS3DirectoryPath": "s3://(your Amazon S3 bucket)/(path to your Python module)",
          "transformEntryPointScript": "(your transform script entry-point name in the Python module)"
        }
      }'
```

**用於建立 `modeltransform` 工作的參數**
+ **`id`** – (*選用*) 新工作的唯一識別符。

  *類型*：字串 *預設值*：自動產生的 UUID。
+ **`dataProcessingJobId`** – 已完成資料處理工作的工作 ID。

  *類型*：字串

  *附註*：您必須同時包含 `dataProcessingJobId` 和 `mlModelTrainingJobId` 或 `trainingJobName`。
+ **`mlModelTrainingJobId`** – 已完成模型訓練工作的工作 ID。

  *類型*：字串

  *附註*：您必須同時包含 `dataProcessingJobId` 和 `mlModelTrainingJobId` 或 `trainingJobName`。
+ **`trainingJobName`**   –   完成的 SageMaker AI 訓練任務的名稱。

  *類型*：字串

  *注意*：您必須同時包含 `dataProcessingJobId` 和 `mlModelTrainingJobId` 參數或包含 `trainingJobName` 參數。
+ **`sagemakerIamRoleArn`**   – (*選用*) SageMaker AI 執行的 IAM 角色 ARN。

  *類型*：字串 *注意*：這必須列示在您的資料庫叢集參數群組中，否則會發生錯誤。
+ **`neptuneIamRoleArn`**   – (*選用*) IAM 角色的 ARN，提供對 SageMaker AI 和 Amazon S3 資源的 Neptune 存取權。

  *類型*：字串 *注意*：這必須列示在您的資料庫叢集參數群組中，否則會發生錯誤。
+ **`customModelTransformParameters `** – (*選用*) 使用自訂模型進行模型轉換的組態資訊。`customModelTransformParameters` 物件包含下列欄位，其具有的值必須與訓練工作中儲存的模型參數相容：
  + **`sourceS3DirectoryPath`** – (*必要*) 此路徑通往實作您模型之 Python 模組所在的 Amazon S3 位置。這必須指向有效的現有 Amazon S3 位置，其中至少包含訓練指令碼、轉換指令碼和 `model-hpo-configuration.json` 檔案。
  + **`transformEntryPointScript`** – (*選用*) 指令碼模組中的進入點名稱，該指令碼應在識別了超參數搜尋中的最佳模型之後執行，以計算模型部署所需的模型成品。它應該能夠在沒有命令列參數的情況下執行。

    *預設*︰`transform.py`。
+ **`baseProcessingInstanceType`** – (*選用*) 用於準備和管理 ML 模型訓練的 ML 執行個體類型。

  *類型*：字串 *注意*：這是根據記憶體需求選擇的 CPU 執行個體，用於處理轉換資料和模型。請參閱 [選取執行個體進行模型訓練和模型轉換](machine-learning-on-graphs-instance-selection.md#machine-learning-on-graphs-training-transform-instance-size)。
+ **`baseProcessingInstanceVolumeSizeInGB`** – (*選用*) 訓練執行個體的磁碟區大小。輸入資料和輸出模型都會儲存在磁碟上，因此磁碟區大小必須大到足以保留這兩個資料集。

  *類型*：整數。*預設*︰`0`。

  *備註*：如果未指定或指定 0，Neptune ML 會根據資料處理步驟中產生的建議選取磁碟區大小。請參閱 [選取執行個體進行模型訓練和模型轉換](machine-learning-on-graphs-instance-selection.md#machine-learning-on-graphs-training-transform-instance-size)。
+ **`subnets`** – (*選用*) Neptune VPC 中子網路的 ID。

  *類型*：字串清單。*預設值*：*none*。
+ **`securityGroupIds`** – (*選用*) VPC 安全群組 ID。

  *類型*：字串清單。*預設值*：*none*。
+ **`volumeEncryptionKMSKey`**   – (*選用*) SageMaker AI 用來加密連接至執行轉換任務之 ML 運算執行個體之儲存磁碟區上的資料之 AWS Key Management Service (AWS KMS) 金鑰。

  *類型*：字串 *預設值*：*none*。
+ **`enableInterContainerTrafficEncryption`** – (*選用*) 在訓練或超參數調校工作中啟用或停用容器間流量加密。

  *類型*：布林值。*預設值*：*true*。
**注意**  
`enableInterContainerTrafficEncryption` 參數僅適用於[引擎版本 1.2.0.2.R3](engine-releases-1.2.0.2.R3.md)。
+ **`s3OutputEncryptionKMSKey`**   – (*選用*) SageMaker AI 用來加密處理任務輸出的 AWS Key Management Service (AWS KMS) 金鑰。

  *類型*：字串 *預設值*：*none*。

## 使用 Neptune ML `modeltransform` 命令取得模型轉換工作的狀態
<a name="machine-learning-api-modeltransform-get-job-status"></a>

工作狀態的範例 Neptune ML `modeltransform` 命令如下所示：

```
curl -s \
  "https://(your Neptune endpoint)/ml/modeltransform/(the job ID)" \
  | python -m json.tool
```

**`modeltransform` 工作狀態的參數**
+ **`id`** – (*必要*) 模型轉換工作的唯一識別符。

  *類型*：字串
+ **`neptuneIamRoleArn`**   – (*選用*) IAM 角色的 ARN，提供對 SageMaker AI 和 Amazon S3 資源的 Neptune 存取權。

  *類型*：字串 *注意*：這必須列示在您的資料庫叢集參數群組中，否則會發生錯誤。

## 使用 Neptune ML `modeltransform` 命令停止模型轉換工作
<a name="machine-learning-api-modeltransform-stop-job"></a>

用於停止工作的範例 Neptune ML `modeltransform` 命令如下所示：

```
curl -s \
  -X DELETE "https://(your Neptune endpoint)/ml/modeltransform/(the job ID)"
```

或如下所示：

```
curl -s \
  -X DELETE "https://(your Neptune endpoint)/ml/modeltransform/(the job ID)?clean=true"
```

**`modeltransform` 停止工作的參數**
+ **`id`** – (*必要*) 模型轉換工作的唯一識別符。

  *類型*：字串
+ **`neptuneIamRoleArn`**   – (*選用*) IAM 角色的 ARN，提供對 SageMaker AI 和 Amazon S3 資源的 Neptune 存取權。

  *類型*：字串 *注意*：這必須列示在您的資料庫叢集參數群組中，否則會發生錯誤。
+ **`clean`** – (*選用*) 此旗標指定在工作停止時應刪除所有 Amazon S3 成品。

  *類型*：布林值。*預設*︰`FALSE`。

## 使用 Neptune ML `modeltransform` 命令列出作用中的模型轉換工作
<a name="machine-learning-api-modeltransform-list-jobs"></a>

用於列出作用中工作的範例 Neptune ML `modeltransform` 命令如下所示：

```
curl -s "https://(your Neptune endpoint)/ml/modeltransform" | python -m json.tool
```

或如下所示：

```
curl -s "https://(your Neptune endpoint)/ml/modeltransform?maxItems=3" | python -m json.tool
```

**`modeltransform` 列出工作的參數**
+ **`maxItems`** – (*選用*) 要傳回的項目數上限。

  *類型*：整數。*預設*︰`10`。*允許的最大值*：`1024`。
+ **`neptuneIamRoleArn`**   – (*選用*) IAM 角色的 ARN，提供對 SageMaker AI 和 Amazon S3 資源的 Neptune 存取權。

  *類型*：字串 *注意*：這必須列示在您的資料庫叢集參數群組中，否則會發生錯誤。

# 使用 `endpoints` 命令管理推論端點
<a name="machine-learning-api-endpoints"></a>

您可以使用 Neptune ML `endpoints` 命令來建立推論端點、檢查其狀態、將其刪除，或列出現有的推論端點。

## 使用 Neptune ML `endpoints` 命令建立推論端點
<a name="machine-learning-api-endpoints-create-job"></a>

如下 Neptune ML `endpoints` 命令可從訓練工作所建立的模型建立推論端點：

```
curl \
  -X POST https://(your Neptune endpoint)/ml/endpoints
  -H 'Content-Type: application/json' \
  -d '{
        "id" : "(a unique ID for the new endpoint)",
        "mlModelTrainingJobId": "(the model-training job-id of a completed job)"
      }'
```

如下 Neptune ML `endpoints` 命令可從訓練工作所建立的模型更新現有的推論端點：

```
curl \
  -X POST https://(your Neptune endpoint)/ml/endpoints
  -H 'Content-Type: application/json' \
  -d '{
        "id" : "(a unique ID for the new endpoint)",
        "update" : "true",
        "mlModelTrainingJobId": "(the model-training job-id of a completed job)"
      }'
```

如下 Neptune ML `endpoints` 命令可從模型轉換工作所建立的模型建立推論端點：

```
curl \
  -X POST https://(your Neptune endpoint)/ml/endpoints
  -H 'Content-Type: application/json' \
  -d '{
        "id" : "(a unique ID for the new endpoint)",
        "mlModelTransformJobId": "(the model-training job-id of a completed job)"
      }'
```

如下 Neptune ML `endpoints` 命令可從模型轉換工作所建立的模型更新現有的推論端點：

```
curl \
  -X POST https://(your Neptune endpoint)/ml/endpoints
  -H 'Content-Type: application/json' \
  -d '{
        "id" : "(a unique ID for the new endpoint)",
        "update" : "true",
        "mlModelTransformJobId": "(the model-training job-id of a completed job)"
      }'
```

**用於建立 `endpoints` 推論端點的參數**
+ **`id`** – (*選用*) 新推論端點的唯一識別符。

  *類型*：字串 *預設值*：自動產生的時間戳記名稱。
+ **`mlModelTrainingJobId`** – 已完成模型訓練工作的工作 ID，該工作已建立推論端點將指向的模型。

  *類型*：字串

  *注意*：您必須提供 `mlModelTrainingJobId` 或 `mlModelTransformJobId`。
+ **`mlModelTransformJobId`** – 已完成模型轉換工作的工作 ID。

  *類型*：字串

  *注意*：您必須提供 `mlModelTrainingJobId` 或 `mlModelTransformJobId`。
+ **`update`** – (*選用*) 如果存在，此參數指示這是更新請求。

  *類型*：布林值。*預設*：`false`

  *注意*：您必須提供 `mlModelTrainingJobId` 或 `mlModelTransformJobId`。
+ **`neptuneIamRoleArn`**   – (*選用*) IAM 角色的 ARN，提供對 SageMaker AI 和 Amazon S3 資源的 Neptune 存取權。

  *類型*：字串 *注意*：這必須列示在您的資料庫叢集參數群組中，否則會擲回錯誤。
+ **`modelName`** – (*選用*) 用於訓練的模型類型。根據預設，ML 模型會是自動以資料處理中使用的 `modelType` 為基礎，但您可以在這裡指定不同的模型類型。

  *類型*：字串 *預設值*：`rgcn` 用於異質圖和 `kge` 用於知識圖譜。*有效值*：若為異質圖：`rgcn`。若為知識圖譜：`kge`、`transe`、`distmult` 或 `rotate`。
+ **`instanceType`** – (*選用*) 用於線上服務的 ML 執行個體類型。

  *類型*：字串 *預設*︰`ml.m5.xlarge`。

  *注意*：為推論端點選擇 ML 執行個體，取決於任務類型、圖形大小以及您的預算。請參閱 [為推論端點選取執行個體](machine-learning-on-graphs-instance-selection.md#machine-learning-on-graphs-inference-endpoint-instance-size)。
+ **`instanceCount`** – (*選用*) 要部署到端點進行預測的 Amazon EC2 執行個體數量下限。

  *類型*：整數。*預設*︰`1`。
+ **`volumeEncryptionKMSKey`**   – (*選用*) SageMaker AI 用來加密連接至執行端點之 ML 運算執行個體之儲存磁碟區上的資料 AWS Key Management Service ()AWS KMS金鑰。

  *類型*：字串 *預設值*：*none*。

## 使用 Neptune ML `endpoints` 命令取得推論端點的狀態
<a name="machine-learning-api-endpoints-get-endpoint-status"></a>

執行個體端點狀態的範例 Neptune ML `endpoints` 命令如下所示：

```
curl -s \
  "https://(your Neptune endpoint)/ml/endpoints/(the inference endpoint ID)" \
  | python -m json.tool
```

**`endpoints` 執行個體-端點狀態的參數**
+ **`id`** – (*必要*) 推論端點的唯一識別符。

  *類型*：字串
+ **`neptuneIamRoleArn`**   – (*選用*) IAM 角色的 ARN，提供對 SageMaker AI 和 Amazon S3 資源的 Neptune 存取權。

  *類型*：字串 *注意*：這必須列示在您的資料庫叢集參數群組中，否則會擲回錯誤。

## 使用 Neptune ML `endpoints` 命令刪除執行個體端點
<a name="machine-learning-api-endpoints-delete-endpoint"></a>

用於刪除執行個體端點的範例 Neptune ML `endpoints` 命令如下所示：

```
curl -s \
  -X DELETE "https://(your Neptune endpoint)/ml/endpoints/(the inference endpoint ID)"
```

或如下所示：

```
curl -s \
  -X DELETE "https://(your Neptune endpoint)/ml/endpoints/(the inference endpoint ID)?clean=true"
```

**`endpoints` 刪除推論端點的參數**
+ **`id`** – (*必要*) 推論端點的唯一識別符。

  *類型*：字串
+ **`neptuneIamRoleArn`**   – (*選用*) IAM 角色的 ARN，提供對 SageMaker AI 和 Amazon S3 資源的 Neptune 存取權。

  *類型*：字串 *注意*：這必須列示在您的資料庫叢集參數群組中，否則會擲回錯誤。
+ **`clean`** – (*選用*) 指示也應刪除與此端點相關的所有成品。

  *類型*：布林值。*預設*︰`FALSE`。

## 使用 Neptune ML `endpoints` 命令列出推論端點
<a name="machine-learning-api-endpoints-list-endpoints"></a>

用於列出推論端點的 Neptune ML `endpoints` 命令如下所示：

```
curl -s "https://(your Neptune endpoint)/ml/endpoints" \
  | python -m json.tool
```

或如下所示：

```
curl -s "https://(your Neptune endpoint)/ml/endpoints?maxItems=3" \
  | python -m json.tool
```

**`dataprocessing` 列出推論端點的參數**
+ **`maxItems`** – (*選用*) 要傳回的項目數上限。

  *類型*：整數。*預設*︰`10`。*允許的最大值*：`1024`。
+ **`neptuneIamRoleArn`**   – (*選用*) IAM 角色的 ARN，提供對 SageMaker AI 和 Amazon S3 資源的 Neptune 存取權。

  *類型*：字串 *注意*：這必須列示在您的資料庫叢集參數群組中，否則會擲回錯誤。

# Neptune ML 管理 API 錯誤和例外狀況
<a name="machine-learning-api-exceptions"></a>

所有 Neptune ML 管理 API 例外狀況都會傳回 400 HTTP 代碼。在收到任何這些例外狀況之後，不應重試產生例外狀況的命令。

****
+ **`MissingParameterException`** – 錯誤訊息：

  `Required credentials are missing. Please add IAM role to the cluster or pass as a parameter to this request.`
+ **`InvalidParameterException`** – 錯誤訊息：
  + `Invalid ML instance type.`
  + `Invalid ID provided. ID can be 1-48 alphanumeric characters.`
  + `Invalid ID provided. Must contain only letters, digits, or hyphens.`
  + `Invalid ID provided. Please check whether a resource with the given ID exists.`
  + `Another resource with same ID already exists. Please use a new ID.`
  + `Failed to stop the job because it has already completed or failed.`
+ **`BadRequestException`** – 錯誤訊息：
  + `Invalid S3 URL or incorrect S3 permissions. Please check your S3 configuration.`
  + `Provided ModelTraining job has not completed.`
  + `Provided SageMaker AI Training job has not completed.`
  + `Provided MLDataProcessing job is not completed.`
  + `Provided MLModelTraining job doesn't exist.`
  + `Provided ModelTransformJob doesn't exist.`
  + `Unable to find SageMaker AI resource. Please check your input.`

# Neptune ML 限制
<a name="machine-learning-limits"></a>
+ 目前支援的推論類型為節點分類、節點迴歸、邊緣分類、邊緣迴歸和連結預測 (請參閱 [Neptune ML 功能](machine-learning.md#machine-learning-capabilities))。
+ Neptune ML 可支援的圖形大小上限取決於[資料準備](machine-learning-on-graphs-instance-selection.md#machine-learning-on-graphs-processing-instance-size)、[模型訓練](machine-learning-on-graphs-instance-selection.md#machine-learning-on-graphs-training-transform-instance-size)和[推論](machine-learning-on-graphs-instance-selection.md#machine-learning-on-graphs-inference-endpoint-instance-size)期間所需的記憶體和儲存體數量。
  + SageMaker AI 資料處理執行個體的記憶體大小上限為 768 GB。因此，資料處理階段若需要超過 768 GB 的記憶體，就會失敗。
  + SageMaker AI 訓練執行個體的記憶體大小上限為 732 GB。因此，訓練階段若需要超過 732 GB 的記憶體，就會失敗。
+ SageMaker AI 端點的推論承載大小上限為 6 MiB。因此，如果子圖承載超過此大小，歸納推論就會失敗。
+ Neptune ML 目前僅適用於支援 Neptune 及其所依賴的其他服務 （例如 AWS Lambda Amazon API Gateway 和 Amazon SageMaker AI) 的區域。

  中國 (北京) 和中國 (寧夏) 中有關於預設使用 IAM 身分驗證的差異，如[這裡所述](https://docs.amazonaws.cn/en_us/aws/latest/userguide/api-gateway.html#feature-diff)以及其他差異。
+ Neptune ML 所啟動的連結預測推論端點目前只能預測訓練期間存在於圖形中之節點的可能連結。

  例如，考慮具有 `User` 和 `Movie` 頂點以及 `Rated` 邊緣的圖形。使用對應的 Neptune ML 連結預測建議模型，您可以將新的使用者新增至圖形，並讓模型為他們預測電影，但模型只能建議模型訓練期間存在的電影。雖然 `User` 節點嵌入是使用其本機子圖和 GNN 模型即時計算的，因此可在使用者對電影進行評分時隨時間變化，但會將其與靜態、預先計算的電影嵌入進行比較，以取得最終建議。
+ Neptune ML 支援的 KGE 模型僅適用於連結預測任務，而且表示法是在訓練期間存在於圖形中的頂點和邊緣類型特有的。這表示在訓練期間，推論查詢中提及的所有頂點和邊緣類型都必須存在於圖形中。若未重新訓練模型，則無法對新邊緣類型或頂點進行預測。

## SageMaker AI 資源限制
<a name="machine-learning-limits-sagemaker"></a>

根據您的活動和資源使用量，您可能會遇到錯誤訊息，指出[您已超過配額 ](https://docs.aws.amazon.com/sagemaker/latest/dg/regions-quotas.html)([ResourceLimitExceeded](https://repost.aws/knowledge-center/sagemaker-resource-limit-exceeded-error))。而且您需要擴展 SageMaker AI 資源，請遵循此頁面[請求提高 SageMaker 資源服務配額](https://docs.aws.amazon.com/sagemaker/latest/dg/regions-quotas.html#service-limit-increase-request-procedure)程序中的步驟，向 AWS Support 請求提高配額。

SageMaker AI 資源名稱對應至 Neptune ML 階段，如下所示：
+ SageMaker AI `ProcessingJob`用於 Neptune 資料處理、模型訓練和模型轉換任務。
+ Neptune 模型訓練任務`HyperParameterTuningJob`使用 SageMaker AI。
+ Neptune 模型訓練任務`TrainingJob`使用 SageMaker AI。
+ Neptune 推論端點`Endpoint`會使用 SageMaker AI。