Структура папок приложения flask с компонентом машинного обучения - PullRequest
0 голосов
/ 19 февраля 2020

Я занимаюсь разработкой flask веб-приложения. Пользователь может ввести спецификации автомобиля и получать прогнозы цены автомобиля на основе модели машинного обучения.

Я следовал многим учебным пособиям о том, как создать веб-приложение, но я не понимаю, куда его ставить. конфигурации для компонента машинного обучения и как правильно структурировать код.

У меня есть следующая структура папок моего проекта:

├── webapp         
│   ├── app        
│       ├── static
│       ├── templates
│       ├── routes.py
│       ├── utils.py --> utils function that are used in 'routes.py'
│   ├── src
│       ├── ml_utils.py --> functions for machine learning component
│   ├── else stuff

в rout.py:

from flask import Flask, request, render_template
from sklearn.externals import joblib
import numpy as np
from app.utils import find_freshest_model, convert_to_float, process_features_info_for_option_html, create_features
from src.ml_utils import load_features_info

app = Flask(__name__)


@app.route('/')
def home():
    return render_template('index.html', car_type=option_values['car type'])


@app.route('/', methods=['POST'])
def predict():
    #order features in a correct way according to order in features_info
    features = create_features(request, features_info)
    prediction = model.predict(features)

    return render_template('index.html',
                           prediction_text='Your predicted car price is {} Euro'.format(prediction), quality=option_values['quality'])


if __name__ == '__main__':
    model_file = find_freshest_model() 
    features_info = load_features_info() # containts correct order of the features and categorization of features (numerical, categorical)
    option_values = process_features_info_for_option_html(features_info['features_dummy'])

    model = joblib.load(model_file)
    app.run(host='0.0.0.0', debug=True)

Задача и вопросы:
Я хочу подготовить свое приложение к производству и лучше структурировать его.

  1. Должен ли я ввести init .py следующий код?

  2. Относительно кода в if __name__ == '__main__':. Должен ли я создать класс modelConfigs, поместить его в models.py? В init.py я импортирую modelConfigs и инициализирую его routs.py.

models.py

from src.ml_utils import load_features_info
from sklearn.externals import joblib
from app.utils import find_freshest_model, process_features_info_for_option_html


class ModelConfigs:
    __tablename__ = 'modelConfigs'
    model = joblib.load(find_freshest_model())
    features_info = load_features_info()
    option_values = process_features_info_for_option_html(features_info['features_dummy'])

init. py :

from flask import Flask

app = Flask(__name__)

from app.models import ModelConfigs

model_config = ModelConfigs

from app import routes

rout.py:

from flask import request, render_template
import numpy as np
from app.utils import create_features
from app import app, model_config



@app.route('/')
def home():
    return render_template('index.html', car_type=option_values['car type'])


@app.route('/', methods=['POST'])
def predict():
    features = create_features(request, model_config.features_info)
    prediction = np.expm1(model_config.model.predict(features))    
    return render_template('index.html',
                           prediction_text='Your predicted car price is {} Euro'.format(prediction), quality=option_values['quality'])
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...