Python Plotly仪表板回调v2

Python Plotly仪表板回调v2,python,callback,plotly-dash,Python,Callback,Plotly Dash,我有一个滑块,用户输入和工作表之间的依赖关系。尽管如此,由于我只能描述从字典创建的基本数据帧进行更新,并且在字典中有一个简单的计算(基于阈值)。我无法显示表格,我不确定哪里出了问题 **其他信息:** 阈值默认为0.5,并通过用户输入(滑块或手动输入)的回调进行更新 额外的列作为基于阈值的二进制输出添加到数据帧df metrics是对y_true和y_pred的计算,即fr,它输入的阈值尝试输出数据并使用回调更新数据。有人建议我只在回调中创建表,并使用“Div”定义其在显示中的位置 我的代码

我有一个滑块,用户输入和工作表之间的依赖关系。尽管如此,由于我只能描述从字典创建的基本数据帧进行更新,并且在字典中有一个简单的计算(基于阈值)。我无法显示表格,我不确定哪里出了问题

**其他信息:**

  • 阈值默认为0.5,并通过用户输入(滑块或手动输入)的回调进行更新
  • 额外的列作为基于阈值的二进制输出添加到数据帧
    df
  • metrics
    是对
    y_true
    y_pred
    的计算,即fr,它输入的阈值尝试输出数据并使用回调更新数据。有人建议我只在回调中创建表,并使用“Div”定义其在显示中的位置
我的代码如下:


import dash_bootstrap_components as dbc

import dash_core_components as dcc

import dash_html_components as html

import numpy as np

from scipy import stats

import plotly.graph_objs as go

from plotly.offline import init_notebook_mode, iplot

from datetime import datetime as dt

import dash_table

import pandas as pd

from sklearn import svm, datasets

import base64

import numpy as np

from sklearn.metrics import roc_auc_score, accuracy_score, cohen_kappa_score, recall_score, accuracy_score, precision_score, f1_score

from sklearn import metrics

from dash.dependencies import Input, Output```
import pandas as pd

from dash.dependencies import Input, Output

threshold = 0.5

# read data

data = pd.read_csv('data.csv')

#count columns in dataframe
count_algo = len(data.columns)


################################################################
########################  Body  ################################
################################################################


body = dbc.Container(
    [
        dbc.Row(
            [
                dbc.Col(
                    [
                        html.H2("Slider + Manual entry test"),
                        dcc.Slider(
                            id="my-slider",
                            min=0,
                            max=1,
                            step=0.01,
                            marks={"0": "0", "0.5": "0.5", "1": "1"},
                            value=threshold,
                        ),
                        html.Div(id="update-table"),
                    ]
                ),
                dbc.Col(
                    [
                        html.Div(
                            [
                                html.Div(
                                    dcc.Input(
                                        id="input-box",
                                        max=0,
                                        min=1,
                                        step=0.01,
                                        value=threshold,
                                    )
                                ),
                                html.Div(id="slider-output-container"),
                            ]
                        )
                    ]
                ),
            ]
        )
    ]
)

app = dash.Dash(__name__, external_stylesheets=[dbc.themes.BOOTSTRAP])

app.layout = html.Div([body])


##############################################################
######################## callbacks ###########################
##############################################################


@app.callback(
    dash.dependencies.Output("slider-output-container", "children"),
    [dash.dependencies.Input("my-slider", "value")],
)
def update_output(value):
    threshold = float(value)
    return threshold


# call back for slider to update based on manual input
@app.callback(
    dash.dependencies.Output(component_id="my-slider", component_property="value"),
    [dash.dependencies.Input("input-box", "value")],
)
def update_output(value):
    threshold = float(value)
    return threshold


# call back to update table


@app.callback(
    dash.dependencies.Output("update-table", "children"),
    [dash.dependencies.Input("my-slider", "value")],
)
def update_output(value):
    #take value of threshold
    threshold = float(value)

    # add predicted 
    for i in data.iloc[:,1:]:
        data['predicted_"{}"'.format(i)] = (data[i] >= threshold).astype('int')

    table_data = pd.DataFrame.from_dict({
        "AUC":[roc_auc_score(data.actual_label, data[i]) for i in data.iloc[:,count_algo:]],
        "Accuracy":[accuracy_score(data.actual_label, data[i])for i in data.iloc[:,count_algo:]],
        "Kappa":[cohen_kappa_score(data.actual_label, data[i])for i in data.iloc[:,count_algo:]],
        "Sensitivity (Recall)": [recall_score(data.actual_label, data[i], average = 'weighted')for i in data.iloc[:,count_algo:]],
        "Specificity": [accuracy_score(data.actual_label, data[i])for i in data.iloc[:,count_algo:]],
        "Precision": [precision_score(data.actual_label, data[i], average = 'weighted')for i in data.iloc[:,count_algo:]],
        "F1": [f1_score(data.actual_label, data[i], average = 'weighted')for i in data.iloc[:,count_algo:]]
    }, orient = 'index').reset_index()

    return html.Div([
        dash_table.DataTable(
            data=table_data.to_dict("rows"),
            columns=[{"id": x, "name": x} for x in table_data.columns],
            style_table={'overflowX': 'scroll'},
            style_cell={'width':100},
        )
    ])




if __name__ == "__main__":
    app.run_server()

我找到了问题的解决方案,但无法确定实际问题是什么。我必须假设它与脚本的顺序有关(我可以得到一个未填充的表)。无论如何,我通过创建一个函数来填充并返回表来解决这个问题(见下文):

roc_表(数据)
插入
dash_表
。使用的数据集来自:
def roc_table(data,threshold):
    #count columns in dataframe
    count_algo = len(data.columns)

    for i in data.iloc[:,1:]:
        data['predicted_{}'.format(i)] = (data[i] >= threshold).astype('int')

    rock_table = {
        "AUC":[roc_auc_score(data.actual_label, data[i]) for i in data.iloc[:,count_algo:]],
        "Accuracy":[accuracy_score(data.actual_label, data[i])for i in data.iloc[:,count_algo:]],
        "Kappa":[cohen_kappa_score(data.actual_label, data[i])for i in data.iloc[:,count_algo:]],
        "Sensitivity (Recall)": [recall_score(data.actual_label, data[i], average = 'weighted')for i in data.iloc[:,count_algo:]],
        "Specificity": [accuracy_score(data.actual_label, data[i])for i in data.iloc[:,count_algo:]],
        "Precision": [precision_score(data.actual_label, data[i], average = 'weighted')for i in data.iloc[:,count_algo:]],
        "F1": [f1_score(data.actual_label, data[i], average = 'weighted')for i in data.iloc[:,count_algo:]]
    }   

    rock_table = pd.DataFrame.from_dict(rock_table, orient = 'index').reset_index()
    col = ['metrics']
    col.extend([x for x in data.iloc[:,count_algo:]])
    rock_table.columns = col    

    return rock_table