如何将GridSearchCV训练的模型部署到Amazon SageMaker并创建端点
自定义Scikit-learn模型部署到Amazon SageMaker指南及疑问解答
核心疑问解答:是否必须使用SageMaker内置算法?
不需要。Amazon SageMaker支持部署自定义框架模型(如Scikit-learn、TensorFlow、PyTorch等),无需依赖SageMaker内置算法。你可以直接部署自己用GridSearchCV训练的Scikit-learn Pipeline模型。
具体部署步骤(基于你的训练代码)
1. 保存训练好的最优模型
你的训练代码中,grid_search.best_estimator_是经过GridSearchCV筛选后的最优Pipeline模型(包含预处理逻辑+分类器),需要将其序列化保存:
import joblib # 保存最优模型 best_model = grid_search.best_estimator_ joblib.dump(best_model, 'titanic_model.joblib') # 上传模型到S3(SageMaker部署需要模型存储在S3) import sagemaker from sagemaker.s3 import S3Uploader sagemaker_session = sagemaker.Session() model_s3_path = S3Uploader.upload(local_path='titanic_model.joblib', desired_s3_uri=f's3://{sagemaker_session.default_bucket()}/titanic-model')
2. 编写推理脚本(inference.py)
SageMaker的Scikit-learn容器需要特定的接口函数来处理推理请求,创建如下脚本:
import joblib import pandas as pd def model_fn(model_dir): # 加载保存的模型 model = joblib.load(f"{model_dir}/titanic_model.joblib") return model def input_fn(request_body, request_content_type): # 处理输入数据(示例:JSON格式的请求) if request_content_type == 'application/json': input_data = pd.read_json(request_body, orient='records') return input_data else: raise ValueError(f"Unsupported content type: {request_content_type}") def predict_fn(input_data, model): # 执行预测 predictions = model.predict(input_data) return predictions def output_fn(prediction, accept): # 格式化输出结果 if accept == 'application/json': return pd.DataFrame(prediction, columns=['Survived']).to_json(orient='records'), accept else: raise ValueError(f"Unsupported accept type: {accept}")
3. 创建SageMaker模型并部署端点
使用SageMaker的SKLearnModel类封装模型,然后部署:
from sagemaker.sklearn.model import SKLearnModel from sagemaker import get_execution_role # 获取SageMaker执行角色 role = get_execution_role() # 创建SKLearnModel对象 sklearn_model = SKLearnModel(model_data=model_s3_path, role=role, entry_point='inference.py', framework_version='1.2-1') # 需匹配你的Scikit-learn版本,兼容SageMaker容器 # 部署模型到端点 predictor = sklearn_model.deploy(instance_type='ml.t2.medium', initial_instance_count=1)
4. 测试推理端点
部署完成后,发送测试请求验证:
# 构造测试数据(和训练时的输入格式一致) test_data = pd.DataFrame([{ 'Pclass': 3, 'Sex': 'male', 'Age': 22.0, 'SibSp': 1, 'Parch': 0, 'Fare': 7.25, 'Embarked': 'S' }]) # 发送预测请求 prediction = predictor.predict(test_data) print(f"预测生存结果: {prediction[0]}")
5. 清理资源(可选)
测试完成后,若不再需要端点,记得删除以避免费用:
predictor.delete_endpoint()
内容的提问来源于stack exchange,提问作者Lijin Durairaj
相关产品推荐
相关产品推荐

