Я пытаюсь развернуть модель машинного обучения на веб-сервере цифрового океана, который прогнозирует вероятность заболевания на основе его симптомов. Для этого я использую консоль Ubuntu 18.04 и flask. Мой рабочий каталог
var/www/na/na
Все файлы загружены в вышеуказанный каталог. Содержание каталога будет опубликовано ниже. Все отлично работает, я успешно разместил свой сайт. Это мой flask код
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)
Приведенный выше код работает нормально. Но когда я пытаюсь развернуть модель машинного обучения, сохраненную с использованием файла маринованного файла, выдается ошибка. Проблема возникает, когда я пытаюсь открыть clf. файл pkl
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)
Выдается эта ошибка
[wsgi:error] mod_wsgi (pid=2228): Target WSGI script '/var/www/na/na.wsgi' cannot be loaded as Python module., referer: http://161.35.14.65/
[wsgi:error]mod_wsgi (pid=2228): Exception occurred processing WSGI script '/var/www/na/na.wsgi'., referer: http://161.35.14.65/
[wsgi:error]Traceback (most recent call last):, referer: http://161.35.14.65/
[wsgi:error] File "/var/www/na/na.wsgi", line 7, in <module>, referer: http://161.35.14.65/
[wsgi:error]from na import app as application, referer: http://161.35.14.65/
[wsgi:error]File "/var/www/na/na/__init__.py", line 8, in <module>, referer: http://161.35.14.65/
[wsgi:error]file = open('model.pkl', 'rb'), referer: http://161.35.14.65/
[wsgi:error] [pid 2228]FileNotFoundError: [Errno 2] No such file or directory: 'model.pkl', referer: http://161.35.14.65/
Мой файл wsgi сохраняется как na. wsgi в каталоге
var/www/na
Код для wsgi
#!/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'
Когда я запускаю этот код с помощью python3 na.py, он создает модель. файл pkl, но я не могу загрузить этот файл в мой __init__.py
![enter image description here](https://i.stack.imgur.com/RCOR2.png)
Это вывод, если я не пытаюсь загрузить маринад файл ![enter image description here](https://i.stack.imgur.com/lnF6F.jpg)