Dash Classification Models

Hello, I want to create a web-based application with the dash library and the models I have specified below (for example the model I set up for logistics).
import pandas as pd # data processing
import numpy as np # working with arrays
import itertools # construct specialized tools
import matplotlib.pyplot as plt # visualizations
from sklearn.linear_model import LogisticRegression # model algorithm
from sklearn.preprocessing import StandardScaler # data normalization
from sklearn.metrics import accuracy_score
from sklearn.metrics import recall_score
from sklearn.metrics import f1_score
from sklearn.metrics import precision_score # evaluation metric
from sklearn.metrics import classification_report # evaluation metric
from sklearn.metrics import confusion_matrix # evaluation metric
LogisticRegression (C = 1.0, class_weight = None, dual = False, fit_intercept = True, intercept_scaling = 1, max_iter = 100, multi_class = ‘warn’, n_jobs = None, penalty = ‘l2’, random_state = 0, solver = 'lbfgs ', tol = 0.0001, verbose = 0, warm_start = False)
data = pd.read_excel (r’C: \ Users \ silk \ Desktop \ data.xlsx ')
def log_function (data, classifier):
print (log_function)
c = len (data.columns)
np.array (data)
a = np.array (data)
y = a [:, 0]
x = a [:, 1: c]
classifier = LogisticRegression (random_state = 0)
classifier.fit (x, y)
LogisticRegression (random_state = 0)
y_pred = classifier.predict (x)
for x in range (len (y_pred)):
if (y_pred == 1):
print (x, end = “\ t”)
cm = confusion_matrix (y, y_pred)
print (classifier, data.describe ())
print (“Confusion Matrix: \ n”, cm)
print (“Accuracy:”, accuracy_score (y, y_pred))
print (“Precision:”, metrics.precision_score (y, y_pred))
print (“Recall:”, metrics.recall_score (y, y_pred))
print (“f1_score:”, metrics.f1_score (y, y_pred))

My model includes logistic regression, svm, and decision trees. With Dash;
import base64
import datetime
import io
import dash
from dash.dependencies import Input, Output, State
import dash_core_components as dcc
import dash_html_components as html
import dash_table
import pandas as pd

external_stylesheets = [‘https://codepen.io/chriddyp/pen/bWLwgP.css’]

app = dash.Dash (__ name__, external_stylesheets = external_stylesheets)

app.layout = html.Div ([
dcc.Upload (
id = ‘upload-data’,

    children = html.Div ([
        'This developed system supports data files with .xls / .xlsx and .csv extensions.',
         html.Hr (),
        html.Button ('Select')
    ]),
    style = {
        'width': '100%',
        'height': '60px',
        'lineHeight': '60px',
        'borderWidth': '1px',
        'borderStyle': 'solid',
        'borderColor': '# c66',
        'backgroundColor': '#eee',
        'borderRadius': '5px',
        'textAlign': 'center',
        'margin': '10px'
    },
    # Allow multiple files to be uploaded
    multiple = True
),
html.Div (id = 'output-data-upload'),

])

def parse_contents (contents, filename, date):
content_type, content_string = contents.split (’,’)

decoded = base64.b64decode (content_string)
try:
    if 'csv' in filename:
        # Assume that the user uploaded a CSV file
        df = pd.read_csv (
            io.StringIO (decoded.decode ('utf-8')))
    elif 'xls' filename:
        # Assume that the user uploaded an excel file
        df = pd.read_excel (io.BytesIO (decoded))
except Exception as e:
    print (e)
    return html.Div ([
        'There was an error processing this file.'
    ])

return html.Div ([
    html.H5 (filename),
    html.H6 (datetime.datetime.fromtimestamp (date)),

    dash_table.DataTable (
        data = df.to_dict ('records'),
        columns = [{'name': i, 'id': i} for i in df.columns]
    ),

    html.Hr (), # horizontal line

    # For debugging, display the raw contents provided by the web browser
    html.Div ('Raw Content'),
    html.Pre (contents [0: 200] + '...', style = {
        'whiteSpace': 'pre-wrap',
        'wordBreak': 'break-all'
    })
])

@ app.callback (Output (‘output-data-upload’, ‘children’),
Input (‘upload-data’, ‘contents’),
State (‘upload-data’, ‘filename’),
State (‘upload-data’, ‘last_modified’))
def update_output (list_of_contents, list_of_names, list_of_dates):
if list_of_contents is not None:
children = [
parse_contents (c, n, d) for c, n, d in
zip (list_of_contents, list_of_names, list_of_dates)]
return children

if name == ‘main’:
app.run_server (debug = True)
I was able to load a generic data set using these codes. However, I want to create buttons that will allow the user to select the uploaded dataset as target (class) and independent (predictive) variables. After selecting these variables separately from the user data set, I want you to apply the models I have created and print the results. How should I do it?

Hi @YAGIN ,

Use the </> botton in the menu of (Ctrl+Shift+C) to show your code better to read and copy. :grinning:

2 Likes