{"id":10951,"date":"2021-11-16T10:00:00","date_gmt":"2021-11-16T01:00:00","guid":{"rendered":"https:\/\/www.gigas-jp.com\/appnews\/?p=10951"},"modified":"2021-11-15T18:52:07","modified_gmt":"2021-11-15T09:52:07","slug":"deploying-a-machine-learning-model-into-a-web-application-with-django","status":"publish","type":"post","link":"https:\/\/www.gigas-jp.com\/appnews\/archives\/10951","title":{"rendered":"Deploying a machine learning model into a web application with Django"},"content":{"rendered":"\n<p><font><font>Today, I would like to sh<\/font><font>are about deploying a machine learning model into a web application using Django<\/font>.<font><\/font><\/p>\n\n\n\n<p><em><strong>Note : In this article, I will focus only how to deploy a trained machine learning model in a web application with django rather than about the steps of machine learning processes.<\/strong><\/em><\/p>\n\n\n\n<p>First, I will create a simple ML model using multinomial Naive Bayes Classifier with the spam text dataset (spam.csv). The following code is to create spam text detection model.<\/p>\n\n\n\n<p>First, import the necessary libraries.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import pandas as pd\nimport numpy as np\nfrom sklearn.feature_extraction.text import CountVectorizer\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.naive_bayes import MultinomialNB<\/code><\/pre>\n\n\n\n<p><font><\/p>\n\n\n\n<hr class=\"wp-block-separator\" \/>\n\n\n\n<p><font><\/p>\n\n\n\n<p><font>And load dataset file with pandas.<\/font><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>data = pd.read_csv(\"D:\\Python\\datasets\\spam.csv\", encoding= 'latin-1')\ndata.head()\nThen extract features and labels using CountVectorizer.\ndata = data&#091;&#091;\"class\", \"message\"]]\nx = np.array(data&#091;\"message\"])\ny = np.array(data&#091;\"class\"])\ncv = CountVectorizer()\nX = cv.fit_transform(x) # Fit the Data\n<\/code><\/pre>\n\n\n\n<p><font><\/p>\n\n\n\n<hr class=\"wp-block-separator\" \/>\n\n\n\n<p><font><\/p>\n\n\n\n<p><font>let\u2019s split this dataset into training and test sets and train the model to detect spam messages<\/p>\n\n\n\n<p><font><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.33, random_state=42)\nclf = MultinomialNB()\nclf.fit(X_train,y_train)\n<\/code><\/pre>\n\n\n\n<p><font><\/p>\n\n\n\n<hr class=\"wp-block-separator\" \/>\n\n\n\n<p><font><\/p>\n\n\n\n<p><font>And save the model.<\/p>\n\n\n\n<p><font><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import pickle\npickle.dump(clf,open(\"spamdetection_model.sav\", \"wb\"))\n<\/code><\/pre>\n\n\n\n<p><font><\/p>\n\n\n\n<p><font>This will output spamdetection_model.sav file. This file will be used in the web app later.<\/p>\n\n\n\n<p><font><\/p>\n\n\n\n<hr class=\"wp-block-separator\" \/>\n\n\n\n<p><font><font><\/font><\/p>\n\n\n\n<p>So, Let\u2019s start to develop a Django web app.<\/p>\n\n\n\n<p><strong>mkdir Spamdetection<\/strong> &#8211; First make a directory named \/<strong>Spamdetection<\/strong> for the Django project.<\/p>\n\n\n\n<p><strong>cd Spamdetection<\/strong> \u2013 Change directory into the folder created<\/p>\n\n\n\n<p>And to create a Django project, it is needed to run the following command.<\/p>\n\n\n\n<p><strong>D:\/Spamdetection&gt;django-admin startproject spamdetectapp<\/strong><\/p>\n\n\n\n<p>This command create a new directory named spamdetectapp.<\/p>\n\n\n\n<figure class=\"wp-block-image size-full is-resized\"><img loading=\"lazy\" src=\"https:\/\/www.gigas-jp.com\/appnews\/wp-content\/uploads\/sites\/4\/2021\/11\/blog1.png\" alt=\"\" class=\"wp-image-10955\" width=\"237\" height=\"314\" \/><figcaption><font><\/figcaption><\/figure>\n\n\n\n<p><font><\/p>\n\n\n\n<p>To run the djangoapp, the following command is typed in the spamdetectapp directory created.<\/p>\n\n\n\n<p><strong>python manage.py runserver<\/strong><\/p>\n\n\n\n<p>Copy and open the link <a href=\"http:\/\/127.0.0.1:8000\/\">http:\/\/127.0.0.1:8000\/<\/a> in a web browser. You should see Django Home page.<\/p>\n\n\n\n<p>Then create <strong>views.py<\/strong> inside the same folder to work for getting inputs from users. In the main project folder, create a new folder named \u2018templates\u2019 to work with html files and new folders named \u2018<strong>datasets\u2019<\/strong> and \u2018<strong>mlmodels\u2019<\/strong>. Then move <strong>spam.csv<\/strong> dataset file into the datasets folder and <strong>spamdetection_model.sav<\/strong> file into the <strong>mlmodels<\/strong> folder.<\/p>\n\n\n\n<p><font>Now our project folder will be like that.<\/p>\n\n\n\n<figure class=\"wp-block-image size-full\"><img loading=\"lazy\" width=\"245\" height=\"375\" src=\"https:\/\/www.gigas-jp.com\/appnews\/wp-content\/uploads\/sites\/4\/2021\/11\/image-1.png\" alt=\"\" class=\"wp-image-10957\" \/><figcaption><font><\/figcaption><\/figure>\n\n\n\n<p><font>Now open settings.py and add <strong>\u2018templates<\/strong>\u2019 to register in <strong>\u2018DIRS\u2019<\/strong> list in the <strong>\u2018TEMPLATES<\/strong>\u2019 list.<\/p>\n\n\n\n<figure class=\"wp-block-image size-full\"><img loading=\"lazy\" width=\"587\" height=\"304\" src=\"https:\/\/www.gigas-jp.com\/appnews\/wp-content\/uploads\/sites\/4\/2021\/11\/image-2.png\" alt=\"\" class=\"wp-image-10958\" \/><\/figure>\n\n\n\n<p><font><\/p>\n\n\n\n<hr class=\"wp-block-separator\" \/>\n\n\n\n<p><font><\/p>\n\n\n\n<p><font>Now inside the urls.py file, add the following codes to configure the urls.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>from django.contrib import admin\nfrom django.urls import path\n\nfrom spamdetectapp import views # add this new line to import views files\n\nurlpatterns = &#091;\n    path('admin\/', admin.site.urls),\n    \n    # add these new two lines to configure for home page and result page\n    path('', views.home, name='home'), \n    path('result\/', views.result, name='result'),\n]\n<\/code><\/pre>\n\n\n\n<p><font><\/p>\n\n\n\n<hr class=\"wp-block-separator\" \/>\n\n\n\n<p><font><\/p>\n\n\n\n<p><font>And define two functions for home and result in views.py. And create a libs.py in mlmodels folder. In libs.py, we will define a <strong>getResult()<\/strong> function to get results from model prediction and use it in views.py.<\/p>\n\n\n\n<p><font><\/p>\n\n\n\n<p><strong><font>v<\/font><font>i<\/font><font>e<\/font><font>w<\/font><font>s<\/font><font>.<\/font><font>p<\/font>y<\/strong><font><font><\/font><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>from django.shortcuts import render\nfrom mlmodels.libs import getResult\n\n# for default home page view\ndef home(request):    \n    return render(request, 'index.html')\n\n# for result page view\ndef result(request):\t\n    message = request.POST&#091;'message']\n    result = getResult(message)\n    return render(request, 'result.html', {'result':result , 'message':message})\n<\/code><\/pre>\n\n\n\n<p><font><\/p>\n\n\n\n<hr class=\"wp-block-separator\" \/>\n\n\n\n<p><font><\/p>\n\n\n\n<p><font><strong>libs.py<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import pandas as pd\nimport numpy as np\nfrom sklearn.feature_extraction.text import CountVectorizer\nfrom sklearn.model_selection import train_test_split\n\ndef getResult(message):\n    import pickle\n    data = pd.read_csv(\"D:\\Spamdetection\\spamdetectapp\\datasets\\spam.csv\", encoding= 'latin-1')\n    data.head()\n\n    data = data&#091;&#091;\"class\", \"message\"]]\n    x = np.array(data&#091;\"message\"])\n    y = np.array(data&#091;\"class\"])\n    cv = CountVectorizer()\n    X = cv.fit_transform(x) # Fit the Data\n\n    model= pickle.load(open(\"D:\\Spamdetection\\spamdetectapp\\mlmodels\\spamdetection_model.sav\", \"rb\"))\n\n    data = cv.transform(&#091;message]).toarray()    \n    prediction = model.predict(data)\n    if prediction == 'ham':\n        return 'OK'\n    elif prediction == 'spam':\n        return 'SPAM'\n<\/code><\/pre>\n\n\n\n<p><font><\/p>\n\n\n\n<hr class=\"wp-block-separator\" \/>\n\n\n\n<p><font><\/p>\n\n\n\n<p><font>Now we have done for backend. So, for frontend pages, let\u2019s create index.html and result.html in templates folder.<\/p>\n\n\n\n<p><font><strong>Index.html<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>&lt;!DOCTYPE html&gt;\n&lt;html lang=\"en\"&gt;\n&lt;head&gt;\n    &lt;meta charset=\"UTF-8\"&gt;\n    &lt;meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\"&gt;\n    &lt;meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\"&gt;\n    &lt;title&gt;Spam Text Detection&lt;\/title&gt;\n&lt;\/head&gt;\n&lt;body&gt;\n    &lt;h1&gt;Spam Text detection&lt;\/h1&gt;\n    &lt;form action=\"{% url 'result' %}\" method=\"post\"&gt;\n        {% csrf_token %}\n        &lt;p&gt;Message:&lt;\/p&gt;\n        &lt;input type=\"text\" name=\"message\"&gt;\n        &lt;br&gt;\n        &lt;br&gt;\n        &lt;input type=\"submit\" value='Predict\u2019&gt;\n    &lt;\/form&gt;\n&lt;\/body&gt;\n\n&lt;\/html&gt;\n<\/code><\/pre>\n\n\n\n<p><font><\/p>\n\n\n\n<hr class=\"wp-block-separator\" \/>\n\n\n\n<p><font><\/p>\n\n\n\n<p><font><strong>result.html<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>&lt;!DOCTYPE html&gt;\n&lt;html lang=\"en\"&gt;\n&lt;head&gt;\n    &lt;meta charset=\"UTF-8\"&gt;\n    &lt;meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\"&gt;\n    &lt;meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\"&gt;\n    &lt;title&gt;Spam Text Detection&lt;\/title&gt;\n&lt;\/head&gt;\n&lt;body&gt;\n    &lt;h1&gt;Prediction&lt;\/h1&gt;\n    The Message&#091;{{message}}] is &lt;b&gt;{{result}}&lt;\/b&gt;&lt;\/body&gt;\n&lt;\/html&gt;\n<\/code><\/pre>\n\n\n\n<p><font><\/p>\n\n\n\n<hr class=\"wp-block-separator\" \/>\n\n\n\n<p><font><\/p>\n\n\n\n<p><font><\/p>\n\n\n\n<p>Now all is done. Once the above steps are completed, to stop and restart the server press Ctrl+C and run this command:<\/p>\n\n\n\n<p>D:\/Spamdetection\/spamdetectapp&gt;<strong> python manage.py runserver<\/strong><\/p>\n\n\n\n<p>And reopen the link in the browser. You will see the index home page.<\/p>\n\n\n\n<figure class=\"wp-block-image size-full\"><img loading=\"lazy\" width=\"314\" height=\"233\" src=\"https:\/\/www.gigas-jp.com\/appnews\/wp-content\/uploads\/sites\/4\/2021\/11\/image-3.png\" alt=\"\" class=\"wp-image-10960\" \/><\/figure>\n\n\n\n<p><font><\/p>\n\n\n\n<p>Let\u2019s test with some messages.<\/p>\n\n\n\n<p>When message is \u2018Hello, How are you?\u2019, the result is as follow.<\/p>\n\n\n\n<figure class=\"wp-block-image size-full\"><img loading=\"lazy\" width=\"326\" height=\"159\" src=\"https:\/\/www.gigas-jp.com\/appnews\/wp-content\/uploads\/sites\/4\/2021\/11\/image-4.png\" alt=\"\" class=\"wp-image-10961\" \/><\/figure>\n\n\n\n<p><font>When the message is \u2018You got $1000 prize at our shop.\u2019, the result is as follow.<\/p>\n\n\n\n<figure class=\"wp-block-image size-full\"><img loading=\"lazy\" width=\"407\" height=\"167\" src=\"https:\/\/www.gigas-jp.com\/appnews\/wp-content\/uploads\/sites\/4\/2021\/11\/image-5.png\" alt=\"\" class=\"wp-image-10962\" \/><\/figure>\n\n\n\n<p>Hope you all enjoyed about this article.<\/p>\n\n\n\n<p>By Asahi<\/p>\n\n\n\n<p><font><\/p>\n<div class='wp_social_bookmarking_light'>\n            <div class=\"wsbl_google_plus_one\"><g:plusone size=\"medium\" annotation=\"none\" href=\"https:\/\/www.gigas-jp.com\/appnews\/archives\/10951\" ><\/g:plusone><\/div>\n            <div class=\"wsbl_hatena_button\"><a href=\"\/\/b.hatena.ne.jp\/entry\/https:\/\/www.gigas-jp.com\/appnews\/archives\/10951\" class=\"hatena-bookmark-button\" data-hatena-bookmark-title=\"Deploying a machine learning model into a web application with Django\" data-hatena-bookmark-layout=\"standard\" title=\"\u3053\u306e\u30a8\u30f3\u30c8\u30ea\u30fc\u3092\u306f\u3066\u306a\u30d6\u30c3\u30af\u30de\u30fc\u30af\u306b\u8ffd\u52a0\"> <img src=\"\/\/b.hatena.ne.jp\/images\/entry-button\/button-only@2x.png\" alt=\"\u3053\u306e\u30a8\u30f3\u30c8\u30ea\u30fc\u3092\u306f\u3066\u306a\u30d6\u30c3\u30af\u30de\u30fc\u30af\u306b\u8ffd\u52a0\" width=\"20\" height=\"20\" style=\"border: none;\" \/><\/a><script type=\"text\/javascript\" src=\"\/\/b.hatena.ne.jp\/js\/bookmark_button.js\" charset=\"utf-8\" async=\"async\"><\/script><\/div>\n            <div class=\"wsbl_twitter\"><a href=\"https:\/\/twitter.com\/share\" class=\"twitter-share-button\" data-url=\"https:\/\/www.gigas-jp.com\/appnews\/archives\/10951\" data-text=\"Deploying a machine learning model into a web application with Django\" data-via=\"GIGASJAPAN_APPS\" data-lang=\"ja\">Tweet<\/a><\/div>\n            <div class=\"wsbl_facebook_like\"><div id=\"fb-root\"><\/div><fb:like href=\"https:\/\/www.gigas-jp.com\/appnews\/archives\/10951\" layout=\"button_count\" action=\"like\" width=\"100\" share=\"false\" show_faces=\"false\" ><\/fb:like><\/div>\n            <div class=\"wsbl_facebook_send\"><div id=\"fb-root\"><\/div><fb:send href=\"https:\/\/www.gigas-jp.com\/appnews\/archives\/10951\" colorscheme=\"light\" ><\/fb:send><\/div>\n    <\/div>\n<br class='wp_social_bookmarking_light_clear' \/>\n","protected":false},"excerpt":{"rendered":"<p>Today, I would like to share about deploying a machine learning model into a web application using Django. Not [&hellip;]<\/p>\n","protected":false},"author":20,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":[],"categories":[100,35],"tags":[],"acf":[],"_links":{"self":[{"href":"https:\/\/www.gigas-jp.com\/appnews\/wp-json\/wp\/v2\/posts\/10951"}],"collection":[{"href":"https:\/\/www.gigas-jp.com\/appnews\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.gigas-jp.com\/appnews\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.gigas-jp.com\/appnews\/wp-json\/wp\/v2\/users\/20"}],"replies":[{"embeddable":true,"href":"https:\/\/www.gigas-jp.com\/appnews\/wp-json\/wp\/v2\/comments?post=10951"}],"version-history":[{"count":22,"href":"https:\/\/www.gigas-jp.com\/appnews\/wp-json\/wp\/v2\/posts\/10951\/revisions"}],"predecessor-version":[{"id":10979,"href":"https:\/\/www.gigas-jp.com\/appnews\/wp-json\/wp\/v2\/posts\/10951\/revisions\/10979"}],"wp:attachment":[{"href":"https:\/\/www.gigas-jp.com\/appnews\/wp-json\/wp\/v2\/media?parent=10951"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.gigas-jp.com\/appnews\/wp-json\/wp\/v2\/categories?post=10951"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.gigas-jp.com\/appnews\/wp-json\/wp\/v2\/tags?post=10951"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}