コード例 #1
0
def evaluate_ml_baseline(pkl_path,
                         eval_set_name,
                         use_eiz=True,
                         demographic_features=False,
                         ei_extraction_method=None):
    '''
    Evaluate the a stored ML model on a set.
    :param pkl_path: The path of the trained model to evaluate.
    :param eval_set_name: The name of the set to evaluate on.
    :param use_eiz: Whether to use EIZ or raw EI scores
    :param demographic_features: Whether to include demographic features.
    :param ei_extraction_method: The method for extracting EI scores from records. Can use original scores or recompute.
    :return: Probabilities of NMD for each of the val set patients according to the trained model.
    '''
    additional_features = ['Age', 'Sex', 'BMI'] if demographic_features else []
    from pycaret.classification import load_model
    pipeline, model = load_model(pkl_path)

    if not ei_extraction_method:
        ei_extraction_method = get_original_scores

    val_set = obtain_feature_rep_ml_experiment(
        eval_set_name,
        use_eiz=use_eiz,
        ei_extraction_method=ei_extraction_method,
        additional_features=additional_features)
    val_set['Class'] = val_set['Class'].replace({'no NMD': 0, 'NMD': 1})
    X_test = val_set.drop(columns='Class')
    transformed = pipeline.transform(X_test)
    proba = model.predict_proba(transformed)[:, 1]
    return proba
コード例 #2
0
def update_output(list_of_contents, list_of_names, list_of_dates):
    model = load_model('random_forest')
    if list_of_contents is not None:
        children = [
            parse_contents(c, n, d, model, predict_model)
            for c, n, d in zip(list_of_contents, list_of_names, list_of_dates)
        ]
        return children
    else:
        return ''
コード例 #3
0
from flask import Flask, request, url_for, redirect, render_template, jsonify
from pycaret.classification import load_model, predict_model
import pandas as pd
import pickle
import numpy as np

app = Flask(__name__)

model = load_model('wine_model')
cols = [
    'fixed acidity', 'volatile acidity', 'citric acid', 'residual sugar',
    'chlorides', 'free sulfur dioxide', 'total sulfur dioxide', 'density',
    'pH', 'sulphates', 'alcohol'
]


# render default webpage
@app.route('/')
def home():
    return render_template("home.html")


