Here's a comprehensive guide to deploying a computer vision model on Amazon SageMaker:
Preparing Your Model
First, ensure your model is in a supported format. SageMaker supports various frameworks:
TensorFlow (.pb, SavedModel format)
PyTorch (.pt, .pth files)
MXNet
ONNX
Custom containers with any framework
Package your model artifacts in a compressed tar.gz file containing:
Model weights/parameters
Any preprocessing code
Inference script (if using custom code)
Deployment Options
1. Using SageMaker Built-in Algorithms
If you're using a pre-trained model from SageMaker's model zoo:
python
from sagemaker import get_execution_role
from sagemaker.model import Model
role = get_execution_role()
model = Model(
image_uri='811284229777.dkr.ecr.us-east-1.amazonaws.com/image-classification:latest',
model_data='s3://your-bucket/model.tar.gz',
role=role
)
predictor = model.deploy(
initial_instance_count=1,
instance_type='ml.m5.xlarge'
)
2. Using Framework-Specific Deployments
For TensorFlow models:
python
from sagemaker.tensorflow import TensorFlowModel
tensorflow_model = TensorFlowModel(
model_data='s3://your-bucket/model.tar.gz',
role=role,
framework_version='2.11',
py_version='py39',
entry_point='inference.py' # Your custom inference script
)
predictor = tensorflow_model.deploy(
initial_instance_count=1,
instance_type='ml.g4dn.xlarge' # GPU instance for computer vision
)
import numpy as np
from PIL import Image
import requests
# Load and preprocess image
image = Image.open('test_image.jpg')
image_bytes = io.BytesIO()
image.save(image_bytes, format='PNG')
image_bytes = image_bytes.getvalue()
# Make prediction
response = predictor.predict(image_bytes)
print(response)
Best Practices
Instance Selection: Use GPU instances (ml.g4dn, ml.p3) for complex models, CPU instances (ml.m5, ml.c5) for lighter models
Model Optimization: Consider using SageMaker Neo to optimize your model for specific hardware
Batch Transform: For processing large image datasets, use SageMaker Batch Transform instead of real-time endpoints
Monitoring: Set up CloudWatch alarms for endpoint health and performance metrics
Cost Optimization: Use SageMaker Multi-Model Endpoints if deploying multiple models
Cleanup
Don't forget to delete resources when done:
python
predictor.delete_endpoint()
model.delete_model()
This approach provides a scalable, managed solution for deploying computer vision models with automatic scaling, monitoring, and high availability built in.