使用 Amazon SageMaker JumpStart PlatoBlockchain 数据智能进行微调和 HPO,从文本文档中识别关键见解。 垂直搜索。 人工智能。

使用 Amazon SageMaker JumpStart 通过微调和 HPO 从文本文档中识别关键见解

零售、银行、金融、医疗保健、制造和贷款等行业的组织通常需要处理来自各种来源的大量非结构化文本文档,例如新闻、博客、产品评论、客户支持渠道和社交媒体。 这些文档包含对做出重要业务决策至关重要的关键信息。 随着组织的发展,从这些文档中提取关键信息成为一项挑战。 随着自然语言处理 (NLP) 和机器学习 (ML) 技术的进步,我们可以快速、高精度地从这些文本文档中发现有价值的见解和联系,从而帮助公司及时做出高质量的业务决策。 完全托管的 NLP 服务也加速了 NLP 的采用。 亚马逊领悟 是一项完全托管的服务,使您能够构建特定于您的要求的自定义 NLP 模型,而无需任何 ML 专业知识。

在本文中,我们演示了如何利用最先进的 ML 技术来解决五种不同的 NLP 任务:文档摘要、文本分类、问答、命名实体识别和关系提取。 对于这些 NLP 任务中的每一个,我们都演示了如何使用 亚马逊SageMaker 执行以下操作:

  • 在预训练模型上部署和运行推理
  • 在新的自定义数据集上微调预训练模型
  • 进一步提高微调性能 SageMaker自动模型调整
  • 使用各种评估指标评估模型在保留测试数据上的性能

虽然我们在这篇文章中涵盖了五个特定的 NLP 任务,但您可以将此解决方案用作模板,以使用您自己的数据集泛化微调预训练模型,然后运行超参数优化以提高准确性。

JumpStart 解决方案模板

亚马逊SageMaker JumpStart 为许多常见的 ML 用例提供一键式端到端解决方案。 探索以下用例以获取有关可用解决方案模板的更多信息:

JumpStart 解决方案模板涵盖了各种用例,在每个用例下提供了几个不同的解决方案模板(此文档理解解决方案位于“从文档中提取和分析数据”用例下)。

从 JumpStart 登陆页面选择最适合您的用例的解决方案模板。 有关每个用例下的特定解决方案以及如何启动 JumpStart 解决方案的更多信息,请参阅 解决方案模板.

解决方案概述

下图演示了如何将此解决方案与 SageMaker 组件结合使用。 SageMaker 训练作业用于训练各种 NLP 模型,SageMaker 端点用于在每个阶段部署模型。 我们用 亚马逊简单存储服务 (Amazon S3) 与 SageMaker 一起存储训练数据和模型工件,以及 亚马逊CloudWatch 记录训练和端点输出。

打开文档理解解决方案

导航到 JumpStart 中的文档理解解决方案。

现在我们可以仔细看看这个解决方案中包含的一些资产,从演示笔记本开始。

使用 Amazon SageMaker JumpStart PlatoBlockchain 数据智能进行微调和 HPO,从文本文档中识别关键见解。 垂直搜索。 人工智能。

演示笔记本

您可以使用演示笔记本将示例数据发送到已部署的模型端点,以执行文档摘要和问答任务。 演示笔记本可以让您通过查询示例数据快速获得实践经验。

启动文档理解解决方案后,通过选择打开演示笔记本 在笔记本中使用端点.

使用 Amazon SageMaker JumpStart PlatoBlockchain 数据智能进行微调和 HPO,从文本文档中识别关键见解。 垂直搜索。 人工智能。

让我们深入了解此解决方案的五个主要笔记本中的每一个。

先决条件

In 亚马逊SageMaker Studio,确保您使用的是 PyTorch 1.10 Python 3.8 CPU Optimized image/kernel 打开笔记本。 训练使用五个 ml.g4dn.2xlarge 实例,所以你应该提出一个 服务限制增加请求 如果您的帐户需要增加此类型的限制。

文字分类

文本分类是指将输入句子分类到训练数据集的类标签之一。 该笔记本演示了如何使用 快速启动 API 用于文本分类。

在预训练模型上部署和运行推理

我们选择使用的文本分类模型是建立在文本嵌入(tensorflow-tc-bert-en-uncased-L-12-H-768-A-12-2) 模型来自 TensorFlow 中心,它在维基百科和 BookCorpus 数据集上进行了预训练。

可用于部署的模型是通过将二进制分类层附加到文本嵌入模型的输出来创建的,然后在 不锈钢-2 数据集,由正面和负面的电影评论组成。

