Where can i upload the pickle file on the webserver as when i upload the. pkl file in main directory it shows no file name or directory clf. Pkl

13 views
Skip to first unread message

Akash Banaulikar

unread,
Apr 25, 2020, 5:32:25 AM4/25/20
to PULUG
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)

```
This error is thrown
```

[Sat Apr 25 07:49:59.362282 2020] [wsgi:error] [pid 2228] [client 157.47.60.102:51154] mod_wsgi (pid=2228): Target WSGI script '/var/www/na/na.wsgi' cannot be loaded as Python module., referer: http://161.35.14.65/
[Sat Apr 25 07:49:59.362366 2020] [wsgi:error] [pid 2228] [client 157.47.60.102:51154] mod_wsgi (pid=2228): Exception occurred processing WSGI script '/var/www/na/na.wsgi'., referer: http://161.35.14.65/
[Sat Apr 25 07:49:59.362773 2020] [wsgi:error] [pid 2228] [client 157.47.60.102:51154] Traceback (most recent call last):, referer: http://161.35.14.65/
[Sat Apr 25 07:49:59.362812 2020] [wsgi:error] [pid 2228] [client 157.47.60.102:51154] File "/var/www/na/na.wsgi", line 7, in <module>, referer: http://161.35.14.65/
[Sat Apr 25 07:49:59.362819 2020] [wsgi:error] [pid 2228] [client 157.47.60.102:51154] from na import app as application, referer: http://161.35.14.65/
[Sat Apr 25 07:49:59.362827 2020] [wsgi:error] [pid 2228] [client 157.47.60.102:51154] File "/var/www/na/na/__init__.py", line 8, in <module>, referer: http://161.35.14.65/
[Sat Apr 25 07:49:59.362832 2020] [wsgi:error] [pid 2228] [client 157.47.60.102:51154] file = open('model.pkl', 'rb'), referer: http://161.35.14.65/
[Sat Apr 25 07:49:59.362855 2020] [wsgi:error] [pid 2228] [client 157.47.60.102:51154] FileNotFoundError: [Errno 2] No such file or directory: 'model.pkl', referer: http://161.35.14.65/

```
My wsgi file is saved as na. wsgi in directory
```
var/www/na
```
Code for wsgi is
```

#!/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




code.PNG

Akash Banaulikar

unread,
Apr 26, 2020, 11:46:54 PM4/26/20
to PULUG
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.
Reply all
Reply to author
Forward
0 new messages