我一直在关注Medium上这个非常有帮助的XGBoost教程(文章底部有使用到的代码):https://medium.com/analytics-vidhya/random-forest-and-xgboost-on-amazon-sagemaker-and-aws-lambda-29abd9467795。
到目前为止,我已经能够将数据适当地格式化以用于机器学习目的,基于训练数据创建模型,并将测试数据输入模型以获得有用的结果。
然而,每当我离开并回来继续工作在模型上或输入新的测试数据时,我发现我需要重新运行所有模型创建步骤才能进行进一步的预测。相反,我希望仅根据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 arrayxgb_predictor.serializer = csv_serializer # set the serializer typepredictions = xgb_predictor.predict(test_data_array).decode('utf-8') # predict!predictions_array = np.fromstring(predictions[1:], sep=',') # and turn the prediction into an arrayprint(predictions_array.shape)from sklearn.metrics import r2_scoreprint("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 nametrained_model.deploy(initial_instance_count=1, instance_type='ml.m4.xlarge')
然后替换
xgb_predictor.serializer = csv_serializer # set the serializer typepredictions = xgb_predictor.predict(test_data_array).decode('utf-8') # predict!
为
trained_model.serializer = csv_serializer # set the serializer typepredictions = trained_model.predict(test_data_array).decode('utf-8') # predict!
但我得到了以下错误:
AttributeError: 'Model' object has no attribute 'predict'
回答:
这是一个很好的问题 🙂 我同意,许多官方教程往往展示从训练到调用的完整流程,而没有足够强调每个步骤可以单独完成。在你特定的情况下,当你想调用已部署的端点时,你可以:(A) 在众多SDK中使用invoke API调用(例如在CLI、boto3中),或者(B) 使用高级Python SDK实例化一个predictor
,可以使用通用的sagemaker.model.Model
类或其XGBoost特定的子类:sagemaker.xgboost.model.XGBoostPredictor
,如下所示:
from sagemaker.xgboost.model import XGBoostPredictor predictor = XGBoostPredictor(endpoint_name='your-endpoint')predictor.predict('<payload>')
注意:
- 如果你希望
model.deploy()
调用返回一个predictor,你的模型必须使用predictor_cls
进行实例化。这是可选的,你也可以先部署一个模型,然后再用上述技术作为一个单独的步骤来调用它 - 即使你不调用端点,端点也会产生费用;它们按运行时间收费。所以如果你不需要一个始终在线的端点,不妨将其关闭以最大限度地降低成本。