首页 > 解决方案 > 如何调用 Sagemaker XGBoost 端点后模型创建?

问题描述

我一直在关注这个非常有用的关于 Medium 的 XGBoost 教程(用于文章底部的代码):https ://medium.com/analytics-vidhya/random-forest-and-xgboost-on-amazon-sagemaker-and- aws-lambda-29abd9467795

迄今为止,我已经能够获得为 ML 目的而适当格式化的数据、基于训练数据创建的模型,然后测试通过模型馈送的数据以给出有用的结果。

然而,每当我离开并回来在模型上进行更多工作或输入新的测试数据时,我发现我需要重新运行所有模型创建步骤才能做出进一步的预测。相反,我只想根据 Image_URI 调用我已经创建的模型端点并输入新数据。

当前执行的步骤:

模型训练

xgb = sagemaker.estimator.Estimator(containers[my_region],
                                    role, 
                                    train_instance_count=1, 
                                    train_instance_type='ml.m4.xlarge',
                                    output_path='s3://{}/{}/output'.format(bucket_name, prefix),
                                    sagemaker_session=sess)
xgb.set_hyperparameters(eta=0.06,
                        alpha=0.8,
                        lambda_bias=0.8,
                        gamma=50,
                        min_child_weight=6,
                        subsample=0.5,
                        silent=0,
                        early_stopping_rounds=5,
                        objective='reg:linear',
                        num_round=1000)

xgb.fit({'train': s3_input_train})

xgb_predictor = xgb.deploy(initial_instance_count=1,instance_type='ml.m4.xlarge')

评估

test_data_array = test_data.drop([ 'price','id','sqft_above','date'], axis=1).values #load the data into an array

xgb_predictor.serializer = csv_serializer # set the serializer type

predictions = xgb_predictor.predict(test_data_array).decode('utf-8') # predict!
predictions_array = np.fromstring(predictions[1:], sep=',') # and turn the prediction into an array
print(predictions_array.shape)

from sklearn.metrics import r2_score
print("R2 score : %.2f" % r2_score(test_data['price'],predictions_array))

似乎这条特定的行:

predictions = xgb_predictor.predict(test_data_array).decode('utf-8') # predict!

需要重新编写以便不引用 xgb.predictor 而是引用模型位置。

我试过以下

trained_model = sagemaker.model.Model(
    model_data='s3://{}/{}/output/xgboost-2020-11-10-00-00/output/model.tar.gz'.format(bucket_name, prefix),
    image_uri='XXXXXXXXXX.dkr.ecr.us-east-1.amazonaws.com/xgboost:latest',
    role=role)  # your role here; could be different name

trained_model.deploy(initial_instance_count=1, instance_type='ml.m4.xlarge')

然后替换

xgb_predictor.serializer = csv_serializer # set the serializer type
predictions = xgb_predictor.predict(test_data_array).decode('utf-8') # predict!

trained_model.serializer = csv_serializer # set the serializer type
predictions = trained_model.predict(test_data_array).decode('utf-8') # predict!

但我收到以下错误:

AttributeError: 'Model' object has no attribute 'predict'

标签: pythonmachine-learningxgboostamazon-sagemaker

解决方案


这是一个好问题 :) 我同意,许多官方教程倾向于展示完整的 train-to-invoke 管道,并且没有足够强调每个步骤都可以单独完成。在您的特定情况下,当您想要调用已部署的端点时,您可以:(A) 在众多 SDK 之一中使用调用 API 调用(例如CLIboto3)或 (B) 或predictor使用高级 Python SDK,无论是泛型sagemaker.model.Model类还是它的 XGBoost 特定子类:sagemaker.xgboost.model.XGBoostPredictor如下图所示:

from sagemaker.xgboost.model import XGBoostPredictor
    
predictor = XGBoostPredictor(endpoint_name='your-endpoint')
predictor.predict('<payload>')

类似的问题How to use a pretrained model from s3 to predict some data?

笔记:

  • 如果您希望model.deploy()调用返回一个预测器,您的模型必须用predictor_cls. 这是可选的,您也可以先部署模型,然后使用上述技术将其作为单独的步骤调用
  • 即使您不调用端点,端点也会产生费用;他们按正常运行时间收费。因此,如果您不需要始终在线的端点,请不要犹豫,将其关闭以最大限度地降低成本。

推荐阅读