

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

# 标记模型
<a name="tm-tagging-model"></a>

可以使用标签识别、整理、搜索和筛选 Amazon Rekognition 模型。每个标签都是由用户定义的键和值组成的标签。例如，为了帮助确定模型的账单，可使用 `Cost center` 键标记模型，并添加相应的成本中心编号作为值。有关更多信息，请参阅[标记 AWS 资源](https://docs.aws.amazon.com/general/latest/gr/aws_tagging.html)。

可以使用标签执行以下操作：
+ 使用成本分配标签跟踪模型的账单。有关更多信息，请参阅[使用成本分配标签](https://docs.aws.amazon.com/awsaccountbilling/latest/aboutv2/cost-alloc-tags.html)。
+ 可以使用 Identity and Access Management (IAM) 控制对模型的访问。有关更多信息，请参阅[使用资源标签控制对 AWS 资源的访问](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_tags.html)。
+ 自动管理模型。例如，可以运行自动启动或停止脚本，这些脚本可在非工作时间内关闭开发模型以降低成本。有关更多信息，请参阅 [运行经过训练的 Amazon Rekognition Custom Labels 模型](running-model.md)。

您可以使用 Amazon Rekognition 控制台或使用。 AWS SDKs

**Topics**
+ [标记模型（控制台）](#tm-tagging-model-console)
+ [查看模型标签](#tm-tagging-model-viewing-console)
+ [标记模型 (SDK)](#tm-tagging-model-sdk)

## 标记模型（控制台）
<a name="tm-tagging-model-console"></a>

可以使用 Rekognition 控制台为模型添加标签、查看附加到模型的标签以及移除标签。

### 添加或删除标签
<a name="tm-tagging-model-add-remove-console"></a>

此过程说明了如何向现有模型添加标签或从现有模型中移除标签。也可以在训练新模型后向其添加标签。有关更多信息，请参阅 [训练 Amazon Rekognition Custom Labels 模型](training-model.md)。

**使用控制台向现有模型添加标签或从现有模型中移除标签**

1. 打开亚马逊 Rekognition 控制台，网址为[ https://console.aws.amazon.com/rekognition/]( https://console.aws.amazon.com/rekognition/)。

1. 选择**开始**。

1. 在导航窗格中，选择**项目**。

1. 在**项目**资源页面上，选择包含要标记的模型的项目。

1. 在导航窗格中，于之前选择的项目下，选择**模型**。

1. 在**模型**部分中，选择要为其添加标签的模型。

1. 在模型的详细信息页面上，选择**标签**选项卡。

1. 在**标签**部分中，选择**管理标签**。

1. 在**管理标签**页面上，选择**添加新标签**。

1. 输入键和值。

   1. 对于**键**，输入键名称。

   1. 对于**值**，输入值。

1. 要添加更多标签，请重复步骤 9 和 10。

1. （可选）要移除标签，请选择要移除的标签旁的**移除**。如果移除的是先前保存的标签，则会在保存更改时将其移除。

1. 选择**保存更改**以保存您的更改。

## 查看模型标签
<a name="tm-tagging-model-viewing-console"></a>

可以使用 Amazon Rekognition 控制台查看附加到模型的标签。

要查看附加到*项目内所有模型*的标签，必须使用 AWS SDK。有关更多信息，请参阅 [列出模型标签](#listing-model-tags-sdk)。

**查看附加到模型的标签**

1. 打开亚马逊 Rekognition 控制台，网址为[ https://console.aws.amazon.com/rekognition/]( https://console.aws.amazon.com/rekognition/)。

1. 选择**开始**。

1. 在导航窗格中，选择**项目**。

1. 在**项目**资源页面上，选择包含要查看其标签的模型的项目。

1. 在导航窗格中，于之前选择的项目下，选择**模型**。

1. 在**模型**部分中，选择要查看其标签的模型。

1. 在模型的详细信息页面上，选择**标签**选项卡。**标签**部分中便会显示标签。

## 标记模型 (SDK)
<a name="tm-tagging-model-sdk"></a>

您可以使用 AWS SDK 执行以下操作：
+ 向新模型添加标签
+ 向现有模型添加标签
+ 列出附加到模型的标签 
+ 从模型中移除标签 

以下 AWS CLI 示例中的标签采用以下格式。

```
--tags '{"{{key1}}":"{{value1}}","{{key2}}":"{{value2}}"}' 
```

或者，也可以使用此格式。

```
--tags {{key1}}={{value1}},{{key2}}={{value2}}
```

如果您尚未安装 AWS CLI，请参阅[第 4 步：设置 AWS CLI and AWS 软件开发工具包](su-awscli-sdk.md)。

### 向新模型添加标签
<a name="tagging-new-model-sdk"></a>

使用[CreateProjectVersion](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_CreateProjectVersion.html)操作创建模型时，可以向模型添加标签。在 `Tags` 数组输入参数中指定一个或多个标签。

```
aws rekognition create-project-version --project-arn {{project arn}} \
  --version-name {{version_name}} \
  --output-config '{ "S3Location": { "Bucket": "{{output bucket}}", "Prefix":  "{{output folder}}" } }' \
  --tags '{"{{key1}}":"{{value1}}","{{key2}}":"{{value2}}"}' \
  --profile custom-labels-access
```

有关创建和训练模型的信息，请参阅[训练模型（SDK）](training-model.md#tm-sdk)。

### 向现有模型添加标签
<a name="tagging-new-model-sdk"></a>

要向现有模型添加一个或多个标签，请使用[TagResource](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_TagResource)操作。指定模型的 Amazon 资源名称 (ARN) (`ResourceArn`) 和要添加的标签 (`Tags`)。以下示例说明了如何添加两个标签。

```
aws rekognition tag-resource --resource-arn {{resource-arn}} \
  --tags '{"{{key1}}":"{{value1}}","{{key2}}":"{{value2}}"}' \
  --profile custom-labels-access
```

您可以通过调用来获取模型的 ARN。[CreateProjectVersion](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_CreateProjectVersion)

### 列出模型标签
<a name="listing-model-tags-sdk"></a>

要列出附加到模型的标签，请使用[ListTagsForResource](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_ListTagsForResource)操作并指定模型的 ARN () `ResourceArn`。响应是附加到指定模型的标签键和值的映射。

```
aws rekognition list-tags-for-resource --resource-arn {{resource-arn}} \
  --profile custom-labels-access
```

输出将显示附加到模型的标签列表。

```
{
    "Tags": {
        "Dept": "Engineering",
        "Name": "Ana Silva Carolina",
        "Role": "Developer"
    }
}
```

要查看项目中哪些模型具有特定标签，可调用 `DescribeProjectVersions` 获取模型列表。然后，为 `DescribeProjectVersions` 响应中的每个模型调用 `ListTagsForResource`。检查 `ListTagsForResource` 的响应，看是否存在所需的标签。

以下 Python 3 示例说明了如何在所有项目中搜索特定的标签键和值。输出包含在其中找到匹配键的项目 ARN 和模型 ARN。

**搜索标签值**

1. 将以下代码保存到名为 `find_tag.py` 的文件中。

   ```
   # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
   # SPDX-License-Identifier: Apache-2.0
   """
   Purpose
   Shows how to find a tag value that's associated with models within
   your Amazon Rekognition Custom Labels projects.
   """
   import logging
   import argparse
   import boto3
   
   from botocore.exceptions import ClientError
   
   
   logger = logging.getLogger(__name__)
   
   
   def find_tag_in_projects(rekognition_client, key, value):
       """
       Finds Amazon Rekognition Custom Label models tagged with the supplied key and key value.
       :param rekognition_client: An Amazon Rekognition boto3 client.
       :param key: The tag key to find.
       :param value: The value of the tag that you want to find.
       return: A list of matching model versions (and model projects) that were found.
       """
       try:
   
           found_tags = []
           found = False
   
           projects = rekognition_client.describe_projects()
           # Iterate through each project and models within a project.
           for project in projects["ProjectDescriptions"]:
               logger.info("Searching project: %s ...", project["ProjectArn"])
   
               models = rekognition_client.describe_project_versions(
                   ProjectArn=(project["ProjectArn"])
               )
   
               for model in models["ProjectVersionDescriptions"]:
                   logger.info("Searching model %s", model["ProjectVersionArn"])
   
                   tags = rekognition_client.list_tags_for_resource(
                       ResourceArn=model["ProjectVersionArn"]
                   )
   
                   logger.info(
                       "\tSearching model: %s for tag: %s value: %s.",
                       model["ProjectVersionArn"],
                       key,
                       value,
                   )
                   # Check if tag exists.
   
                   if key in tags["Tags"]:
                       if tags["Tags"][key] == value:
                           found = True
                           logger.info(
                               "\t\tMATCH: Project: %s: model version %s",
                               project["ProjectArn"],
                               model["ProjectVersionArn"],
                           )
                           found_tags.append(
                               {
                                   "Project": project["ProjectArn"],
                                   "ModelVersion": model["ProjectVersionArn"],
                               }
                           )
   
           if found is False:
               logger.info("No match for Tag %s with value %s.", key, value)
           return found_tags
       except ClientError as err:
           logger.info("Problem finding tags: %s. ", format(err))
           raise
   
   
   def main():
       """
       Entry point for example.
       """
       logging.basicConfig(level=logging.INFO,
                           format="%(levelname)s: %(message)s")
   
       # Set up command line arguments.
       parser = argparse.ArgumentParser(usage=argparse.SUPPRESS)
   
       parser.add_argument("tag", help="The tag that you want to find.")
       parser.add_argument("value", help="The tag value that you want to find.")
   
       args = parser.parse_args()
       key = args.tag
       value = args.value
   
       print(f"Searching your models for tag: {key} with value: {value}.")
   
   
       session = boto3.Session(profile_name='custom-labels-access')
       rekognition_client = session.client("rekognition")
   
       # Get tagged models for all projects.
       tagged_models = find_tag_in_projects(rekognition_client, key, value)
   
       print("Matched models\n--------------")
       if len(tagged_models) > 0:
           for model in tagged_models:
               print(
                   "Project: {project}\nModel version: {version}\n".format(
                       project=model["Project"], version=model["ModelVersion"]
                   )
               )
   
       else:
           print("No matches found.")
   
       print("Done.")
   
   
   if __name__ == "__main__":
       main()
   ```

1. 在命令提示符处，输入以下命令。{{value}}用要查找的键名和键值替换{{key}}和。

   ```
   python find_tag.py {{key}} {{value}}
   ```

### 从模型中删除标签
<a name="tm-removing-a-tag-sdk"></a>

要从模型中移除一个或多个标签，请使用[UntagResource](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_UntagResource)操作。指定模型的 ARN (`ResourceArn`) 和要移除的标签键 (`Tag-Keys`)。

```
aws rekognition untag-resource --resource-arn {{resource-arn}} \
  --tag-keys '["{{key1}}","{{key2}}"]' \
  --profile custom-labels-access
```

或者，也可以使用以下格式指定 `tag-keys`。

```
--tag-keys {{key1}},{{key2}} 
```