要在此模型上运行推理,我们首先需要下载推理容器(deploy_image_uri), 推理脚本 (deploy_source_uri), 和预训练模型 (base_model_uri). 然后我们将这些作为参数传递以实例化一个 SageMaker 模型对象,然后我们可以部署它:

model = Model(
    image_uri=deploy_image_uri,
    source_dir=deploy_source_uri,
    model_data=base_model_uri,
    entry_point="inference.py",
    role=aws_role,
    predictor_cls=Predictor,
    name=endpoint_name_tc,
)
# deploy the Model.
base_model_predictor = model.deploy(
    initial_instance_count=1,
    instance_type=inference_instance_type,
    endpoint_name=endpoint_name_tc,
)

部署模型后,我们组装一些示例输入并查询端点:

text1 = "astonishing ... ( frames ) profound ethical and philosophical questions in the form of dazzling pop entertainment" 
text2 = "simply stupid , irrelevant and deeply , truly , bottomlessly cynical "

以下代码显示了我们的响应:

Inference:
Input text: 'astonishing ... ( frames ) profound ethical and philosophical questions in the form of dazzling pop entertainment'
Model prediction: [0.000452966779, 0.999547064]
Labels: [0, 1]
Predicted Label: 1 # value 0 means negative sentiment and value 1 means positive sentiment

Inference:
Input text: 'simply stupid , irrelevant and deeply , truly , bottomlessly cynical '
Model prediction: [0.998723, 0.00127695734]
Labels: [0, 1]
Predicted Label: 0

在自定义数据集上微调预训练模型

我们刚刚完成了对预训练 BERT 模型的运行推理,该模型在 SST-2 数据集。

接下来,我们讨论如何在具有任意数量类的自定义数据集上微调模型。 我们用于微调的数据集仍然是 SST-2 数据集。 您可以将此数据集替换为您感兴趣的任何数据集。

我们检索训练 Docker 容器、训练算法源和预训练模型:

from sagemaker import image_uris, model_uris, script_uris, hyperparameters

model_id, model_version = model_id, "*" # all the other options of model_id are the same as the one in Section 2.
training_instance_type = config.TRAINING_INSTANCE_TYPE

# Retrieve the docker image
train_image_uri = image_uris.retrieve(
    region=None,
    framework=None,
    model_id=model_id,
    model_version=model_version,
    image_scope="training",
    instance_type=training_instance_type,
)
# Retrieve the training script
train_source_uri = script_uris.retrieve(
    model_id=model_id, model_version=model_version, script_scope="training"
)
# Retrieve the pre-trained model tarball to further fine-tune
train_model_uri = model_uris.retrieve(
    model_id=model_id, model_version=model_version, model_scope="training"
)

对于特定于算法的超参数,我们首先获取算法接受的训练超参数及其默认值的 Python 字典。 您可以使用自定义值覆盖它们,如以下代码所示:

from sagemaker import hyperparameters

# Retrieve the default hyper-parameters for fine-tuning the model
hyperparameters = hyperparameters.retrieve_default(model_id=model_id, model_version=model_version)

# [Optional] Override default hyperparameters with custom values
hyperparameters["batch-size"] = "64"
hyperparameters["adam-learning-rate"] = "1e-6"

数据集 (SST-2) 分为训练集、验证集和测试集,其中训练集用于拟合模型,验证集用于计算可用于HPO的评估指标,测试集用作hold-out数据用于评估模型性能。 接下来,训练和验证数据集被上传到 Amazon S3 并用于启动微调训练作业:

# Create SageMaker Estimator instance
tc_estimator = Estimator(
    role=role,
    image_uri=train_image_uri,
    source_dir=train_source_uri,
    model_uri=train_model_uri,
    entry_point="transfer_learning.py",
    instance_count=1,
    instance_type=training_instance_type,
    max_run=360000,
    hyperparameters=hyperparameters,
    output_path=s3_output_location,
    tags=[{'Key': config.TAG_KEY, 'Value': config.SOLUTION_PREFIX}],
    base_job_name=training_job_name,
)

training_data_path_updated = f"s3://{config.S3_BUCKET}/{prefix}/train"
# Launch a SageMaker Training job by passing s3 path of the training data
tc_estimator.fit({"training": training_data_path_updated}, logs=True)

微调工作完成后,我们部署模型,在 hold-out 测试数据集上运行推理,并计算评估指标。 因为这是一个二元分类任务,我们使用 准确度分数F1分数 作为评价指标。 值越大表示性能越好。 以下屏幕截图显示了我们的结果。

使用 Amazon SageMaker JumpStart PlatoBlockchain 数据智能进行微调和 HPO,从文本文档中识别关键见解。 垂直搜索。 人工智能。

通过 SageMaker 自动模型调整进一步提高微调性能

