I am trying to deploy a machine learning model on a web server of digital ocean which predict the probability of disease based on its symptoms.
For this i am using ubuntu 18.04 console and flask.
My working directory is
var/www/na/na
All the files are uploaded in above directory. Content of directory will be posted below.
Everything works fine i successfully hosted my website.
This is my flask code
from flask import Flask,request,render_template,redirect,url_for,session,logging,flash
from flask_sqlalchemy import SQLAlchemy
import pymysql
pymysql.install_as_MySQLdb()
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://root:@localhost/naksh_main'
db = SQLAlchemy(app)
# creating content in database
class Naksh_main_tb(db.Model):
sno = db.Column(db.Integer, primary_key=True)
datetime = db.Column(db.String(12), unique=False)
email = db.Column(db.String(20), unique=True, nullable=False)
password = db.Column(db.String(20), unique=True, nullable=False)
@app.route('/')
def index():
return render_template('index.html')
@app.route('/register',methods=['GET','POST'])
def register():
if(request.method=='POST'):
"fetch entry from database"
# u name is just a variable which is storing name content of form
uname=request.form.get('uname')
passw=request.form.get('passw')
existing_entry=Naksh_main_tb.query.filter_by(email=uname).first()
if existing_entry:
flash('Email already exist')
return redirect(url_for("register"))
# to add entry
# email from database will store uname variable and password from database will store passw variable
new_entry=Naksh_main_tb(email=uname,password=passw)
db.session.add(new_entry)
db.session.commit()
return redirect(url_for("login"))
return render_template("register.html")
@app.route('/login',methods=['GET','POST'])
def login():
if(request.method=='POST'):
"fetch entry from database"
louname=request.form.get('uname')
lopassw=request.form.get('passw')
login=Naksh_main_tb.query.filter_by(email=louname,password=lopassw).first()
if login is not None:
# flash('pleas check')
return render_template('nakshoverview.html')
# else:
# return redirect(url_for("login"))
return render_template("login.html")
@app.route('/',methods=["GET","POST"])
def hello_world():
if request.method == "POST":
print(request.form)
# mydict will access the form using name
mydict=request.form
fever=int(mydict['fever'])
pain=int(mydict['pain'])
runnynose=int(mydict['runnynose'])
diffbreath=int(mydict['diffbreath'])
# now here we can use names like fever pain inplace of values
probability=mp.predict_proba([[fever,pain,age,runnynose,diffbreath]])
# model.predictproba is used to predict probability
prob=probability[0][1]
# to select the probabilty using index 1
print(prob)
#this will return inf value and display it in show.html
# return redirect(url_for('index'))
return render_template('show.html',inf=round(prob*100))
return render_template('index.html')
if __name__== "__init__":
db.create_all()
app.run(debug=True)
Above code works fine
But when i try to deploy my machine learning model which is saved using a pickle file it throws an error.
Problem occurs when i try to open clf. pkl file
from flask import Flask,request,render_template,redirect,url_for,session,logging,flash
from flask_sqlalchemy import SQLAlchemy
import pymysql
pymysql.install_as_MySQLdb()
app = Flask(__name__)
import pickle
# open a file, where you stored the pickled data
file = open('model.pkl', 'rb')
# dump load model information to that file
mp = pickle.load(file)
# close the file
file.close()
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://root:@localhost/naksh_main'
db = SQLAlchemy(app)
# creating content in database
class Naksh_main_tb(db.Model):
sno = db.Column(db.Integer, primary_key=True)
datetime = db.Column(db.String(12), unique=False)
email = db.Column(db.String(20), unique=True, nullable=False)
password = db.Column(db.String(20), unique=True, nullable=False)
@app.route('/')
def index():
return render_template('index.html')
@app.route('/register',methods=['GET','POST'])
def register():
if(request.method=='POST'):
"fetch entry from database"
# u name is just a variable which is storing name content of form
uname=request.form.get('uname')
passw=request.form.get('passw')
existing_entry=Naksh_main_tb.query.filter_by(email=uname).first()
if existing_entry:
flash('Email already exist')
return redirect(url_for("register"))
# to add entry
# email from database will store uname variable and password from database will store passw variable
new_entry=Naksh_main_tb(email=uname,password=passw)
db.session.add(new_entry)
db.session.commit()
return redirect(url_for("login"))
return render_template("register.html")
@app.route('/login',methods=['GET','POST'])
def login():
if(request.method=='POST'):
"fetch entry from database"
louname=request.form.get('uname')
lopassw=request.form.get('passw')
login=Naksh_main_tb.query.filter_by(email=louname,password=lopassw).first()
if login is not None:
# flash('pleas check')
return render_template('nakshoverview.html')
# else:
# return redirect(url_for("login"))
return render_template("login.html")
@app.route('/',methods=["GET","POST"])
def hello_world():
if request.method == "POST":
print(request.form)
# mydict will access the form using name
mydict=request.form
fever=int(mydict['fever'])
pain=int(mydict['pain'])
runnynose=int(mydict['runnynose'])
diffbreath=int(mydict['diffbreath'])
# now here we can use names like fever pain inplace of values
probability=mp.predict_proba([[fever,pain,age,runnynose,diffbreath]])
prob=probability[0][1]
# to select the probabilty using index 1
print(prob)
#this will return inf value and display it in show.html
# return redirect(url_for('index'))
return render_template('show.html',inf=round(prob*100))
return render_template('index.html')
if __name__== "__init__":
db.create_all()
app.run(debug=True)
#!/usr/bin/python3
import sys
import logging
logging.basicConfig(stream=sys.stderr)
sys.path.insert(0,"/var/www/na/")
from na import app as application
application.secret_key = 'Add-secret'
Machine learning code
import pandas as pd
import numpy as np
import pickle
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
df=pd.read_csv('covidnew.csv')
train_set,test_set=train_test_split(df,test_size=0.2,random_state=42)
# this will print length of test set and train set
print("test data is",len(test_set))
print("train data is",len(train_set))
# for training:seperating features and labels
x_train_feature=train_set.drop(["prob"],axis=1)
y_train_label=train_set["prob"].copy()
# to convert to array
x_train_feature.to_numpy()
y_train_label.to_numpy()
# for testing:seperating features and labels
x_test_feature=test_set.drop(["prob"],axis=1)
y_test_label=test_set["prob"].copy()
x_test_feature.to_numpy()
y_test_label.to_numpy()
# logistic regression
clf=LogisticRegression()
# model=DecisionTreeRegressor()
# model=RandomForestRegressor()
# fit function takes label and features
clf.fit(x_train_feature,y_train_label)
# open a file, where you ant to store the data
file = open('model.pkl', 'wb')
# dump model information to that file
pickle.dump(clf, file)
file.close()
When i run this code using python3 na.py it creates an model. pkl file but i am not able to load this file in my init.py
I am trying to deploy a machine learning model on a web server of digital ocean which predict the probability of disease based on its symptoms. For this i am using ubuntu 18.04 console and flask. My working directory is
All the files are uploaded in above directory. Content of directory will be posted below. Everything works fine i successfully hosted my website. This is my flask code
Above code works fine But when i try to deploy my machine learning model which is saved using a pickle file it throws an error. Problem occurs when i try to open clf. pkl file
This error is thrown
My wsgi file is saved as na. wsgi in directory
Code for wsgi is
Machine learning code
When i run this code using python3 na.py it creates an model. pkl file but i am not able to load this file in my init.py