

本文属于机器翻译版本。若本译文内容与英语原文存在差异，则一律以英文原文为准。

# Neptune ML 中的 Gremlin 推理查询
<a name="machine-learning-gremlin-inference-queries"></a>

如[Neptune ML 功能](machine-learning.md#machine-learning-capabilities)中所述，Neptune ML 支持可以执行以下类型的推理任务的训练模型：
+ **节点分类** - 预测顶点属性的分类特征。
+ **节点回归** - 预测顶点的数值属性。
+ **边缘分类** - 预测边缘属性的分类特征。
+ **边缘回归** - 预测边缘的数值属性。
+ **链接预测** - 根据源节点和传出边缘预测目标节点，或者根据目标节点和传入边缘预测源节点。

我们可以通过使用 R [GroupLens es](https://grouplens.org/datasets/movielens/) earch 提供的 [MovieLens 100k 数据集](https://grouplens.org/datasets/movielens/100k/)的示例来说明这些不同的任务。这个数据集由电影、用户和用户对电影的评分组成，我们从中创建了如下所示的属性图：

![\[使用 MovieLens 100k 数据集的电影属性图示例\]](http://docs.aws.amazon.com/zh_cn/neptune/latest/userguide/images/movie_property_graph_example.png)


**节点分类**：在上面的数据集中，`Genre` 是一种通过 `included_in` 边缘与顶点类型 `Movie` 相连的顶点类型。但是，如果我们调整数据集以使 `Genre` 成为顶点类型 `Movie` 的[分类](https://en.wikipedia.org/wiki/Categorical_variable)特征，则可以使用节点分类模型来解决对于添加到知识图谱中的新电影推理 `Genre` 的问题。

**节点回归**：如果我们考虑具有如 `timestamp` 和 `score` 等属性的顶点类型 `Rating`，则可以使用节点回归模型来解决对于 `Rating` 推理数值 `Score` 的问题。

**边缘分类**：同样，对于`Rated`边缘，如果我们有一个属性`Scale`可以具有其中一个值`Love``Like`、`Dislike`、`Neutral``Hate`、、，那么 movies/ratings 可以使用`Rated`边分类模型来解决推断`Scale`新边缘的问题。

**边缘回归**：同样，对于同一 `Rated` 边缘，如果我们有一个属性 `Score` 可以保存评分的数值，那么可以从边缘回归模型中推理出来。

**链接预测**：诸如查找最有可能对给定电影进行评分的前十名用户，或者找到给定用户最有可能评分的前十部电影之类的问题，属于链接预测的范围。

**注意**  
对于 Neptune ML 用例，我们有一套非常丰富的笔记本，旨在让您亲身了解每个用例。当你使用 Neptune [ML CloudFormation 模板创建 Neptune 机器学习集群时，你可以将这些笔记本与 Neptune](machine-learning-quick-start.md) 集群一起创建。这些笔记本也可以在 [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 获取元数据可能会比较慢，但是当 A SageMaker I 终端节点在重新训练或转换后更新并且缓存已过时时，它会很有用。

您可以在查询中加入 `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>

必要时，在 `with()` 步骤中使用 `Neptune#ml.endpoint` 谓词来指定推理端点：

```
 .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()`步骤中用于指定 A SageMaker I 执行 IAM 角色的 ARN（如有必要）：

```
 .with("Neptune#ml.iamRoleArn", "the ARN for the SageMaker AI execution IAM role")
```

有关如何创建 A SageMaker I 执行 IAM 角色的信息，请参阅[创建自定义 NeptuneSageMakerIAMRole 角色](machine-learning-manual-setup.md#ml-manual-setup-sm-role)。

**注意**  
如果您[将 Neptune 数据库集群参数组中的参数设置](machine-learning-cluster-setup.md#machine-learning-enabling-create-param-group)为 A SageMaker I 执行 IAM 角色的 ARN，则无需在每个查询中都包含该`Neptune#ml.iamRoleArn`谓词。`neptune_ml_iam_role`

## 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>

在 Gremlin 节点或边缘分类查询中使用 `Neptune#ml.score` 谓词来获取机器学习置信度分数。在 `properties()` 步骤中应将 `Neptune#ml.score` 谓词与查询谓词一起传递，以获得节点或边缘分类查询的 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 节点分类：
+ 模型是在顶点的一个属性上训练的。此属性的唯一值集合称为一组节点类，或者简称为类。
+ 可以从节点分类模型中推理顶点属性的节点类或分类属性值。当此属性尚未附加到顶点时，这很有用。
+ 要从节点分类模型中获取一个或多个类，您需要使用带有谓词 `Neptune#ml.classification` 的 `with()` 步骤来配置 `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")` 以表明这是节点分类机器学习推理查询。

目前不支持在 `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 边缘分类：
+ 模型是在边缘的一个属性上训练的。此属性的唯一值集合称为一组类。
+ 可以从边缘分类模型中推理边缘的类或分类属性值，当该属性尚未附加到边缘时，该模型很有用。
+ 要从边缘分类模型中获取一个或多个类，您需要使用带有谓词 `"Neptune#ml.classification"` 的 `with()` 步骤来配置 `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")` 以表明这是边缘分类机器学习推理查询。

目前不支持在 `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`，则可以使用如下查询对于其大于或等于 9 的边缘推理 `Score`：

```
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 角色或端点相关问题，到不受支持的 Gremlin 步骤以及对每次查询的 ML 推理查询数量的限制。每个条目都包含一条描述问题的详细消息。
+ **`BadRequestException`** – 无法加载所提供角色的凭证。

  *消息*：`Unable to load credentials for role: the specified IAM Role ARN.`
+ **`BadRequestException`**— 指定的 IAM 角色无权调用 A SageMaker I 终端节点。

  *消息*：`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**— A SageMaker I 执行 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`**– 在链接预测查询中，没有在带有 `in()` 或 `out()` 步骤的 `has()` 步骤中指定预测顶点标签。

  *消息*：`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`** – 每个 Gremlin 查询目前仅支持一个 Neptune ML 推理查询。

  *消息*：`Neptune ML inference queries are currently supported only with one ML inference query per gremlin query.`