在此步骤中,我们将演示如何通过使用 SageMaker 自动模型调整对模型进行微调来进一步提高模型性能。 自动模型调整,也称为超参数优化 (HPO),通过使用您指定的一系列超参数在您的数据集上运行多个训练作业来找到模型的最佳版本。 然后,它会选择超参数值,使模型在验证数据集上表现最佳(根据您选择的指标衡量)。

首先,我们将目标设置为验证数据的准确度得分(val_accuracy) 并通过指定目标指标名称和正则表达式 (regex) 为调优作业定义指标。 正则表达式用于匹配算法的日志输出并捕获指标的数值。 接下来,我们指定超参数范围以从中选择最佳超参数值。 我们将调整作业的总数设置为六个,并将这些作业分布在三个不同的 亚马逊弹性计算云 (Amazon EC2) 用于运行并行调整作业的实例。 请参见以下代码:

# Define objective metric per framework, based on which the best model will be selected.
metric_definitions_per_model = {
    "tensorflow": {
        "metrics": [{"Name": "val_accuracy", "Regex": "val_accuracy: ([0-9.]+)"}],
        "type": "Maximize",
    }
}

# You can select from the hyperparameters supported by the model, and configure ranges of values to be searched for training the optimal model.(https://docs.aws.amazon.com/sagemaker/latest/dg/automatic-model-tuning-define-ranges.html)
hyperparameter_ranges = {
    "adam-learning-rate": ContinuousParameter(0.00001, 0.01, scaling_type="Logarithmic")
}

# Increase the total number of training jobs run by AMT, for increased accuracy (and training time).
max_jobs = 6
# Change parallel training jobs run by AMT to reduce total training time, constrained by your account limits.
# if max_jobs=max_parallel_jobs then Bayesian search turns to Random.
max_parallel_jobs = 3

我们传递这些值以实例化 SageMaker Estimator 对象,类似于我们在之前的微调步骤中所做的。 而不是调用 fit 的功能 Estimator 对象,我们通过 Estimator 对象作为参数 超参数调谐器 构造函数并调用 fit 它启动调优作业的功能:

hp_tuner = HyperparameterTuner(
    tc_estimator,
    metric_definitions["metrics"][0]["Name"],
    hyperparameter_ranges,
    metric_definitions["metrics"],
    max_jobs=max_jobs,
    max_parallel_jobs=max_parallel_jobs,
    objective_type=metric_definitions["type"],
    base_tuning_job_name=tuning_job_name,
)

# Launch a SageMaker Tuning job to search for the best hyperparameters
hp_tuner.fit({"training": training_data_path_updated})

调优工作完成后,我们部署在验证数据集上给出最佳评估指标得分的模型,对我们在上一节中所做的相同保留测试数据集进行推理,并计算评估指标。

使用 Amazon SageMaker JumpStart PlatoBlockchain 数据智能进行微调和 HPO,从文本文档中识别关键见解。 垂直搜索。 人工智能。

结果表明,通过自动模型调整选择的模型在 hold-out 测试数据集上明显优于上一节中微调的模型。

命名实体识别

命名实体识别 (NER) 是检测命名实体并将其分类为预定义类别的过程,例如人名、组织、位置和数量。 NER 在现实世界中有许多用例,例如推荐引擎、对客户支持票进行分类并将其分配给正确的部门、从医疗保健中的患者报告中提取基本信息以及新闻和博客的内容分类。

在预训练模型上部署和运行推理

我们部署 en_core_web_md 来自的模型 空间 图书馆。 spaCy 是一个开源 NLP 库,可用于各种任务,并具有用于 NER 的内置方法。 我们使用具有脚本模式的 AWS PyTorch 深度学习容器 (DLC),并将 spaCy 库作为容器顶部的依赖项安装。

接下来,脚本的入口点(参数 entry_point.py) 被指定,包含下载和加载的所有代码 En_core_web_md 对发送到端点的数据进行建模和推理。 最后,我们还需要提供 model_data 作为推理的预训练模型。 因为预训练 En_core_web_md 模型是动态下载的,这是在入口脚本中指定的,我们提供一个空的存档文件。 部署端点后,您可以使用 SageMaker Python SDK 的 notebook 直接调用端点 Predictor。 请参见以下代码:

model = PyTorchModel(
    model_data=f"{config.SOURCE_S3_PATH}/artifacts/models/empty.tar.gz",
    entry_point="entry_point.py",
    source_dir="../containers/entity_recognition",
    role=config.IAM_ROLE,
    framework_version="1.5.0",
    py_version="py3",
    code_location="s3://" + config.S3_BUCKET + "/code",
    env={
        "MMS_DEFAULT_RESPONSE_TIMEOUT": "3000"
    }
)
predictor = model.deploy(
    endpoint_name=endpoint_name,
    instance_type=config.HOSTING_INSTANCE_TYPE,
    initial_instance_count=1,
    serializer=JSONSerializer(),
    deserializer=JSONDeserializer()
)

