用FastAPI部署深度学习模型

FastAPI 部署深度学习模型的方法

安装依赖

确保安装 FastAPI 和 Uvicorn:

bash 复制代码
pip install fastapi uvicorn

如果模型依赖其他库(如 PyTorch、TensorFlow),需一并安装:

bash 复制代码
pip install torch tensorflow
创建 FastAPI 应用

新建一个 Python 文件(如 main.py),初始化 FastAPI 应用:

python 复制代码
from fastapi import FastAPI
app = FastAPI()
加载模型

在应用启动时加载预训练模型。以 PyTorch 为例:

python 复制代码
import torch
from transformers import pipeline

model = pipeline("text-classification", model="distilbert-base-uncased-finetuned-sst-2-english")
定义预测接口

创建一个 POST 接口接收输入数据并返回预测结果:

python 复制代码
from pydantic import BaseModel

class InputText(BaseModel):
    text: str

@app.post("/predict")
def predict(input: InputText):
    prediction = model(input.text)
    return {"prediction": prediction}
运行服务

使用 Uvicorn 启动服务:

bash 复制代码
uvicorn main:app --reload

访问 http://127.0.0.1:8000/docs 可查看交互式 API 文档。

异步支持(可选)

对于高并发场景,可以使用异步方式加载模型:

python 复制代码
from fastapi import FastAPI
import asyncio

app = FastAPI()

async def load_model():
    return pipeline("text-classification", model="distilbert-base-uncased-finetuned-sst-2-english")

model = asyncio.run(load_model())
生产环境部署

使用 Gunicorn 管理多进程:

bash 复制代码
pip install gunicorn
gunicorn -w 4 -k uvicorn.workers.UvicornWorker main:app
Docker 容器化

创建 Dockerfile

dockerfile 复制代码
FROM python:3.9
WORKDIR /app
COPY requirements.txt .
RUN pip install -r requirements.txt
COPY . .
CMD ["gunicorn", "-w", "4", "-k", "uvicorn.workers.UvicornWorker", "main:app"]

构建并运行容器:

bash 复制代码
docker build -t model-api .
docker run -p 8000:8000 model-api
相关推荐
飞哥数智坊1 天前
我的“龙虾”罢工了!正好对比下GLM、MiniMax、Kimi 3家谁更香
人工智能
风象南1 天前
很多人说,AI 让技术平权了,小白也能乱杀老师傅 ?
人工智能·后端
董董灿是个攻城狮1 天前
大模型连载1:了解 Token
人工智能
RoyLin1 天前
沉睡三十年的标准:HTTP 402、生成式 UI 与智能体原生软件的时代
人工智能
needn1 天前
TRAE为什么要发布SOLO版本?
人工智能·ai编程
毅航1 天前
自然语言处理发展史:从规则、统计到深度学习
人工智能·后端
前端付豪1 天前
LangChain链 写一篇完美推文?用SequencialChain链接不同的组件
人工智能·python·langchain
ursazoo1 天前
写了一份 7000字指南,让 AI 帮我消化每天的信息流
人工智能·开源·github
曲幽1 天前
FastAPI实战:打造本地文生图接口,ollama+diffusers让AI绘画更听话
python·fastapi·web·cors·diffusers·lcm·ollama·dreamshaper8·txt2img
_志哥_1 天前
Superpowers 技术指南:让 AI 编程助手拥有超能力
人工智能·ai编程·测试