# when the post method detect, predict value
@app.route('/predict', methods=['POST'])
def predict():
    int_features = [x for x in request.form.values()]
    final = np.array(int_features)
    data_unseen = pd.DataFrame([final], columns=cols)
    prediction = predict_model(model, data=data_unseen, round=3)
    prediction = int(prediction.Label[0])
    return render_template(
コード例 #4
0
from pycaret.classification import load_model, predict_model
import streamlit as st
import pandas as pd
import numpy as np
model = load_model('churn_fr_lgbm')

st.set_option('deprecation.showfileUploaderEncoding', False)

from PIL import Image
image_office = Image.open('office.jpg')
st.image(image_office,use_column_width=True)
add_selectbox = st.sidebar.selectbox("Comment voulez-vous faire votre prédiction?",("Online", "Fichier"))
st.sidebar.info("Ce modèle a été créé dans le but de prédire si un(e) employé(e) quittera l'entreprise")
st.sidebar.info("Résultat: 0 (reste); 1 (démissionne)")
st.sidebar.success('https://www.pycaret.org')
st.title("Prédire le départ d'un(e) employé(e)")


def predict(model, input_df):
    predictions_df = predict_model(estimator=model, data=input_df)
    predictions = predictions_df['Label'][0]
    return predictions



def run():

    if add_selectbox == 'Online':
        satisfaction_level=st.number_input('Niveau de satisfaction' , min_value=0.1, max_value=1.0, value=0.1)
        last_evaluation =st.number_input('Note dernière évaluation',min_value=0.1, max_value=1.0, value=0.1)
        number_project = st.number_input('Nombre de projets', min_value=0, max_value=50, value=5)
コード例 #5
0
import streamlit as st
import pandas as pd
from pycaret.classification import load_model, predict_model

modelo1 = load_model('meu-modelo-para-os-custos')
modelo2 = load_model('meu-modelo-para-smoker')


def classificador(modelo, dados):
    pred = predict_model(estimator=modelo, data=dados)
    return pred


def smap(x):
    y = 'male' if x == 'Masculino' else 'female'
    return y


def rmap(x):
    if x == 'Sudeste':
        return 'southeast'
    elif x == 'Noroeste':
        return 'northwest'
    elif x == 'Sudoeste':
        return 'southwest'
    else:
        return 'northeast'


def fmap(x):
    y = 'yes' if x == 'Sim' else 'no'
コード例 #6
0
    return {
        'fixed acidity': fixed_acidity,
        'volatile acidity': volatile_acidity,
        'citric acid': citric_acid,
        'residual sugar': residual_sugar,
        'chlorides': chlorides,
        'free sulfur dioxide': f_sulf_diox,
        'total sulfur dioxide': t_sulf_diox,
        'density': density,
        'pH': ph,
        'sulphates': sulphates,
        'alcohol': alcohol
    }


model = load_model('random_forest_model')

st.title('Classificador de vinhos')
st.write(
    'Este app tem o objetivo de classificar vinhos com base nas características fornecidas pelo usuário.\
         Por favor, ajuste os parâmetros de cada característica que referentes ao vinho que se deseja classificar. Após isto, clique em Classificar.'
)

features = define_features()

features_df = pd.DataFrame([features])

st.table(features_df)

if st.button('Classificar'):
コード例 #7
0
import streamlit as st

import pandas as pd

from sklearn import datasets

import matplotlib.pyplot as plt

from pycaret.classification import load_model, predict_model

modelo = load_model('Melhor Modelo para Custos')

st.title('Plano de Saúde Deploy Center')

st.sidebar.title('Menu Lateral')

idade = st.sidebar.number_input('Entre com sua idade', 18, 65, 20, 1)
imc = st.sidebar.slider('Entre com o seu IMC:', 18, 45, 25, 1)
sexo = st.sidebar.selectbox('Entre com o sexo:', ['male', 'female'])
criancas = st.sidebar.slider('Número de crianças:', 0, 5, 0, 1)
fumante = st.sidebar.selectbox('Fumante?', ['yes', 'no'])
regiao = st.sidebar.selectbox(
    'Região:', ['southeast', 'southwest', 'northeast', 'northwest'])

dicionario = {
    'age': [idade],
    'sex': [idade],
    'bmi': [imc],
    'children': [criancas],
    'region': [regiao],
    'smoker': [fumante]
コード例 #8
0
ファイル: app.py プロジェクト: LangatGilbert/100daysofcode
from pycaret.classification import load_model, predict_model
from pycaret.utils import check_metric
import streamlit as st
import pandas as pd
import numpy as np

#load the model
model = load_model('../model/employees_churn_model')

#define prediction fuction


def predict(model, input_df):
    predictions_df = predict_model(estimator=model, data=input_df)
    predictions = predictions_df['Label'][0]
    return predictions


def run():

    from PIL import Image
    # Image.open('../image/download.png').convert('RGB').save('../image/logo.png')
    # image = Image.open('../image/logo.png')

    Image.open('../image/kate-sade-unsplash.jpg').convert('RGB').save(
        '../image/employee_churn.png')
    image_churn = Image.open('../image/employee_churn.png')

    # st.image(image)

    add_selectbox = st.sidebar.selectbox(
コード例 #9
0
from pycaret.classification import load_model, predict_model
import streamlit as st
import pandas as pd
import numpy as np
model = load_model('Final_model')


def predict(model, input_df):
    predictions_df = predict_model(estimator=model, data=input_df)
    predictions = predictions_df['Label'][0]
    return predictions


def run():
    from PIL import Image
    image = Image.open('employeeleftimage.jpg')
    image_office = Image.open('office.jpg')
    st.image(image, use_column_width=True)
    add_selectbox = st.sidebar.selectbox("How would you like to predict?",
                                         ("Online", "Batch"))
    st.sidebar.info(
        'This app is created to predict if an employee will leave the company')
    st.sidebar.success('https://www.pycaret.org')
    st.sidebar.image(image_office)
    st.title("Predicting employee leaving")
    if add_selectbox == 'Online':
        satisfaction_level = st.number_input('satisfaction_level',
                                             min_value=0.1,
                                             max_value=1.0,
                                             value=0.1)
        last_evaluation = st.number_input('last_evaluation',
コード例 #10
0
from pycaret.classification import load_model, predict_model
import streamlit as st
import pandas as pd
import numpy as np

model = load_model('final_tuned_first_model_titanic_28Mar2021')

def predict(model, input_df):
    predictions_df = predict_model(estimator=model, data=input_df)
    predictions = predictions_df['Label'][0]
    return predictions

def main():

    from PIL import Image
    image = Image.open('labs.jpg')
    img_if = Image.open('ifserra.jpg')

    st.image(image,use_column_width=False)

    add_selectbox = st.sidebar.selectbox(
    "Forma de predição?",
    ("Online", "Batch"))

    st.title("App de Predição - Survived")
    st.sidebar.info('Verificar se com base nas informações o tripulante do Titanic sobreviveu ou não!')
    st.sidebar.success('https://www.github.com/disciplabs')  
    st.sidebar.image(img_if)

    if add_selectbox == 'Online':
コード例 #11
0
# -*- coding: utf-8 -*-
"""
Created on Wed Sep 23 21:36:59 2020

@author: Chamsedine
"""

from pycaret.classification import load_model, predict_model
import streamlit as st
import pandas as pd
import numpy as np
import io

model = load_model('deployment_dc')


def predict(model, input_df):
    predictions_df = predict_model(estimator=model, data=input_df)
    predictions = predictions_df['Label'][0]
    return predictions


def run():

    from PIL import Image
    image = Image.open('logo_train-data.png')

    st.image(image, use_column_width=False)

    add_selectbox = st.sidebar.selectbox("How would you like to predict?",
                                         ("Online", "Batch"))
コード例 #12
0
ファイル: streamlitapp.py プロジェクト: wandabwa2004/OTP
    st.markdown(page_bg_img, unsafe_allow_html=True)
    return


set_png_as_page_bg('nexplorer.jpg')


def predict_quality(model, df):

    predictions_data = predict_model(estimator=model, data=df)

    return predictions_data['Label'][0]


model = load_model('Randomforestmodel')

st.title('Kiwirail Trains OnTime  Predictions')
st.write(
    'A web-based app to predict whether a train will be late  or on time based on several features that you can see in the sidebar. Please adjust / select the value of each feature. After that, click on the Predict button at the bottom to  see the prediction of the model. Based on the  number of features at the moment, \
          accuracy in the predictions is about 91.81%. With more parameters, the model will improve.'
)

#origin_1_choices = {1:"Auckland",2: "Hamilton", 3: "Palmerston North"}
# def format_func(option)

train_id = st.sidebar.selectbox(
    "Train", ('B21', '269X', '249', 'B15', 'B43', 'B49', 'F19', '263', '243',
              '217', '221', '229', '267', '239', '225', '241R', 'B25', '267M',
              '241', '263X', '261', '235R', 'B35', 'B23', '239X', '217X',
              '221X', '221Y', '225X', '229X', '229Y', '243X', '243Y', 'F17',
コード例 #13
0
from pycaret.classification import load_model, predict_model
import streamlit as st
import pandas as pd
import numpy as np

# Reads in saved classification model
model = load_model('predict_resolution_time')

def predict(model, input_df):
    predictions_df = predict_model(estimator=model, data=input_df)
    predictions = predictions_df['Label'][0]
    return predictions

def run():

    st.write("""
    # SNOW Resolution Time Prediction App
    This app predicts the **Resolution Time Interval**!
    """)

    st.sidebar.header('User Input Features')

    st.sidebar.markdown("""
    [Example CSV input file](https://raw.githubusercontent.com/jraymartinez/snow-heroku/main/example_input_file.csv)
    """)

    # Collects user input features into dataframe
    uploaded_file = st.sidebar.file_uploader("Upload your input CSV file", type=["csv"])
    if uploaded_file is not None:
        input_df = pd.read_csv(uploaded_file)
        input_df['group'] = input_df['business_service'].map(str) + ' | ' + input_df['service_offering'].map(str) + ' | ' + input_df['assignment_group'].map(str)
コード例 #14
0
import streamlit as st
import pandas as pd
import os
from PIL import Image
from pycaret.classification import load_model, predict_model
from extract_features import various_features

width = 700

ml_model = load_model(
    '/mnt/napster_disk/ai_projects/ai_models/breast_cancer/breast_cancer_model'
)


def ml_breast_cancer_model():
    st.subheader("Classification using the machine learning model")
    uploaded_file = st.file_uploader("Insert image to analizer", type=None)

    if uploaded_file is not None:
        image_ml = Image.open(uploaded_file)
        st.image(image_ml,
                 caption="The image has been uploaded successfully...",
                 width=width)

        # Send to extract image caracters in dataset
        image_processing = various_features(image_ml)
        df_image_processing = pd.DataFrame(image_processing)
        predictions = predict_model(ml_model, df_image_processing)
        os.remove("/mnt/napster_disk/ai_projects/demos/analizer.png")
        result = int(predictions['Label'])
        score = float(predictions['Score'])
コード例 #15
0
from pycaret.classification import load_model, predict_model
import streamlit as st
import pandas as pd
import numpy as np

model = load_model('Airline passenger')


def predict(model, input_df):
    predictions_df = predict_model(estimator=model, data=input_df)
    predictions = predictions_df['Label'][0]
    return predictions


def run():
    from PIL import Image
    image = Image.open('airline sats.jfif')
    image_office = Image.open('side.jfif')
    st.image(image, use_column_width=True)
    add_selectbox = st.sidebar.selectbox("How would you like to predict?",
                                         ("single", "Batch"))
    st.sidebar.info(
        'This app is created to prdicting Airline Passenger Satisfaction')
    st.sidebar.success('https://www.pycaret.org')
    st.sidebar.image(image_office)
    st.title("Airline satisfaction")
    if add_selectbox == 'single':
        Age = st.number_input('Age', min_value=7, max_value=85, value=7)
        Flight_Distance = st.number_input('Flight_Distance',
                                          min_value=31.0,
                                          max_value=4983.0,
コード例 #16
0
 
from pycaret.classification import load_model, predict_model
import streamlit as st
import pandas as pd
import numpy as np
model = load_model('stroke-data')






def predict(model, input_df):
    predictions_df = predict_model(estimator=model, data=input_df)
    predictions = predictions_df['Label'][0]
    return predictions

def run():
    from PIL import Image
    image = Image.open('brainomixstroke.jpg')
    image_office = Image.open('stroke-recovery-timeline.jpg')
    st.image(image,use_column_width=True)
    add_selectbox = st.sidebar.selectbox(
    "How would you like to predict?",
    ("Online", "Batch"))
    st.sidebar.info('This app is created to predict if a patient is likely to get a stroke or not')
    st.sidebar.success('https://www.pycaret.org')
    st.sidebar.image(image_office)
    st.title("Predicting Stroke Disease")
    if add_selectbox == 'Online':
        id=st.number_input('id' , min_value=1, max_value=72943, value=1)
コード例 #17
0
ファイル: main.py プロジェクト: parmpreet/ml-edible-mushroom
            "stalk-surface-above-ring": [self.stalk_surface_above_ring],
            "stalk-surface-below-ring": [self.stalk_surface_below_ring],
            "stalk-color-above-ring": [self.stalk_color_above_ring],
            "stalk-color-below-ring": [self.stalk_color_below_ring],
            "veil-type": [self.veil_type],
            "veil-color": [self.veil_color],
            "ring-number": [self.ring_number],
            "ring-type": [self.ring_type],
            "spore-print-color": [self.spore_print_color],
            "population": [self.population],
            "habitat": [self.population]
        }


app = FastAPI()
model = load_model("final_knn_30-10-2020")


# TODO: load the config to setup app
@app.on_event("startup")
def startup():
    """
    This method will load the model on startup
    """
    # model =


# TODO: Return the useful status information
@app.get("/")
def read_root():
    """
コード例 #18
0
 def iaJob(self):
     saved_model = load_model('Prod_model')
     predictions = predict_model(saved_model, data=self.df_inc)
     return predictions
コード例 #19
0
from pycaret.classification import load_model, predict_model
import streamlit as st
import pandas as pd
import numpy as np
model = load_model('final qda model')


def predict(model, input_df):
    predictions_df = predict_model(estimator=model, data=input_df)
    predictions = predictions_df['Label'][0]
    return predictions


def run():
    from PIL import Image
    image = Image.open('irispred.jpg')
    image_office = Image.open('iris.jpg')
    st.image(image, use_column_width=True)
    add_selectbox = st.sidebar.selectbox("How would you like to predict?",
                                         ("Online", "Batch"))
    st.sidebar.info('This app is created to predict the class of iris plant.')
    st.sidebar.success('https://www.pycaret.org')
    st.sidebar.image(image_office)
    st.title("Predicting class of iris plant")
    if add_selectbox == 'Online':
        sepal_length = st.number_input('sepal length in cm',
                                       min_value=0.1,
                                       max_value=7.9,
                                       value=0.1)
        sepal_width = st.number_input('sepal width in cm',
                                      min_value=0.1,
コード例 #20
0
"""
# Global Libraries
from flask import Flask, request
import pandas as pd
import numpy as np
from pycaret.classification import load_model, predict_model
from sklearn.feature_extraction.text import TfidfVectorizer
from flask_jsonpify import jsonpify
import nltk
from nltk.corpus import stopwords
nltk.download('stopwords')

# Flask app
app = Flask(__name__)
# Charge model
et_model = load_model('et_model')
# Global dataset
df = pd.read_csv('final_df.csv')
# Add stop words
stop_words_eng = set(stopwords.words('english'))
stop_words_sp = set(stopwords.words('spanish'))
final_stop_words = set(list(stop_words_eng) + list(stop_words_sp))


@app.route('/')
def welcome():
    return "Welcome All"


@app.route('/predict_file', methods=["POST"])
def predict_batch_estimation_future():
コード例 #21
0
## for 0 prediction weekday, tem- 20 ,25,27,490,0.003
from pycaret.classification import load_model, predict_model
import streamlit as st
import pandas as pd
import numpy as np
import pickle
import six
import joblib
import sys
from datetime import datetime
import warnings
warnings.filterwarnings('ignore')
sys.modules['sklearn.externals.six'] = six
#import six

model = load_model('catboost classifier 17dec2020')


def predict(model, input_df):
    predictions_df = predict_model(estimator=model, data=input_df)
    predictions = predictions_df['Label'][0]
    return predictions


def run():

    from PIL import Image
    image = Image.open('dsp3.jpeg')
    image = image.resize((300, 100))
    #new_img.save("car_resized.jpg", "JPEG", optimize=True)
    image_meeting_room = Image.open('meeting room.JPG')
コード例 #22
0
from pycaret.classification import load_model, predict_model
import streamlit as st
import pandas as pd
model = load_model('Logistic regression')


def run():
    def predict(model, input_df):
        predictions_df = predict_model(estimator=model, data=input_df)
        predictions = predictions_df['Label'][0]
        return predictions

    st.title("Welcome to Dream Finance Housing Company")
    st.header("Please choose fill in the choices to get your Loan Eligibility")
    Gender = st.selectbox('Gender', ['Select', 'Male', 'Female'])
    Married = st.selectbox('Married', ['Select', 'Yes', 'No'])
    Dependents = st.selectbox('Dependents', ['Select', '0', '1', '2', '3+'])
    Education = st.selectbox('Education',
                             ['Select', 'Graduate', 'Not Graduate'])
    Self_Employed = st.selectbox('Self Employed', ['Select', 'Yes', 'No'])
    ApplicantIncome = st.number_input('Applicant Income',
                                      min_value=1.0,
                                      max_value=100000.0)
    CoapplicantIncome = st.number_input('Coapplicant Income',
                                        min_value=0.0,
                                        max_value=100000.0)
    LoanAmount = st.number_input('Loan Amount(In Hundreds)', min_value=1)
    Loan_Amount_Term = st.selectbox(
        'Term of Loan Amount(In Months)',
        ['Select', '60', '120', '180', '240', '300', '360'])
    Credit_History = st.selectbox('Credit History', ['Select', '0', '1'])
コード例 #23
0
from pycaret.classification import load_model, predict_model
import streamlit as st
import pandas as pd
import numpy as np

model = load_model('logistic')


def predict_churn(model, df):

    predictions_data = predict_model(estimator=model, data=df)
    return predictions_data['Label'][0]


st.title('Customer Churn Web App')
st.write('This is a web app to classify whether a customer will churn based on\
         several features that you can see in the sidebar. Please adjust the\
         value of each feature. After that, click on the Predict button at the bottom to\
         see the prediction of the classifier.')


def run():

    from PIL import Image
    image_2 = Image.open('churn_image.jpeg')

    #st.image(image,use_column_width=False)

    add_selectbox = st.sidebar.selectbox("How would you like to predict?",
                                         ("Online", "Batch"))
コード例 #24
0
from pycaret.classification import load_model, predict_model
import streamlit as st
import pandas as pd
import numpy as np

model = load_model('bank-loan')


def predict(model, input_df):
    predictions_df = predict_model(estimator=model, data=input_df)
    predictions = predictions_df['Label'][0]
    return predictions


def run():
    from PIL import Image
    image = Image.open('Personal_Loan.jpg')
    image_office = Image.open('bank.jpg')
    st.image(image, use_column_width=True)
    add_selectbox = st.sidebar.selectbox("How would you like to predict?",
                                         ("Online", "Batch"))
    st.sidebar.info(
        'This app is created to predict if customer is eligible for personal loan or not'
    )
    st.sidebar.success('https://www.pycaret.org')
    st.sidebar.image(image_office)
    st.title("Predicting chance to have personal loan")
    if add_selectbox == 'Online':
        ID = st.number_input('ID', min_value=1.0, max_value=10000.0, value=1.0)
        Age = st.number_input('Age', min_value=1.0, max_value=70.0, value=1.0)
        Experience = st.number_input('Experience',
コード例 #25
0
    }

    features = pd.DataFrame(data, index=[0])
    return features


# In[3]:

if __name__ == '__main__':

    st.write("""
    # Credit Card Fraud Detection
    """)

    st.sidebar.header('User Input Parameters')
    df = user_input_features()
    st.subheader('User Input Parameters')
    st.write(df)

    #filename = 'D:/IPSR/PYCARAT/catboost_final.pkl'
    model = load_model('catboost_final')
    pred = model.predict(df)
    st.subheader(
        '1 denotes frauduluent transaction, 0 denotes non-fraudulent transaction'
    )
    st.write(pred)

# In[4]:

# In[ ]:
コード例 #26
0

from pycaret.classification import load_model, predict_model
import streamlit as st
import pandas as pd
import numpy as np
model = load_model('final rf model')






def predict(model, input_df):
    predictions_df = predict_model(estimator=model, data=input_df)
    predictions = predictions_df['Label'][0]
    return predictions

def run():
    from PIL import Image
    image = Image.open('employee_left_image.jpg')
    image_office = Image.open('office_image.jpg')
    st.image(image,use_column_width=True)
    add_selectbox = st.sidebar.selectbox(
    "How would you like to predict?",
    ("Online", "Batch"))
    st.sidebar.info('This app is created to predict if an employee will leave the company')
    st.sidebar.success('https://www.pycaret.org')
    st.sidebar.image(image_office)
    st.title("Predicting employee leaving")
    if add_selectbox == 'Online':
コード例 #27
0
ファイル: stream_bank96.py プロジェクト: felixpaul96/bankdata
 
from pycaret.classification import load_model, predict_model
import streamlit as st
import pandas as pd
import numpy as np
model = load_model('bank')






def predict(model, input_df):
    predictions_df = predict_model(estimator=model, data=input_df)
    predictions = predictions_df['Label'][0]
    return predictions

def run():
    from PIL import Image
    image = Image.open('photo-1518183214770-9cffbec72538.jpg')
    image_office = Image.open('HOME-LOAN-HIKE.jpg')
    st.image(image,use_column_width=True)
    add_selectbox = st.sidebar.selectbox(
    "How would you like to predict?",
    ("Online", "Batch"))
    st.sidebar.info('This app is created to predict if customer is eligible for personal loan or not')
    st.sidebar.success('https://www.pycaret.org')
    st.sidebar.image(image_office)
    st.title("Predict that whether the individual could get a loan from bank or not ")
    if add_selectbox == 'Online':
        age=st.number_input('age',min_value=1.0, max_value=100.0, value=1.0)
コード例 #28
0
def run():
    from PIL import Image
    image = Image.open('logo.jpg')
    image_stock = Image.open('stock.jpg')

    st.image(image, use_column_width=False)

    add_selectbox = st.sidebar.selectbox("예측 방법 결정", ("Online", "Batch"))

    st.sidebar.info('프로젝트명 :' + '\n' + '자연어 처리 기반의 투자분석 및 예측시스템 개발')
    st.sidebar.success('★멘토님★ : 정좌연 PE')
    st.sidebar.info('팀명 : 턴어라운드')
    st.sidebar.success('팀원 : 이지훈, 이문형, 강민재, 구병진, 김서정')

    st.sidebar.image(image_stock)

    st.title("KOSPI 지수 및 YG 종목 주가 예측 모델")

    # 사용자 설정
    if add_selectbox == 'Online':
        date = str(
            st.number_input('Date',
                            min_value=20200101,
                            max_value=20201231,
                            value=20201027))
        rev_date = date[0:4] + '-' + date[4:6] + '-' + date[6:]
        target = st.selectbox('Target', ['KOSPI', 'YG'])
        method = st.selectbox(
            'Method',
            ['AutoML_CLA', 'AutoML_REG', 'ARIMA', 'Prophet', 'RL', 'NLP'])

        output = ""

        input_dict = {'Date': date, 'Target': target, 'Method': method}
        input_ = DataCollectionModel.DataCollection(date)
        prophet_input_ = ProphetModel.Prophet_(date)

        # 코스피 예측모델 데이터 수집 + 학습 데이터 준비
        if target == 'KOSPI':
            input_df = input_.kospi_collection()

            if method == 'AutoML_CLA':
                # 예측 모델
                model = load_model('deployment_kospi_20201029')
                # 학습 평가 모델
                model_train = load_model('deployment_kospi_train_20201029')
                load_test_model = predict_model(model_train,
                                                data=input_df[0].iloc[382:])
                test_model = load_test_model[['Labeling', 'Label']]

                acc_ = accuracy_score(test_model['Labeling'],
                                      test_model['Label'])
                auc_ = roc_auc_score(test_model['Labeling'],
                                     test_model['Label'])
                recall_ = recall_score(test_model['Labeling'],
                                       test_model['Label'])
                prec_ = precision_score(test_model['Labeling'],
                                        test_model['Label'])
                f1_ = f1_score(test_model['Labeling'], test_model['Label'])

                data = {
                    'ACC': [acc_],
                    'AUC': [auc_],
                    'RECALL': [recall_],
                    'PREC': [prec_],
                    'F1': [f1_]
                }

                score_model = pd.DataFrame(
                    data=data, columns=['ACC', 'AUC', 'RECALL', 'PREC', 'F1'])
                score_model.index.name = "Metrics Score"
                st.write("Test Data Metrics Score")
                st.table(score_model)

            elif method == 'AutoML_REG':

                # 예측 모델
                model = load_model('deployment_kospi_reg_20201029')
                # 학습 평가 모델
                model_train = load_model('deployment_kospi_reg_train_20201029')
                reg_data = copy.deepcopy(input_df[0].iloc[382:])
                del reg_data['Labeling']
                load_test_model = predict_model(model_train, data=reg_data)
                test_model = load_test_model[['Close', 'Label']]

                mae_ = mean_absolute_error(test_model['Close'],
                                           test_model['Label'])
                mse_ = mean_squared_error(test_model['Close'],
                                          test_model['Label'])
                rmse_ = mean_squared_error(test_model['Close'],
                                           test_model['Label'],
                                           squared=False)
                r2_ = r2_score(test_model['Close'], test_model['Label'])

                data = {
                    'MAE': [mae_],
                    'MSE': [mse_],
                    'RMSE': [rmse_],
                    'R2': [r2_]
                }

                score_model = pd.DataFrame(
                    data=data, columns=['MAE', 'MSE', 'RMSE', 'R2'])
                score_model.index.name = "Metrics Score"

                st.write("Test Data Metrics Score")
                st.table(score_model)
                st.write("Forecast Data (Test Data)")
                st.line_chart(test_model)

            elif method == 'ARIMA':
                # model load 필요시 여기에 추가
                print("ARIMA")

            elif method == 'Prophet':
                # model load 필요시 여기에 추가
                print("Prophet")

            elif method == 'RL':
                import main
                # model load 필요시 여기에 추가

                print("RL")

            elif method == 'NLP':
                # model load 필요시 여기에 추가
                print("NLP")

        # YG 예측모델 데이터 수집 + 학습 데이터 준비
        else:
            input_df = input_.yg_collection()

            if method == 'AutoML_CLA':
                # 예측 모델
                model = load_model('deployment_yg_20201029')
                # 학습 평가 모델
                model_train = load_model('deployment_yg_train_20201029')
                load_test_model = predict_model(model_train,
                                                data=input_df[0][341:])
                test_model = load_test_model[['Labeling', 'Label']]

                acc_ = accuracy_score(test_model['Labeling'],
                                      test_model['Label'])
                auc_ = roc_auc_score(test_model['Labeling'],
                                     test_model['Label'])
                recall_ = recall_score(test_model['Labeling'],
                                       test_model['Label'])
                prec_ = precision_score(test_model['Labeling'],
                                        test_model['Label'])
                f1_ = f1_score(test_model['Labeling'], test_model['Label'])

                data = {
                    'ACC': [acc_],
                    'AUC': [auc_],
                    'RECALL': [recall_],
                    'PREC': [prec_],
                    'F1': [f1_]
                }

                score_model = pd.DataFrame(
                    data=data, columns=['ACC', 'AUC', 'RECALL', 'PREC', 'F1'])
                score_model.index.name = "Metrics Score"
                st.write("Test Data Metrics Score")
                st.table(score_model)

            elif method == 'AutoML_REG':
                # 예측 모델
                model = load_model('deployment_yg_reg_20201029')
                # 학습 평가 모델
                model_train = load_model('deployment_yg_reg_train_20201029')
                reg_data = copy.deepcopy(input_df[0].iloc[341:])
                del reg_data['Labeling']
                load_test_model = predict_model(model_train, data=reg_data)
                test_model = load_test_model[['Close', 'Label']]

                mae_ = mean_absolute_error(test_model['Close'],
                                           test_model['Label'])
                mse_ = mean_squared_error(test_model['Close'],
                                          test_model['Label'])
                rmse_ = mean_squared_error(test_model['Close'],
                                           test_model['Label'],
                                           squared=False)
                r2_ = r2_score(test_model['Close'], test_model['Label'])

                data = {
                    'MAE': [mae_],
                    'MSE': [mse_],
                    'RMSE': [rmse_],
                    'R2': [r2_]
                }

                score_model = pd.DataFrame(
                    data=data, columns=['MAE', 'MSE', 'RMSE', 'R2'])
                score_model.index.name = "Metrics Score"

                st.write("Test Data Metrics Score")
                st.table(score_model)
                st.write("Forecast Data (Test Data)")
                st.line_chart(test_model)

            elif method == 'ARIMA':
                # model load 필요시 여기에 추가
                print("ARIMA")

            elif method == 'Prophet':
                # model load 필요시 여기에 추가
                print("prophet")

            elif method == 'RL':
                # model load 필요시 여기에 추가
                print("RL")

            elif method == 'NLP':
                print("NLP")

        # 예측 모델 실행
        buy_message = "주가 상승 예상 -> 매매 어드바이스 : 매수"
        sell_message = "주가 하락 예상 -> 매매 어드바이스 : 매도"

        if st.button("주가 예측"):
            if method == 'AutoML_CLA':
                output = predict(model=model, input_df=input_df[0])
                if output == '1':
                    output = date + buy_message
                else:
                    output = date + sell_message

            elif method == 'AutoML_REG':
                output = predict_reg(model=model, input_df=input_df)
                if output == '1':
                    output = date + buy_message
                else:
                    output = date + sell_message

            elif method == 'ARIMA':
                print("ARIMA")

            elif method == 'Prophet':
                if target == 'KOSPI':
                    df_prophet = copy.deepcopy(input_df[0])
                    df_prophet['date'] = pd.to_datetime(df_prophet.index)
                    df_data = df_prophet[['date',
                                          'Close']].reset_index(drop=True)
                    df_data = df_data.rename(columns={
                        'date': 'ds',
                        'Close': 'y'
                    })

                    prop_model = Prophet(yearly_seasonality='auto',
                                         weekly_seasonality='auto',
                                         daily_seasonality='auto',
                                         changepoint_prior_scale=0.15,
                                         changepoint_range=0.9)

                    prop_model.add_country_holidays(country_name='KR')
                    prop_model.fit(df_data)

                    kor_holidays = pd.concat([
                        pd.Series(np.array(SouthKorea().holidays(2020))[:, 0]),
                        pd.Series(np.array(SouthKorea().holidays(2021))[:, 0])
                    ]).reset_index(drop=True)

                    prop_future = prop_model.make_future_dataframe(periods=10)
                    prop_future = prop_future[prop_future.ds.dt.weekday != 5]
                    prop_future = prop_future[prop_future.ds.dt.weekday != 6]
                    for kor_holiday in kor_holidays:
                        prop_future = prop_future[
                            prop_future.ds != kor_holiday]

                    prop_forecast = prop_model.predict(prop_future)
                    prop_forecast[['ds', 'yhat', 'yhat_upper', 'yhat_lower']]

                    fig1 = prop_model.plot(prop_forecast)
                    fig2 = prop_model.plot_components(prop_forecast)
                    #cv = cross_validation(prop_model, initial='10 days', period='20 days', horizon='5 days')
                    #df_pm = performance_metrics(cv)
                    #fig3 = plot_cross_validation_metric(cv, metric='rmse')

                    st.write("Forecast Data")
                    st.write(fig1)
                    st.write("Component Wise Forecast")
                    st.write(fig2)
                    #st.write("Cross Validation Metric")
                    #st.table(df_pm)
                    #st.write(fig3)
                    output = prophet_input_.prophet_kospi(input_df[0])

                    if output == '1':
                        output = date + buy_message
                    else:
                        output = date + sell_message
                else:
                    df_prophet = copy.deepcopy(input_df[0])
                    df_prophet['date'] = pd.to_datetime(df_prophet.index)
                    df_data = df_prophet[['date',
                                          'Close']].reset_index(drop=True)
                    df_data = df_data.rename(columns={
                        'date': 'ds',
                        'Close': 'y'
                    })

                    # cp=['2019-10-23', '2019-11-04', '2019-11-13', '2019-11-22', '2019-12-04', '2019-12-13', '2019-12-26', '2020-01-08', '2020-01-17', '2020-01-31', '2020-02-11', '2020-02-20', '2020-03-03', '2020-03-12', '2020-03-23', '2020-04-02', '2020-04-13', '2020-04-23', '2020-05-08', '2020-05-19', '2020-05-29', '2020-06-09', '2020-06-18', '2020-06-30', '2020-07-09']
                    cp_spc = [
                        '2020-08-11', '2020-08-12', '2020-08-13', '2020-08-18',
                        '2020-08-19', '2020-08-20', '2020-08-26', '2020-08-28',
                        '2020-08-31', '2020-09-02', '2020-09-03', '2020-09-07',
                        '2020-09-08'
                    ]

                    cp_default = [
                        '2018-10-29', '2018-11-19', '2018-12-11', '2019-01-04',
                        '2019-01-29', '2019-02-22', '2019-03-19', '2019-04-10',
                        '2019-05-03', '2019-05-27', '2019-06-19', '2019-07-10',
                        '2019-08-01', '2019-08-26', '2019-09-20', '2019-10-15',
                        '2019-11-07', '2019-11-29', '2019-12-26', '2020-01-20',
                        '2020-02-13', '2020-03-05', '2020-03-30', '2020-04-21',
                        '2020-05-18'
                    ]
                    cp = cp_default + cp_spc

                    prop_model = Prophet(yearly_seasonality='auto',
                                         weekly_seasonality='auto',
                                         daily_seasonality='auto',
                                         changepoints=cp,
                                         changepoint_range=0.85,
                                         changepoint_prior_scale=0.2)
                    prop_model.fit(df_data)
                    kor_holidays = pd.concat([
                        pd.Series(np.array(SouthKorea().holidays(2019))[:, 0]),
                        pd.Series(np.array(SouthKorea().holidays(2020))[:, 0])
                    ]).reset_index(drop=True)
                    prop_future = prop_model.make_future_dataframe(periods=10)

                    prop_future = prop_future[prop_future.ds.dt.weekday != 5]
                    prop_future = prop_future[prop_future.ds.dt.weekday != 6]
                    for kor_holiday in kor_holidays:
                        prop_future = prop_future[
                            prop_future.ds != kor_holiday]

                    prop_forecast = prop_model.predict(prop_future)
                    prop_forecast[['ds', 'yhat', 'yhat_lower',
                                   'yhat_upper']].tail(10)

                    fig1 = prop_model.plot(prop_forecast)
                    fig2 = prop_model.plot_components(prop_forecast)
                    #cv = cross_validation(prop_model, initial='10 days', period='20 days', horizon='5 days')
                    #df_pm = performance_metrics(cv)
                    #fig3 = plot_cross_validation_metric(cv, metric='rmse')

                    st.write("Forecast Data")
                    st.write(fig1)
                    st.write("Component Wise Forecast")
                    st.write(fig2)
                    #st.write("Cross Validation Metric")
                    #st.table(df_pm)
                    #st.write(fig3)
                    output = prophet_input_.prophet_yg(input_df[0])

                    if output == '1':
                        output = date + buy_message
                    else:
                        output = date + sell_message

        st.success(output)

    if add_selectbox == 'Batch':

        file_upload = st.file_uploader("Upload csv file for predictions",
                                       type=["csv"])

        if file_upload is not None:
            data = pd.read_csv(file_upload)
            predictions = predict_model(estimator=model, data=data)
            st.write(predictions)
コード例 #29
0
from pycaret.classification import load_model, predict_model

import streamlit as st
import pandas as pd
import plotly.express as px

import matplotlib.pyplot as plt
import seaborn as sns
import warnings

warnings.filterwarnings("ignore")

#Loading Model ,model is placed in my local directory where the code file is
model = load_model('final_model')


def predict(model, input_df):
    predictions_df = predict_model(estimator=model, data=input_df)
    predictions = predictions_df['Label'][0]
    return predictions


def run_app():
    from PIL import Image
    image = Image.open('diabetes_img.JPG')
    st.image(image, use_column_width=True)
    add_selectbox = st.sidebar.selectbox(
        "How would you like to predict diabetes?", ("In Person", "Batch"))
    st.sidebar.info(
        'This application works  in two modes 1). InPerson mode where you can predict diabetes individually. '
        '2) Batch processing where you can predict diabetes of group of people and can visualize the data'
コード例 #30
0
from pycaret.classification import load_model, predict_model
import streamlit as st
import pandas as pd
import numpy as np
#from pycaret.regression import *


def predict_quality(model, df):

    predictions_data = predict_model(estimator=model, data=df)
    return predictions_data['Label'][0]


model = load_model('Final_rf')
############################################
# Title - The title and introductory text and images are all written in Markdown format here, using st.write()

st.write("""

# Predicción de victimización de empresas

Esta aplicación predice la victimizacin  de una empresa en Perú mediante un modelo de aprendizaje automático impulsado por[Pycaret](https://pycaret.org/).

Los datos del modelo son btenids de INEI [victimizacin de empresas](https://www.inei.gob.pe) Dataset.

Juega con los valores a través de los controles deslizantes del panel izquierdo para generar nuevas predicciones.
""")
st.write("---")

full_df = pd.read_csv('data/example1.csv')