模型的输入数据是文本文档。 命名实体模型提取文本文档中的名词块和命名实体,并将它们分类为许多不同的类型(例如人、地点和组织)。 示例输入和输出显示在以下代码中。 这 start_char 参数指示跨度开始的字符偏移量,并且 end_char 表示跨度的结束。

data = {'text': 'Amazon SageMaker is a fully managed service that provides every developer and data scientist with the ability to build, train, and deploy machine learning (ML) models quickly.'}
response = predictor.predict(data=data)

print(response['entities'])
print(response['noun_chunks'])

[{'text': 'Amazon SageMaker', 'start_char': 0, 'end_char': 16, 'label': 'ORG'}]
[{'text': 'Amazon SageMaker', 'start_char': 0, 'end_char': 16}, {'text': 'a fully managed service', 'start_char': 20, 'end_char': 43}, {'text': 'that', 'start_char': 44, 'end_char': 48}, {'text': 'every developer and data scientist', 'start_char': 58, 'end_char': 92}, {'text': 'the ability', 'start_char': 98, 'end_char': 109}, {'text': 'ML', 'start_char': 156, 'end_char': 158}]

在自定义数据集上微调预训练模型

在此步骤中,我们将演示如何在您自己的数据集上为 NER 微调预训练语言模型。 微调步骤更新模型参数以捕获您自己数据的特征并提高准确性。 我们使用 维基神经网络 (PAN-X) 数据集微调 DistilBERT-base-uncased 来自 Hugging Face 的变形金刚模型。

数据集分为训练集、验证集和测试集。

接下来,我们指定模型的超参数,并使用带有脚本模式的 AWS Hugging Face DLC(参数 entry_point) 触发微调作业:

hyperparameters = {
    "pretrained-model": "distilbert-base-uncased",
    "learning-rate": 2e-6,
    "num-train-epochs": 2,
    "batch-size": 16,
    "weight-decay": 1e-5,
    "early-stopping-patience": 2,
}

ner_estimator = HuggingFace(
    pytorch_version='1.10.2',
    py_version='py38',
    transformers_version="4.17.0",
    entry_point='training.py',
    source_dir='../containers/entity_recognition/finetuning',
    hyperparameters=hyperparameters,
    role=aws_role,
    instance_count=1,
    instance_type=training_instance_type,
    output_path=f"s3://{bucket}/{prefix}/output",
    code_location=f"s3://{bucket}/{prefix}/output",
    tags=[{'Key': config.TAG_KEY, 'Value': config.SOLUTION_PREFIX}],
    sagemaker_session=sess,
    volume_size=30,
    env={
        'MMS_DEFAULT_RESPONSE_TIMEOUT': '500'
    },
    base_job_name = training_job_name
)

微调作业完成后,我们部署一个端点并使用保留测试数据查询该端点。 要查询端点,每个文本字符串都需要标记为一个或多个标记并发送到转换器模型。 每个令牌都有一个预测的命名实体标签。 因为每个文本字符串都可以标记为一个或多个标记,所以我们需要将字符串的 ground truth 命名实体标签复制到与其关联的所有标记。 提供的笔记本将引导您完成实现此目标的步骤。

最后,我们使用 Hugging Face 内置的评估指标 塞克瓦尔 计算保留测试数据的评估分数。 使用的评估指标是总体精度、总体召回率、总体 F1 和准确性。 以下屏幕截图显示了我们的结果。

使用 Amazon SageMaker JumpStart PlatoBlockchain 数据智能进行微调和 HPO,从文本文档中识别关键见解。 垂直搜索。 人工智能。

通过 SageMaker 自动模型调整进一步提高微调性能

与文本分类类似,我们演示了如何通过使用 SageMaker 自动模型调整对模型进行微调来进一步提高模型性能。 要运行调优作业,我们需要定义一个客观指标,用于评估验证数据集上的模型性能(在本例中为 F1 分数)、超参数范围以从中选择最佳超参数值,以及调优作业配置,例如一次启动的最大调优作业数和并行作业数:

hyperparameters_range = {
    "learning-rate": ContinuousParameter(1e-5, 0.1, scaling_type="Logarithmic"),
    "weight-decay": ContinuousParameter(1e-6, 1e-2, scaling_type="Logarithmic"),
}

