惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

有赞技术团队
有赞技术团队
G
Google Developers Blog
T
Tailwind CSS Blog
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
人人都是产品经理
人人都是产品经理
J
Java Code Geeks
P
Proofpoint News Feed
V
Visual Studio Blog
爱范儿
爱范儿
The Cloudflare Blog
博客园 - 叶小钗
V
V2EX
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
M
MIT News - Artificial intelligence
Microsoft Security Blog
Microsoft Security Blog
博客园 - 聂微东
H
Help Net Security
B
Blog
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
博客园 - 【当耐特】
量子位
宝玉的分享
宝玉的分享
WordPress大学
WordPress大学
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant
How to Deploy Your ML Model to AWS (Step-by-Step Guide)
Shrestha Pandey · 2026-06-22 · via DEV Community
Cover image for How to Deploy Your ML Model to AWS (Step-by-Step Guide)

Shrestha Pandey

I've trained more ML models than I've deployed. There's something comforting about the local loop—model.fit()model.evaluate(), hitting 94% accuracy, then staring at the screen wondering, "Okay, how do I make this actually useful?"

If you're stuck there right now, this guide will help.

Note: I wrote this based on AWS documentation and standard SageMaker patterns. If you try it, drop a comment about what worked (or broke).

What You Need Before Starting

  • AWS account with SageMaker enabled
  • A trained model saved as model.pkl (or .joblib)
  • requirements.txt with your dependencies
  • Python 3.8+ installed
  • AWS CLI configured (aws configure)

Step 1: Save Your Model

import joblib
joblib.dump(model, 'model.pkl')

Create a requirements.txt file:

sklearn==1.2.0
pandas==1.5.0
numpy==1.23.0`

Keep both files in the same folder.

Step 2: Upload to S3

import boto3

s3 = boto3.client('s3')

bucket_name = 'my-unique-ml-bucket-12345'  # Make this unique
s3.create_bucket(Bucket=bucket_name, CreateBucketConfiguration={
    'LocationConstraint': 'us-east-1'
})

s3.upload_file('model.pkl', bucket_name, 'models/model.pkl')
s3.upload_file('requirements.txt', bucket_name, 'models/requirements.txt')

model_s3_path = f's3://{bucket_name}/models/model.pkl'

Step 3: Write Your Inference Script

Save this as inference.py:

import json
import joblib
import numpy as np
import os

model = None

def model_fn(model_dir):
    return joblib.load(os.path.join(model_dir, 'model.pkl'))

def input_fn(input_data, content_type):
    if content_type == 'application/json':
        data = json.loads(input_data)
        return np.array(data['features'])
    raise ValueError(f"Unsupported content type: {content_type}")

def predict_fn(input_data, model):
    return model.predict(input_data)

def output_fn(prediction, content_type):
    return json.dumps({'predictions': prediction.tolist()})

These four functions are what SageMaker calls when someone hits your endpoint.

Step 4: Deploy Using Python SDK

Run this in a Python script:

from sagemaker.sklearn.model import SKLearnModel
from sagemaker import get_execution_role

sklearn_model = SKLearnModel(
    model_data=model_s3_path,
    role=get_execution_role(),
    instance_type='ml.m5.large',
    entry_point='inference.py',
    py_version='py3'
)

sklearn_model.deploy(
    initial_instance_count=1,
    instance_type='ml.m5.large',
    endpoint_name='my-model-endpoint'
)

This takes 5–10 minutes. You'll see Creating → In Service.

Step 5: Test Your Endpoint

import boto3
import json

runtime = boto3.client('sagemaker-runtime')

response = runtime.invoke_endpoint(
    EndpointName='my-model-endpoint',
    ContentType='application/json',
    Body=json.dumps({'features': [[5.1, 3.5, 1.4, 0.2]]})
)

result = json.loads(response['Body'].read().decode())
print(result)

If you see {'predictions': [...]}, it worked.

Step 6: Clean Up

Endpoints cost money even when idle:

aws sagemaker delete-endpoint --endpoint-name my-model-endpoint
aws sagemaker delete-endpoint-config --endpoint-config-name my-model-endpoint

Common Errors (And Fixes)

Error Fix
NoCredentialsError Run aws configure again
InvalidRoleException IAM role needs S3 + SageMaker permissions
ModelError Check inference.py for missing imports
Endpoint stuck on Creating Wait 5–10 more minutes

Your IAM role needs:

  • s3:GetObjects3:PutObject
  • sagemaker:CreateModelsagemaker:CreateEndpoint

Cost Breakdown

Resource Cost
ml.m5.large ~$0.20/hour (~$6/month if 24/7)
S3 storage ~$0.02/GB/month

Delete when not using. I've seen $50 surprises from idle endpoints.

Verify This Before You Trust It

If you're following this, check:

  1. AWS SDK version — Run pip show boto3 sagemaker
  2. IAM role permissions — Biggest blocker is usually missing permissions
  3. Region mismatch — S3 bucket region must match SageMaker region
  4. Inference.py imports — Make sure osjoblibnumpy are installed

If something breaks, comment below with the error. I'll update this guide.

Final Thoughts

Deploying ML feels intimidating until you do it once. SageMaker handles most of the complexity. You just upload your model to S3, point SageMaker at it, and deploy.

I've trained models that sat on my laptop for months because I didn't know how to deploy them. Now I tell people: "Just run this script, it's not that hard."


If you're building something with this, drop a comment. I love seeing what people deploy.