使用Django部署模型

上一篇把Django的开发环境准备好了, 这一篇我们来写程序将模型部署在Django专案并且可以提供endpoint可让使用者(client)传送一张手写图档到endpoint後取得推论後的结果, 也就是会回传这张图片是数字0-9的哪一个数字.

建立Django专案

  • 开启上一篇准备好的Django环境

    $cd ironman-workspace
    $source VENV/bin/activate
    
  • 建立专案
    专案名称为mnistinfernce

    $django-admin startproject mnistinfernce
    

    https://ithelp.ithome.com.tw/upload/images/20210923/20140792ARBCedlasy.png

撰写专案程序

接下来开启vs code, 我们开始来写程序
打开vs code之後会看到我们下列里面, 一个具有基本程序框架的开发环境
https://ithelp.ithome.com.tw/upload/images/20210923/20140792W8BBROTrQs.png

  • 修改core/views.py
    我们先来写第一支程序, 用来判断推论结果的程序, 请打开core/views.py, 加入下列内容:
from django.shortcuts import render
from rest_framework.decorators import api_view
from django.http.response import JsonResponse
from rest_framework import status

from PIL import Image
from fastai.vision.all import *

@api_view(['GET', 'POST', 'DELETE'])
def predict(request):  
    if request.method == 'POST':
        # Read the image uploaded by the curl command
        requested_img = request.FILES['file']

        img = PILImage.create(requested_img)
        
        learn_inf = load_learner("pretrained_model/export.pkl")
        pred = learn_inf.predict(img)

        # Get the digit
        result = int(pred[0])

    # Return the JSON response
    return JsonResponse({"digit": result}, status=status.HTTP_201_CREATED) 
  • 放置训练好的model
    我们在Day6 已使用fastai训练好手写辩识的model, model的名称为 export.pkl , 我们现在把这个model档放到django专案的 pretrained_model 这个目录, 如下图:
    https://ithelp.ithome.com.tw/upload/images/20210923/20140792fruU2X35Oc.png

  • 修改urls.py
    增加一个path指向views.py的 predict function

    from django.contrib import admin
    from django.urls import path
    from core.views import predict
    
    urlpatterns = [
      path('admin/', admin.site.urls),
      path('predict/', predict),
    ]
    
  • 修改 settings.py
    将这一行
    ALLOWED_HOSTS = []
    改为
    ALLOWED_HOSTS = ['*',]

    另外, 在INSTALLED_APPS 加入我们的app, 名称为 core

    INSTALLED_APPS = [
      'django.contrib.admin',
      'django.contrib.auth',
      'django.contrib.contenttypes',
      'django.contrib.sessions',
      'django.contrib.messages',
      'django.contrib.staticfiles',
      'rest_framework',
      'core'
    ]
    
  • 安装fastai package
    到这里我们可以试试看能不能将专案顺利跑起来, 但在跑之前, 我们忘了一件事: 我们还没有安装fastai与rest_framework这两个package. 我们现在就来安装. 回到建立django的console里面, 执行如下列指令:

    $cd ~/ironman-workspace/mnistinfernce
    $pip install fastai
    $pip install djangorestframework
    

    https://ithelp.ithome.com.tw/upload/images/20210923/20140792bmRZuwwUTo.png

    https://ithelp.ithome.com.tw/upload/images/20210923/20140792H9QxqFZwsT.png

  • 启动web server
    在console中执行下列指令

    $cd ~/ironman-workspace/mnistinfernce
    $python manage.py migrate
    $python manage.py runserver 0.0.0.0:8000
    

    web server启动後的console画面
    https://ithelp.ithome.com.tw/upload/images/20210923/20140792BBzZJxOyRu.png

到这里我们已经将模型部署好, 而且也成功建立endpoint可以让外部使用者存取这个endpoint後取得推论後的结果.

Client site环境

接下来我们来准备客户端的环境

  • 准备图片
    从github下载推论用的范例图档
    $git clone https://github.com/masonwu1762/mnist_inference_png.git
    $cd mnist_inference_png
    
  • 使用curl存取endpoint最得推论结果
    $curl -F 'file=@png/7.png' 127.0.0.1:8000/predict/
    
    回传的推论结果为数字7:
    https://ithelp.ithome.com.tw/upload/images/20210923/20140792vf9KnFZuaS.png

到这里我们就完成第一个范例的所有说明, 内容包含使用CNN训练出一个手写辨识的Model, 并且使用MLFlow将每次训练的parameter与参数记录起来, 再挑出比较准确的model执行部署, 使用Django部署模型并提供endpoint, 最後也使用client程序确认推论结果是正确的.


<<:  Day11回圈(Ⅰ)

>>:  #23 JS: HTML DOM Events - Part 1

Day28-介绍 Redux DevTools

这篇要介绍的是 Redux DevTools,是一个可以纪录及操作存在 Redux store 内的...

[Angular] Day8. Templates and Text interpolation

前几天大概讲完了 Angular 的 Component 的基本功能与介绍,在很多例子中可以看到在 ...

DAY1 自我介绍及任务规划

我是谁为何要参与 您好我是阿刘,是一名就读资讯管理的同学,之所以会想要参加这个挑战,是因为经历过了社...

【Vue】帮元件加上样式啦|修改 bootstrap 变数供全域样式共用 失败

将样式区分为全域样式/区域样式 全域样式:大多页面都会共用到的样式,reset & vari...

Day03:Set User Name(存放使用者名称)

全文同步於个人 Docusaurus Blog 在这一章中,主要处理下述两个问题: 初始进入页面的建...