tuner = HyperparameterTuner(
    estimator,
    "f1",
    hyperparameters_range,
    [{"Name": "f1", "Regex": "'eval_f1': ([0-9.]+)"}],
    max_jobs=6,
    max_parallel_jobs=3,
    objective_type="Maximize",
    base_tuning_job_name=tuning_job_name,
)

tuner.fit({
    "train": f"s3://{bucket}/{prefix}/train/",
    "validation": f"s3://{bucket}/{prefix}/validation/",
}, logs=True)

调优工作完成后,我们部署在验证数据集上给出最佳评估指标得分的模型,对我们在上一节中所做的相同保留测试数据集进行推理,并计算评估指标。

使用 Amazon SageMaker JumpStart PlatoBlockchain 数据智能进行微调和 HPO,从文本文档中识别关键见解。 垂直搜索。 人工智能。

我们可以看到,具有 HPO 的模型在所有指标上都取得了明显更好的性能。

问题回答

当您想查询大量文本以获取特定信息时,问答很有用。 它允许用户用自然语言表达问题并得到即时和简短的答复。 由 NLP 提供支持的问答系统可用于搜索引擎和电话对话界面。

在预训练模型上部署和运行推理

我们的预训练模型是提取式问答 (EQA) 模型 bert-large-uncased-whole-word-masking-finetuned-squad 基于 Hugging Face 的 Transformer 模型构建。 我们使用脚本模式的 AWS PyTorch DLC 并安装 变形金刚 库作为容器顶部的依赖项。 与 NER 任务类似,我们在参数中提供了一个空的存档文件 model_data 因为预训练模型是即时下载的。 部署端点后,您可以使用 SageMaker Python SDK 的 notebook 直接调用端点 Predictor。 请参见以下代码:

model = PyTorchModel(
    model_data=f"{config.SOURCE_S3_PATH}/artifacts/models/empty.tar.gz",
    entry_point="entry_point.py",
    source_dir="../containers/question_answering",
    role=config.IAM_ROLE,
    framework_version="1.5.0",
    py_version="py3",
    code_location="s3://" + config.S3_BUCKET + "/code",
    env={
        "MODEL_ASSETS_S3_BUCKET": config.SOURCE_S3_BUCKET,
        "MODEL_ASSETS_S3_PREFIX": f"{config.SOURCE_S3_PREFIX}/artifacts/models/question_answering/",
        "MMS_DEFAULT_RESPONSE_TIMEOUT": "3000",
    },
)

在成功部署端点并配置预测器后,我们可以在示例输入上试用问答模型。 该模型已经在 斯坦福问答数据集 (SQuAD) 数据集。 引入该数据集是为了进一步推进问答建模领域。 这是一个由文章、问题和答案组成的阅读理解数据集。

我们需要做的就是构造一个有两个键的字典对象。 context 是我们希望从中检索信息的文本。 question 是指定我们有兴趣提取的信息的自然语言查询。 我们称之为 predict 在我们的预测器上,我们应该从包含最可能答案的端点得到响应:

data = {'question': 'what is my name?', 'context': "my name is thom"}
response = predictor.predict(data=data)

我们有响应,我们可以打印出从前面的文本中提取的最有可能的答案。 每个答案都有一个用于排名的置信度分数(但不应将此分数解释为真实概率)。 除了逐字回答之外,您还可以从原始上下文中获取答案的开始和结束字符索引:

print(response['answers'])
[{'score': 0.9793591499328613, 'start': 11, 'end': 15, 'answer': 'thom'}, 
{'score': 0.02019440196454525, 'start': 0, 'end': 15, 'answer': 'my name is thom'}, 
{'score': 4.349117443780415e-05, 'start': 3, 'end': 15, 'answer': 'name is thom'}]

现在我们用我们自己的自定义数据集微调这个模型以获得更好的结果。

在自定义数据集上微调预训练模型

在此步骤中,我们将演示如何在您自己的数据集上微调用于 EQA 的预训练语言模型。 微调步骤更新模型参数以捕获您自己数据的特征并提高准确性。 我们使用 小队2.0 微调文本嵌入模型的数据集 bert-base-uncased 来自拥抱的脸。 可用于微调的模型将答案提取层附加到文本嵌入模型,并将层参数初始化为随机值。 微调步骤微调所有模型参数以最小化输入数据的预测误差并返回微调模型。

与文本分类任务类似,数据集 (SQuAD2.0) 分为训练集、验证集和测试集。

接下来,我们指定模型的超参数,并使用 快速启动 API 触发微调工作:

hyperparameters = {'epochs': '3', 'adam-learning-rate': '2e-05', 'batch-size': '16'}

