本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。
您可以使用图像分类- TensorFlow 作为 Amazon A SageMaker I 的内置算法。以下部分介绍如何在 SageMaker AI Python 软件开发工具包中 TensorFlow 使用图像分类。有关如何使用 Amazon SageMaker Studio 经典版用户界面中的图片分类的信息,请参阅SageMaker JumpStart 预训练模型。 TensorFlow
图像分类- TensorFlow 算法支持使用任何兼容的预训练 TensorFlow Hub 模型进行迁移学习。有关所有可用的预先训练模型的列表,请参阅 TensorFlow 集线器型号。每个预先训练的模型都有独特的 model_id
。以下示例使用 MobileNet V2 1.00 224 (model_id
:tensorflow-ic-imagenet-mobilenet-v2-100-224-classification-4
) 对自定义数据集进行微调。预训练的模型都是从 TensorFlow Hub 预先下载的,并存储在 Amazon S3 存储桶中,这样训练作业就可以在网络隔离的情况下运行。使用这些预生成的模型训练工件来构建 A SageMaker I 估算器。
首先,检索 Docker 映像 URI、训练脚本 URI 和预先训练模型 URI。然后,根据需要更改超参数。您可以使用 hyperparameters.retrieve_default
查看包含所有可用超参数及其默认值的 Python 字典。有关更多信息,请参阅 图像分类- TensorFlow 超参数。使用这些值构建 A SageMaker I 估算器。
注意
不同模型具有不同的默认超参数值。对于较大的模型,默认批量大小较小,且 train_only_top_layer
超参数设置为 "True"
。
此示例使用 tf_flowers
.fit
。
from sagemaker import image_uris, model_uris, script_uris, hyperparameters
from sagemaker.estimator import Estimator
model_id, model_version = "tensorflow-ic-imagenet-mobilenet-v2-100-224-classification-4"
, "*"
training_instance_type = "ml.p3.2xlarge"
# Retrieve the Docker image
train_image_uri = image_uris.retrieve(model_id=model_id,model_version=model_version,image_scope="training",instance_type=training_instance_type,region=None,framework=None)
# Retrieve the training script
train_source_uri = script_uris.retrieve(model_id=model_id, model_version=model_version, script_scope="training")
# Retrieve the pretrained model tarball for transfer learning
train_model_uri = model_uris.retrieve(model_id=model_id, model_version=model_version, model_scope="training")
# 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["epochs"] = "5"
# The sample training data is available in the following S3 bucket
training_data_bucket = f"jumpstart-cache-prod-{aws_region}"
training_data_prefix = "training-datasets/tf_flowers/"
training_dataset_s3_path = f"s3://{training_data_bucket}/{training_data_prefix}"
output_bucket = sess.default_bucket()
output_prefix = "jumpstart-example-ic-training"
s3_output_location = f"s3://{output_bucket}/{output_prefix}/output"
# Create SageMaker Estimator instance
tf_ic_estimator = Estimator(
role=aws_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,
)
# Use S3 path of the training data to launch SageMaker TrainingJob
tf_ic_estimator.fit({"training": training_dataset_s3_path}, logs=True)