eqa_estimator = Estimator(
    role=role,
    image_uri=train_image_uri,
    source_dir=train_source_uri,
    model_uri=train_model_uri,
    entry_point="transfer_learning.py",
    instance_count=1,
    instance_type=training_instance_type,
    max_run=360000,
    hyperparameters=hyperparameters,
    output_path=s3_output_location,
    tags=[{'Key': config.TAG_KEY, 'Value': config.SOLUTION_PREFIX}],
    base_job_name=training_job_name,
    debugger_hook_config=False,
)

training_data_path_updated = f"s3://{config.S3_BUCKET}/{prefix}/train"
# Launch a SageMaker Training job by passing s3 path of the training data
eqa_estimator.fit({"training": training_data_path_updated}, logs=True)

微调工作完成后,我们部署模型,在 hold-out 测试数据集上运行推理,并计算评估指标。 使用的评估指标是平均精确匹配分数和平均 F1 分数。 以下屏幕截图显示了结果。

使用 Amazon SageMaker JumpStart PlatoBlockchain 数据智能进行微调和 HPO,从文本文档中识别关键见解。 垂直搜索。 人工智能。

通过 SageMaker 自动模型调整进一步提高微调性能

与前面的部分类似,我们使用 HyperparameterTuner 启动调整作业的对象:

hyperparameter_ranges = {
    "adam-learning-rate": ContinuousParameter(0.00001, 0.01, scaling_type="Logarithmic"),
    "epochs": IntegerParameter(3, 10),
    "train-only-top-layer": CategoricalParameter(["True", "False"]),
}

hp_tuner = HyperparameterTuner(
    eqa_estimator,
    metric_definitions["metrics"][0]["Name"],
    hyperparameter_ranges,
    metric_definitions["metrics"],
    max_jobs=max_jobs,
    max_parallel_jobs=max_parallel_jobs,
    objective_type=metric_definitions["type"],
    base_tuning_job_name=training_job_name,
)

# Launch a SageMaker Tuning job to search for the best hyperparameters
hp_tuner.fit({"training": training_data_path_updated})

调优工作完成后,我们部署在验证数据集上给出最佳评估指标得分的模型,对我们在上一节中所做的相同保留测试数据集进行推理,并计算评估指标。

使用 Amazon SageMaker JumpStart PlatoBlockchain 数据智能进行微调和 HPO,从文本文档中识别关键见解。 垂直搜索。 人工智能。

我们可以看到,具有 HPO 的模型在保留测试数据上显示出明显更好的性能。

关系抽取

关系提取是从文本中提取语义关系的任务,通常发生在两个或多个实体之间。 关系提取在从原始文本等非结构化来源中提取结构化信息方面起着重要作用。 在此笔记本中,我们演示了关系提取的两个用例。

在自定义数据集上微调预训练模型

我们使用建立在 BERT-base-uncased 使用变压器的模型 拥抱脸变压器 图书馆。 用于微调的模型附加了一个线性分类层,该层采用文本嵌入模型输出的一对标记嵌入,并将层参数初始化为随机值。 微调步骤微调所有模型参数以最小化输入数据的预测误差并返回微调模型。

我们微调模型的数据集是 SemEval-2010 任务 8. 微调返回的模型可以进一步部署进行推理。

数据集包含训练集、验证集和测试集。

我们将 AWS PyTorch DLC 与 SageMaker Python SDK 的脚本模式结合使用,其中 transformers 库作为容器顶部的依赖项安装。 我们定义 SageMaker PyTorch 估计器和一组超参数,如预训练模型、学习率和 epoch 数,以执行微调。 微调关系抽取模型的代码定义在 entry_point.py。 请参见以下代码:

hyperparameters = {
    "pretrained-model": "bert-base-uncased",
    "learning-rate": 0.0002,
    "max-epoch": 2,
    "weight-decay": 0,
    "batch-size": 16,
    "accumulate-grad-batches": 2,
    "gradient-clip-val": 1.0
}

re_estimator = PyTorch(
    framework_version='1.5.0',
    py_version='py3',
    entry_point='entry_point.py',
    source_dir='../containers/relationship_extraction',
    hyperparameters=hyperparameters,
    role=aws_role,
    instance_count=1,
    instance_type=train_instance_type,
    output_path=f"s3://{bucket}/{prefix}/output",
    code_location=f"s3://{bucket}/{prefix}/output",
    base_job_name=training_job_name,
    tags=[{'Key': config.TAG_KEY, 'Value': config.SOLUTION_PREFIX}],
    sagemaker_session=sess,
    volume_size=30,
    env={
        'MMS_DEFAULT_RESPONSE_TIMEOUT': '500'
    },
    debugger_hook_config=False
)

re_estimator.fit(
    {
        "train": f"s3://{bucket}/{prefix}/train/",
        "validation": f"s3://{bucket}/{prefix}/validation/",
    }
)

训练作业大约需要 31 分钟才能完成。 我们使用该模型对保留测试集进行推理,并使用以下方法评估结果 , F1宏F1微型 分数。 以下屏幕截图显示了评估分数。

使用 Amazon SageMaker JumpStart PlatoBlockchain 数据智能进行微调和 HPO,从文本文档中识别关键见解。 垂直搜索。 人工智能。

通过 SageMaker 自动模型调整进一步提高微调性能

与前面的部分类似,我们使用 HyperparameterTuner 对象与 SageMaker 超参数调整 API 进行交互。 我们可以通过调用 fit 方法:

hyperparameters = {
    "max-epoch": 2,
    "weight-decay": 0,
    "batch-size": 16,
    "accumulate-grad-batches": 2,
    "gradient-clip-val": 1.0
}

estimator = PyTorch(
    framework_version='1.5.0',
    py_version='py3',
    entry_point='entry_point.py',
    source_dir='../containers/relationship_extraction',
    hyperparameters=hyperparameters,
    role=aws_role,
    instance_count=1,
    instance_type=train_instance_type,
    output_path=f"s3://{bucket}/{prefix}/output",
    code_location=f"s3://{bucket}/{prefix}/output",
    base_job_name=tuning_job_name,
    tags=[{'Key': config.TAG_KEY, 'Value': config.SOLUTION_PREFIX}],
    sagemaker_session=sess,
    volume_size=30,
    env={
        'MMS_DEFAULT_RESPONSE_TIMEOUT': '500'
    },
    debugger_hook_config=False
    
    re_tuner = HyperparameterTuner(
    estimator,
    metric_definitions["metrics"][0]["Name"],
    hyperparameter_ranges,
    metric_definitions["metrics"],
    max_jobs=max_jobs,
    max_parallel_jobs=max_parallel_jobs,
    objective_type=metric_definitions["type"],
    base_tuning_job_name=tuning_job_name,
)

re_tuner.fit({
    "train": f"s3://{bucket}/{prefix}/train/",
    "validation": f"s3://{bucket}/{prefix}/validation/",
})

当超参数调整工作完成后,我们进行推理并检查评估分数。

使用 Amazon SageMaker JumpStart PlatoBlockchain 数据智能进行微调和 HPO,从文本文档中识别关键见解。 垂直搜索。 人工智能。

我们可以看到,具有 HPO 的模型在保留测试数据上显示出更好的性能。

文件摘要

文档或文本摘要是将大量文本数据压缩为更小的有意义句子子集的任务,这些句子代表原始内容中最重要或相关的信息。 文档摘要是一种有用的技术,可以将重要信息从大量文本数据中提取到几个句子中。 文本摘要用于许多用例,例如文档处理和从博客、文章和新闻中提取信息。

此笔记本演示部署文档摘要模型 T5-基地 来自 拥抱脸变压器 图书馆。 我们还使用文本文章测试部署的端点,并使用 Hugging Face 内置评估指标评估结果 RED.

类似于问答和 NER 笔记本,我们使用 PyTorchModel 来自 SageMaker Python SDK 以及 entry_point.py 用于将 T5 基础模型加载到 HTTPS 端点的脚本。 端点部署成功后,我们可以向端点发送文本文章以获取预测响应:

ARTICLE = """ Documents are a primary tool for communication,
collaboration, record keeping, and transactions across industries,
including financial, medical, legal, and real estate. The format of data
can pose an extra challenge in data extraction, especially if the content
is typed, handwritten, or embedded in a form or table. Furthermore,
extracting data from your documents is manual, error-prone, time-consuming,
expensive, and does not scale. Amazon Textract is a machine learning (ML)
service that extracts printed text and other data from documents as well as
tables and forms. We’re pleased to announce two new features for Amazon
Textract: support for handwriting in English documents, and expanding
language support for extracting printed text from documents typed in
Spanish, Portuguese, French, German, and Italian. Many documents, such as
medical intake forms or employment applications, contain both handwritten
and printed text. The ability to extract text and handwriting has been a
need our customers have asked us for. Amazon Textract can now extract
printed text and handwriting from documents written in English with high
confidence scores, whether it’s free-form text or text embedded in tables
and forms. Documents can also contain a mix of typed text or handwritten
text. The following image shows an example input document containing a mix
of typed and handwritten text, and its converted output document.."""

data = {'text': ARTICLE}
response = predictor.predict(data=data)
print(response['summary'])

"""Amazon Textract is a machine learning (ML) service that extracts printed text 
and other data from documents as well as tables and forms . 
customers can now extract and process documents in more languages .
support for handwriting in english documents and expanding language support for extracting 
printed text ."""

接下来,我们使用 ROUGE 指标评估和比较文本文章和摘要结果。 计算三个评估指标: rougeN, rougeLrougeLsum. rougeN 衡量匹配的数量 n-grams 在模型生成的文本(汇总结果)和 reference (输入文本)。 指标 rougeLrougeLsum 通过在生成的摘要和参考摘要中寻找最长的公共子串来测量最长的匹配单词序列。 对于每个指标,计算精度、召回率和 F1 分数的置信区间。请参见以下代码:

results = rouge.compute(predictions=[response['summary']], references=[ARTICLE])

rouge1: AggregateScore(low=Score(precision=1.0, recall=0.1070615034168565, fmeasure=0.1934156378600823), 
mid=Score(precision=1.0, recall=0.1070615034168565, fmeasure=0.1934156378600823), high=Score(precision=1.0, recall=0.1070615034168565, fmeasure=0.1934156378600823))

rouge2: AggregateScore(low=Score(precision=0.9565217391304348, recall=0.1004566210045662, fmeasure=0.18181818181818182), 
mid=Score(precision=0.9565217391304348, recall=0.1004566210045662, fmeasure=0.18181818181818182), high=Score(precision=0.9565217391304348, recall=0.1004566210045662, 
fmeasure=0.18181818181818182))

rougeL: AggregateScore(low=Score(precision=0.8085106382978723, recall=0.08656036446469248, fmeasure=0.15637860082304528), 
mid=Score(precision=0.8085106382978723, recall=0.08656036446469248, fmeasure=0.15637860082304528), high=Score(precision=0.8085106382978723, recall=0.08656036446469248, 
fmeasure=0.15637860082304528))

rougeLsum: AggregateScore(low=Score(precision=0.9787234042553191, recall=0.10478359908883828, fmeasure=0.18930041152263374), 
mid=Score(precision=0.9787234042553191, recall=0.10478359908883828, fmeasure=0.18930041152263374), high=Score(precision=0.9787234042553191, recall=0.10478359908883828, 
fmeasure=0.18930041152263374))

清理

可以使用删除为此解决方案创建的资源 删除所有资源 SageMaker Studio IDE 中的按钮。 每个笔记本还提供了一个清理部分,其中包含删除端点的代码。

使用 Amazon SageMaker JumpStart PlatoBlockchain 数据智能进行微调和 HPO,从文本文档中识别关键见解。 垂直搜索。 人工智能。

结论

在本文中,我们演示了如何利用最先进的 ML 技术解决五种不同的 NLP 任务:文档摘要、文本分类、问答、命名实体识别和使用 Jumpstart 的关系提取。 立即开始使用 Jumpstart!


作者简介

使用 Amazon SageMaker JumpStart PlatoBlockchain 数据智能进行微调和 HPO,从文本文档中识别关键见解。 垂直搜索。 人工智能。黄鑫博士 是 Amazon SageMaker JumpStart 和 Amazon SageMaker 内置算法的应用科学家。 他专注于开发可扩展的机器学习算法。 他的研究兴趣是自然语言处理、表格数据的可解释深度学习以及非参数时空聚类的稳健分析。 他在 ACL、ICDM、KDD 会议和皇家统计学会:A 系列期刊上发表了多篇论文。

使用 Amazon SageMaker JumpStart PlatoBlockchain 数据智能进行微调和 HPO,从文本文档中识别关键见解。 垂直搜索。 人工智能。维韦克甘加萨尼 是 Amazon Web Services 的高级机器学习解决方案架构师。 他帮助初创公司构建和运营 AI/ML 应用程序。 他目前专注于结合他在容器和机器学习方面的背景,以提供有关 MLOps、ML 推理和低代码 ML 的解决方案。 在业余时间,他喜欢尝试新餐厅,探索人工智能和深度学习的新兴趋势。

使用 Amazon SageMaker JumpStart PlatoBlockchain 数据智能进行微调和 HPO,从文本文档中识别关键见解。 垂直搜索。 人工智能。杰里米·科恩 是 AWS 的解决方案架构师,他帮助客户构建基于云的尖端解决方案。 在业余时间,他喜欢在海滩上短途散步,和家人一起探索海湾地区,修理房子周围的东西,破坏房子周围的东西,以及烧烤。

使用 Amazon SageMaker JumpStart PlatoBlockchain 数据智能进行微调和 HPO,从文本文档中识别关键见解。 垂直搜索。 人工智能。尼拉姆·克希亚 是AWS的企业解决方案架构师。 她目前的重点是帮助企业客户采用云技术,以实现战略业务成果。 在业余时间,她喜欢读书和在户外。

时间戳记:

更多来自 AWS机器学习