Ejemplo n.º 1
0
def plot_3d(nclicks, oc, ctry):
    filtered_df = df_density[df_density['Country/Region'].isin(ctry)]
    fig1 = px.scatter_3d(filtered_df, x='Density', y='HDI', z='Hospital_beds_per_1000', color='Country/Region',
                         size=oc, size_max=90, hover_name='Country/Region',
                         height=690)
    fig1.update_layout(showlegend=False, hovermode='closest', margin=dict(l=50, b=80, t=40, r=30), height=700)
    return fig1
Ejemplo n.º 2
0
 def make_figure(color):
     print('ccc ', color)
     if color == None:
         my_color = None
     else:
         my_color = data1[color]
     return px.scatter_3d(
         projections,
         x=0,
         y=1,
         z=2,
         color=my_color,
         height=700,
     )
Ejemplo n.º 3
0
def threed_plot(df, x, y, z, c, s):
    """
    Generate a plotly 3d chart
    """
    args = {
        'x': x,
        'y': y,
        'z': z,
        'size': 'Annuli',
        'size_max': 20,
    }
    if c != 'None':
        args['color'] = c
    if s != 'None':
        args['symbol'] = s

    fig = go.Figure(px.scatter_3d(df, **args))
    fig['layout']['height'] = 1000
    graph = dcc.Graph(id='threed-chart', figure=fig)
    return graph
Ejemplo n.º 4
0
def main():
    df.drop(['Id'], inplace=True, axis=1)

    if st.sidebar.checkbox('EDA'):
        st.subheader('Exploratory data analysis (EDA)')
        # describe dataset
        if st.checkbox('Describe dataset'):

            st.write('Describe the data set')
            st.write(df.describe())

# value count
        if st.checkbox('Display vaules'):

            color_pallete = ['#fc5185', '#3fc1c9', '#364f6b']
            st.write('values of dataset')
            df['Species'].value_counts().plot(kind='bar', color=color_pallete)
            st.pyplot()

# drop the id

# visualization
        if st.checkbox('Visualize data'):

            st.write('Visualize dataset')
            plt.figure(figsize=(8, 8))
            ax = sns.pairplot(df, hue='Species')
            st.pyplot()

# Vusualize 3d plot
        if st.checkbox('Plot 3D plot'):

            fig = px.scatter_3d(df,
                                x="PetalLengthCm",
                                y="PetalWidthCm",
                                z="SepalLengthCm",
                                size="SepalWidthCm",
                                symbol="Species",
                                color='Species',
                                color_discrete_map={
                                    "Joly": "blue",
                                    "Bergeron": "violet",
                                    "Coderre": "pink"
                                })
            fig.show()
            st.pyplot()

# heat map
        if st.checkbox('Display heat map'):

            plt.figure()
            sns.heatmap(df.corr(), annot=True)
            plt.show()
            st.pyplot()


# train test split

    if st.sidebar.checkbox('Algorithms'):
        st.subheader('Alorithms')
        X = df.drop(['Species'], axis=1)
        y = df['Species']
        X_train, X_test, y_train, y_test = train_test_split(X,
                                                            y,
                                                            test_size=0.33,
                                                            random_state=42)
        # K
        if st.checkbox('KNN'):
            k = st.slider('K', 1, 15)
            knn = KNeighborsClassifier(n_neighbors=k)
            kfold_knn = model_selection.KFold(n_splits=10, random_state=7)
            knn_result = model_selection.cross_val_score(knn,
                                                         X,
                                                         y,
                                                         cv=kfold_knn,
                                                         scoring='accuracy')

            st.write('classifier name: K nearest neighbor algorithm')
            st.write('Accuracy score for your model is: ', knn_result.mean())
            SCORE['KNN'].append(knn_result)
            RESULTS.append(knn_result)

            plt.title('Accuracy score for KNN')
            plt.boxplot(SCORE['KNN'])
            plt.xlabel('KNN')
            st.pyplot()

        # Gausian Naive Baise Algorithm
        if st.checkbox('GausianNB'):
            gnb = GaussianNB()
            # start train
            kfold_gnb = model_selection.KFold(n_splits=10, random_state=7)
            gnb_result = model_selection.cross_val_score(gnb,
                                                         X,
                                                         y,
                                                         cv=kfold_gnb,
                                                         scoring='accuracy')
            SCORE['GausianNB'].append(gnb_result)
            RESULTS.append(gnb_result)
            st.write('classifier name: Gaussian Naive Baise algorithm')
            st.write('Accuracy score for your model is: ', gnb_result.mean())
            # plotbox
            plt.title('Accuracy score for Gaussian Naive Baise')
            plt.boxplot(SCORE['GausianNB'])
            plt.xlabel('GausianNB')
            st.pyplot()

        if st.checkbox('SVC'):
            c = st.slider('C', 0.01, 15.0)
            # g = st.slider('G', 0.01, 15.0)
            # support vector classifier
            svc = SVC(C=c, gamma='scale')

            kfold_svc = model_selection.KFold(n_splits=10, random_state=7)
            svc_result = model_selection.cross_val_score(svc,
                                                         X,
                                                         y,
                                                         cv=kfold_svc,
                                                         scoring='accuracy')
            SCORE['SVM'].append(svc_result)
            RESULTS.append(svc_result)
            st.write('classifier name: Support Vector Machine')
            st.write('Accuracy score for your model is: ', svc_result.mean())

            # plotbox
            plt.title('Accuracy score for Support Vector Classifier')
            plt.boxplot(SCORE['SVM'])
            plt.xlabel('SVM')
            st.pyplot()
        # Logistc Regression
        if st.checkbox('Logistic Regression'):
            lrc = LogisticRegression()

            kfold_lrc = model_selection.KFold(n_splits=10, random_state=7)
            lrc_result = model_selection.cross_val_score(lrc,
                                                         X,
                                                         y,
                                                         cv=kfold_lrc,
                                                         scoring='accuracy')
            SCORE['LRC'].append(lrc_result)
            RESULTS.append(lrc_result)

            st.write('classifier name: Logistic Regresssion')
            st.write('Accuracy score for your model is: ', lrc_result.mean())
            # plotbox
            plt.title('Accuracy score for Logistic Regression')
            plt.boxplot(SCORE['LRC'])
            plt.xlabel('LRC')
            st.pyplot()

        # Decision tree classifier
        if st.checkbox('Decision Tree Classifier'):
            depth = st.slider('max_depth', 1, 15)
            state = st.slider('random_state', 1, 15)

            mad_dt = DecisionTreeClassifier(max_depth=depth,
                                            random_state=state)

            kfold_dt = model_selection.KFold(n_splits=10, random_state=7)
            dt_result = model_selection.cross_val_score(mad_dt,
                                                        X,
                                                        y,
                                                        cv=kfold_dt,
                                                        scoring='accuracy')
            SCORE['DecisionTree'].append(dt_result)
            RESULTS.append(dt_result)
            st.write('classifier name: Decision Tree Algorithm')
            st.write('Accuracy score for your model is: ', dt_result.mean())

            # plotbox
            plt.title('Accuracy score for Decision Tree')
            plt.boxplot(SCORE['DecisionTree'])
            plt.xlabel('Decision Tree')
            st.pyplot()
    # RESULT
    if st.sidebar.checkbox('Results'):
        st.subheader('Accuracy scores of your models')
        if not SCORE:
            st.write('No model trained')
        else:
            st.write('SVC accuracy score: {} '.format(
                round(SCORE['SVM'][0].mean(), 2)))
            st.write('KNN accuracy score: {} '.format(
                round(SCORE['KNN'][0].mean(), 2)))
            st.write('Gaussian accuracy score: {} '.format(
                round(SCORE['GausianNB'][0].mean(), 2)))
            st.write('Logistic regression accuracy score:{}'.format(
                round(SCORE['LRC'][0].mean(), 2)))
            st.write('Decision Tree Algorithm: {} '.format(
                round(SCORE['DecisionTree'][0].mean(), 2)))

        st.subheader('The overall Boxplot of the result')

        fig = plt.figure()
        fig.suptitle('Algorithm Comparision')
        ax = fig.add_subplot(111)
        plt.boxplot(RESULTS)
        ax.set_xticklabels(NAME)
        st.pyplot()

    if st.sidebar.checkbox('About'):
        st.subheader('About this app')
        st.write("""
            The aim is to classify iris flowers among three species (setosa, versicolor, or virginica) from measurements of sepals and petals' length and width.

            The iris data set contains 3 classes of 50 instances each, where each class refers to a type of iris plant.

            This app uses 5 classification algorithms and check accuracy score between each others
        """)
        st.balloons()
Ejemplo n.º 5
0
import plotly_express as px
import seaborn as sns

iris = sns.load_dataset('iris')
iris.head()

px.scatter_3d(iris,
              x="petal_length",
              y="petal_width",
              z="sepal_length",
              size="sepal_width",
              color="species",
              color_discrete_map={
                  "Joly": "blue",
                  "Bergeron": "violet",
                  "Coderre": "pink"
              })
def update_graph(option_slctd):
    print(option_slctd)
    print(type(option_slctd))

    container = "The type of data choosen. by user was: {}".format(
        option_slctd)

    dff1 = df1.copy()
    dff1 = dff1[dff1["type"] == option_slctd]

    dff2 = df2.copy()
    dff2 = dff2[dff2["type"] == option_slctd]

    dff3 = df3.copy()
    dff3 = dff3[dff3["type"] == option_slctd]

    dff4 = df4.copy()
    dff4 = dff4[dff4["type"] == option_slctd]

    dff5 = df5.copy()
    dff5 = dff5[dff5["type"] == option_slctd]

    dff6 = df6.copy()
    dff6 = dff6[dff6["type"] == option_slctd]

    dfs = {
        "0033C822": dff1,
        "0034C8DF": dff2,
        "0034C74E": dff3,
        "0034C91E": dff4,
        "0034C559": dff5,
        "0034C864": dff6
    }

    data = [["0033C822",
             dff1["value"].max()], ["0034C8DF", dff2["value"].max()],
            ["0034C74E",
             dff3["value"].max()], ["0034C91E", dff4["value"].max()],
            ["0034C559", dff5["value"].max()],
            ["0034C864", dff6["value"].max()]]

    df = pd.DataFrame(data, columns=['device', 'value'])

    features = ["CO2", "humidity", "temperature"]
    # Plotly Express
    fig1 = go.Figure()
    fig2 = px.box(dff1, y="value")
    fig3 = px.bar(df, x="device", y="value")
    fig4 = px.scatter(dff1[6:132], x="timestamp", y="value")
    fig5 = px.scatter_3d(gdf6[:10],
                         x='CO2',
                         y='temperature',
                         z='humidity',
                         color='timestamp')
    fig6 = px.parallel_coordinates(
        gdf5[:50],
        color="CO2",
        labels={
            "CO2": "CO2",
            "humidity": "Humidity",
            "temperature": "Temperature",
        },
        color_continuous_scale=px.colors.diverging.Tealrose,
        color_continuous_midpoint=2)
    fig7 = px.scatter_matrix(gdf6, dimensions=features, color="CO2")
    fig7.update_traces(diagonal_visible=False)

    for i in dfs:
        fig1.add_trace(
            go.Scatter(x=dfs[i]["timestamp"], y=dfs[i]["value"], name=i))

    return container, fig1, fig2, fig3, fig4, fig5, fig6, fig7
Ejemplo n.º 7
0
    vp = rho * u - v - u * w

    wp = - beta * w + u * v

    return up, vp, wp

    # NUMERICAL INTEGRATIONS

t = np.linspace(0, tmax, n) # time
f = odeint(Lorenz, (u0, v0, w0), t, args = (sigma, beta, rho)) # numerical values for x,y,z states
x, y, z = f.T

    # PLOT

lor = px.scatter_3d(x = x, y = y, z = z, template = 'plotly_dark', width = 920, height = 700)
lor.update_traces(marker = dict(size = 4,
                              color = '#FFFFFF',
                              line = dict(width=2, color = '#000000')),
                  selector = dict(mode = 'markers'))
lor.update_xaxes(showgrid = False)
lor.update_yaxes(showgrid = False)
lor.update_xaxes(showticklabels = False)
lor.update_yaxes(showticklabels = False)

    # TEXT

st.subheader("3-DIMENSIONAL LORENZ SYSTEM: ")
st.markdown("")
st.latex("\Large{\dot{x} = \sigma(y - x)}")
st.latex("\Large{\dot{y} = rx - y - xz}")
Ejemplo n.º 8
0
def default_3d():
    fig3 = px.scatter_3d(df_density, x='Density', y='HDI', z='Hospital_beds_per_1000', color='Country/Region',
                         size='Incidence (per 100,000)', size_max=90, hover_name='Country/Region')
    fig3.update_layout(showlegend=False, hovermode='closest', margin=dict(l=50, b=80, t=40, r=30))
    return fig3
# 3-DIMENSIONAL PRINCIPAL COMPONENTS EXPLORATION

pca3 = PCA(n_components=3)
components3 = pca3.fit_transform(feature_set)

totalvar = pca3.explained_variance_ratio_.sum() * 100

st.title("")
st.subheader("Visualizing the Principal Components in 3 Dimensions")
pc3 = px.scatter_3d(
    components3,
    x = components3[:,0],
    y = components3[:,1],
    z = components3[:,2],
    color = feature_set['price'],
    size = feature_set['price'],
    title=f'Total Explained Variance: {totalvar:.2f}%',
    labels={'0': 'PC 1', '1': 'PC 2', '2': 'PC 3'},
    template = 'plotly_dark'
)
st.write(pc3)
if st.checkbox("Show Principal Components (N = 3)", False):
    st.write(components3)

# 2-DIMENSIONAL PRINCIPAL COMPONENTS EXPLORATION

pca2 = PCA(n_components = 2)
components2 = pca2.fit_transform(feature_set)

totalvar2 = pca2.explained_variance_ratio_.sum() * 100
Ejemplo n.º 10
0
    for r in rates:
        for A in As:
            ans_ = calc(enterprise, A, r)
            frame5 = frame5.append([{
                '预期收益': ans_,
                '贷款金额': A,
                '年利率': r
            }],
                                   ignore_index=True)
            # print(enterprise.number, ans_, A, r)
            if (ans_ > ans):
                ans = ans_
                ans_A = A
                ans_r = r
    print(enterprise.number, ans_, ans_A, ans_r)
    graph4 = px.scatter_3d(frame5, x="贷款金额", y="年利率", z='预期收益')
    graph4.write_html('./1_graph/预期收益/' + enterprise.number + '.html')
    break
    if i == 6:
        break
    else:
        i = i + 1

# %%
graph4 = px.scatter_3d(frame5, x="贷款金额", y="年利率", z='预期收益')
graph4.write_image('./1_graph/预期收益/' + enterprise.number + '.png')

# %%
import plotly
plotly.io.orca.config.executable = '/usr/bin/orca'
plotly.io.orca.config.save()
Ejemplo n.º 11
0
def upload_3():
    print('eer  0', request.form)
    dropdown_selection = str(request.form)
    dropdown_selection = dropdown_selection.split()
    dropdown_selection = dropdown_selection[1]

    print(dropdown_selection, "  nuna bhai")
    global id_name

    target = 'images/'
    print('tt', target)

    if not os.path.isdir(target):
        os.mkdir(target)
    global ff
    ff = []
    for file in request.files.getlist("file"):
        print(file)
        filename = file.filename
        destination = "/".join([target, filename])
        print('des', destination)
        file.save(destination)
        ff.append(destination)

    mypath = os.getcwd()
    onlyfiles = [
        os.path.join(mypath, f) for f in os.listdir(mypath)
        if os.path.isfile(os.path.join(mypath, f))
    ]

    import pandas as pd
    print('raJA ', ff)
    import warnings
    warnings.filterwarnings("ignore")

    data1 = pd.read_csv(ff[0])
    #print('datagg ',data1)

    #    dim = data = data1[['bedrooms', 'bathrooms', 'sqft_living',
    #       'sqft_lot', 'floors', 'waterfront', 'view', 'condition', 'grade',
    #       'sqft_above', 'sqft_basement', 'yr_built', 'yr_renovated', 'zipcode',
    #       'lat', 'long', 'sqft_living15', 'sqft_lot15', 'price']]

    if 'PCA' in dropdown_selection:
        input_list = request.form.to_dict()

        #data['some_key'] = "Some Value"
        print('input values ', input_list)
        print('input values ', type(input_list))

        target_name = input_list['lname']

        target_name = target_name.split("'")[1]
        print('taget ss ', target_name)
        print('taget ss ', type(target_name))

        feature_name = input_list['features']
        feature_name = feature_name.split(",")
        uuu = []
        for i in range(0, len(feature_name)):
            uuu.append(feature_name[i].split("'")[1])

        print('nuna yadav ', uuu)

        data = data1[uuu]
        yw = data1[target_name]

        #twrv = ThreadWithReturnValue(target=thread_function, args=(data1,data,yw))
        #twrv.start()
        #value = twrv.join()
        #data_explanation_thread = threading.Thread()
        #data_explanation_thread.start()
        #value = data_explanation_thread.join()
        #que = queue.Queue()
        #value = que.get()
        #print(value)
        #value = thread_function(data1,data,yw)

        print("pca ki jai")
        import plotly_express as px
        import dash
        import dash_html_components as html
        import dash_core_components as dcc
        from dash.dependencies import Input, Output

        # tips = px.data.tips()
        col_options = [dict(label=x, value=x) for x in data1.columns]
        dimensions = ['Select dimension to be shown in colour']

        ###pca
        from sklearn.preprocessing import StandardScaler
        scaler = StandardScaler()
        scaler.fit(data)
        scaled_data = scaler.transform(data)

        import plotly.express as px
        from sklearn.decomposition import PCA

        pca = PCA(n_components=2)
        components = pca.fit_transform(data)

        pca3 = PCA(n_components=3)
        components_3 = pca3.fit_transform(scaled_data)

        total_var = pca.explained_variance_ratio_.sum() * 100

        fig_3 = px.scatter_3d(
            components_3,
            x=0,
            y=1,
            z=2,
            color=yw,
            title=f'Total Explained Variance: {total_var:.2f}%',
            labels={
                '0': 'PC 1',
                '1': 'PC 2',
                '2': 'PC 3'
            })

        fig_3.show()
        #need to upload csv only

        fig = px.scatter(components, x=0, y=1, color=yw)
        fig.show()
        ###

        global id_name
        id_name_str = "my_graph" + str(id_name)
        print('---------------', id_name_str)
        id_name = id_name + 1

        new_pca.layout = html.Div([
            html.H1("Demo"),
            html.Div(
                [
                    html.P([d + ":",
                            dcc.Dropdown(id=d, options=col_options)])
                    for d in dimensions
                ],
                style={
                    "width": "25%",
                    "float": "left"
                },
            ),
            dcc.Graph(id=id_name_str,
                      style={
                          "width": "75%",
                          "display": "inline-block"
                      }),
            html.
            H3("Principal Component Analysis (PCA) is an unsupervised linear transformation technique that is widely used across different fields, most prominently for feature extraction and dimensionality reduction. Other popular applications of PCA include exploratory data analyses and de-noising of signals in stock market trading, and the analysis of genome data and gene expression levels in the field of bioinformatics."
               ),
        ])

        print('dimsum ', dimensions)

        @new_pca.callback(Output(id_name_str, "figure"),
                          [Input(d, "value") for d in dimensions])
        def make_figure(color):
            print('ccc ', color)
            if color == None:
                my_color = None
            else:
                my_color = data1[color]
            return px.scatter(
                components,
                x=0,
                y=1,
                color=my_color,
                height=700,
            )

        jj.layout = html.Div([dcc.Graph(figure=fig)])
        qq.layout = html.Div([dcc.Graph(figure=fig_3)])
        print("done")

        return render_template('pca_result.html',
                               PCA=new_pca.index(),
                               PCAA=new_pca.index())

    #######
    #p3
    if 'P3' in dropdown_selection:
        input_list = request.form.to_dict()

        #data['some_key'] = "Some Value"
        print('input values ', input_list)
        print('input values ', type(input_list))

        target_name = input_list['lname']

        target_name = target_name.split("'")[1]
        print('taget ss ', target_name)
        print('taget ss ', type(target_name))

        feature_name = input_list['features']
        feature_name = feature_name.split(",")
        uuu = []
        for i in range(0, len(feature_name)):
            uuu.append(feature_name[i].split("'")[1])

        print('nuna yadav ', uuu)

        data = data1[uuu]
        yw = data1[target_name]

        #twrv = ThreadWithReturnValue(target=thread_function, args=(data1,data,yw))
        #twrv.start()
        #value = twrv.join()
        #data_explanation_thread = threading.Thread()
        #data_explanation_thread.start()
        #value = data_explanation_thread.join()
        #que = queue.Queue()
        #value = que.get()
        #print(value)
        #value = thread_function(data1,data,yw)

        print("pca ki jai")
        import plotly_express as px
        import dash
        import dash_html_components as html
        import dash_core_components as dcc
        from dash.dependencies import Input, Output

        # tips = px.data.tips()
        col_options = [dict(label=x, value=x) for x in data1.columns]
        dimensions = ['Select dimension to be shown in colour']

        ###pca
        from sklearn.preprocessing import StandardScaler
        scaler = StandardScaler()
        scaler.fit(data)
        scaled_data = scaler.transform(data)

        import plotly.express as px
        from sklearn.decomposition import PCA

        pca = PCA(n_components=2)
        components = pca.fit_transform(scaled_data)

        pca3 = PCA(n_components=3)
        components_3 = pca3.fit_transform(data)

        total_var = pca.explained_variance_ratio_.sum() * 100

        #        global id_name
        id_name_str = "my_graph" + str(id_name)
        print('---------------', id_name_str)
        id_name = id_name + 1

        fig_3 = px.scatter_3d(
            components_3,
            x=0,
            y=1,
            z=2,
            color=yw,
            title=f'Total Explained Variance: {total_var:.2f}%',
            labels={
                '0': 'PC 1',
                '1': 'PC 2',
                '2': 'PC 3'
            })

        fig_3.show()
        #need to upload csv only

        fig = px.scatter(components, x=0, y=1, color=yw)
        fig.show()
        ###

        pca_3_fig.layout = html.Div([
            html.H1("Demo"),
            html.Div(
                [
                    html.P([d + ":",
                            dcc.Dropdown(id=d, options=col_options)])
                    for d in dimensions
                ],
                style={
                    "width": "25%",
                    "float": "left"
                },
            ),
            dcc.Graph(id=id_name_str,
                      style={
                          "width": "75%",
                          "display": "inline-block"
                      }),
            html.
            H3("Principal Component Analysis (PCA) is an unsupervised linear transformation technique that is widely used across different fields, most prominently for feature extraction and dimensionality reduction. Other popular applications of PCA include exploratory data analyses and de-noising of signals in stock market trading, and the analysis of genome data and gene expression levels in the field of bioinformatics."
               ),
        ])

        print('dimsum ', dimensions)

        @pca_3_fig.callback(Output(id_name_str, "figure"),
                            [Input(d, "value") for d in dimensions])
        def make_figure(color):
            print('ccc ', color)
            if color == None:
                my_color = None
            else:
                my_color = data1[color]
            return px.scatter_3d(
                components_3,
                x=0,
                y=1,
                z=2,
                color=my_color,
                height=700,
            )

        jj.layout = html.Div([dcc.Graph(figure=fig)])
        qq.layout = html.Div([dcc.Graph(figure=fig_3)])
        print("done")

        return render_template('pca_result.html',
                               PCA=pca_3_fig.index(),
                               PCAA=pca_3_fig.index())

    #######

    #t3

    if 'TSNE' in dropdown_selection:
        None
        input_list = request.form.to_dict()

        #data['some_key'] = "Some Value"
        print('input values ', input_list)
        print('input values ', type(input_list))

        target_name = input_list['lname']

        target_name = target_name.split("'")[1]
        print('taget ss ', target_name)
        print('taget ss ', type(target_name))

        feature_name = input_list['features']
        feature_name = feature_name.split(",")
        uuu = []
        for i in range(0, len(feature_name)):
            uuu.append(feature_name[i].split("'")[1])

        print('nuna yadav ', uuu)

        data = data1[uuu]
        yw = data1[target_name]

        #twrv = ThreadWithReturnValue(target=thread_function, args=(data1,data,yw))
        #twrv.start()
        #value = twrv.join()
        #data_explanation_thread = threading.Thread()
        #data_explanation_thread.start()
        #value = data_explanation_thread.join()
        #que = queue.Queue()
        #value = que.get()
        #print(value)
        #value = thread_function(data1,data,yw)

        print("pca ki jai")
        import plotly_express as px
        import dash
        import dash_html_components as html
        import dash_core_components as dcc
        from dash.dependencies import Input, Output

        # tips = px.data.tips()
        col_options = [dict(label=x, value=x) for x in data1.columns]
        dimensions = ['Select dimension to be shown in colour']

        ###pca
        from sklearn.preprocessing import StandardScaler
        scaler = StandardScaler()
        scaler.fit(data)
        scaled_data = scaler.transform(data)

        from sklearn.manifold import TSNE
        import plotly.express as px

        tsne_algo = TSNE(n_components=3, random_state=0)
        projections = tsne_algo.fit_transform(data, )

        #        global id_name
        id_name_str = "my_graph" + str(id_name)
        print('---------------', id_name_str)
        id_name = id_name + 1

        fig_3 = px.scatter_3d(projections,
                              x=0,
                              y=1,
                              z=2,
                              color=yw,
                              labels={
                                  '0': 'PC 1',
                                  '1': 'PC 2',
                                  '2': 'PC 3'
                              })

        fig_3.show()
        #need to upload csv only

        tsne.layout = html.Div([
            html.H1("Demo"),
            html.Div(
                [
                    html.P([d + ":",
                            dcc.Dropdown(id=d, options=col_options)])
                    for d in dimensions
                ],
                style={
                    "width": "25%",
                    "float": "left"
                },
            ),
            dcc.Graph(id=id_name_str,
                      style={
                          "width": "75%",
                          "display": "inline-block"
                      }),
            html.
            H3("t-Distributed Stochastic Neighbor Embedding (t-SNE) is an unsupervised, non-linear technique primarily used for data exploration and visualizing high-dimensional data. In simpler terms, t-SNE gives you a feel or intuition of how the data is arranged in a high-dimensional space. It was developed by Laurens van der Maatens and Geoffrey Hinton in 2008."
               ),
        ])

        print('dimsum ', dimensions)

        @tsne.callback(Output(id_name_str, "figure"),
                       [Input(d, "value") for d in dimensions])
        def make_figure(color):
            print('ccc ', color)
            if color == None:
                my_color = None
            else:
                my_color = data1[color]
            return px.scatter_3d(
                projections,
                x=0,
                y=1,
                z=2,
                color=my_color,
                height=700,
            )

        return render_template('pca_result.html',
                               PCA=tsne.index(),
                               PCAA=tsne.index())

    if 'PP' in dropdown_selection:
        import plotly_express as px
        import dash
        import dash_html_components as html
        import dash_core_components as dcc
        from dash.dependencies import Input, Output

        id_name_str = "my_graph" + str(id_name)

        print('---------------', id_name_str)

        id_name = id_name + 1

        col_options = [dict(label=x, value=x) for x in data1.columns]
        dimensions = ["x", "y", "color", "facet_col", "facet_row"]

        local_explain2.layout = html.Div([
            html.H1("dashboard"),
            html.Div(
                [
                    html.P([d + ":",
                            dcc.Dropdown(id=d, options=col_options)])
                    for d in dimensions
                ],
                style={
                    "width": "25%",
                    "float": "left"
                },
            ),
            dcc.Graph(id=id_name_str,
                      style={
                          "width": "75%",
                          "display": "inline-block"
                      }),
        ])

        @local_explain2.callback(Output(id_name_str, "figure"),
                                 [Input(d, "value") for d in dimensions])
        def make_figure(x, y, color, facet_col, facet_row):
            ctx = dash.callback_context

            print('-----------', ctx)
            if x == None:
                x = data1[data1.columns[2]]
            if y == None:
                y = data1[data1.columns[3]]

            return px.scatter(
                data1,
                x=x,
                y=y,
                color=color,
                facet_col=facet_col,
                facet_row=facet_row,
                height=700,
            )

        return render_template('local_local_result.html',
                               LL=local_explain2.index(),
                               TA=1)

    if 'DE' in dropdown_selection:
        None
Ejemplo n.º 12
0
def thread_function(data1, data, yw):
    print("pca ki jai")
    import plotly_express as px
    import dash
    import dash_html_components as html
    import dash_core_components as dcc
    from dash.dependencies import Input, Output

    wwww = dash.Dash(__name__, server=app, url_base_pathname='/wwww/')

    fig = go.Figure(data=[go.Bar(x=[1, 2, 3], y=[1, 3, 2])],
                    layout=go.Layout(title=go.layout.Title(
                        text="A Figure Specified By A Graph Object")))

    wwww.layout = html.Div([dcc.Graph(figure=fig)])

    # tips = px.data.tips()
    col_options = [dict(label=x, value=x) for x in data1.columns]
    dimensions = ['color']

    ###pca
    from sklearn.preprocessing import StandardScaler
    scaler = StandardScaler()
    scaler.fit(data)
    scaled_data = scaler.transform(data)

    import plotly.express as px
    from sklearn.decomposition import PCA

    pca = PCA(n_components=2)
    components = pca.fit_transform(scaled_data)

    pca3 = PCA(n_components=3)
    components_3 = pca3.fit_transform(scaled_data)

    total_var = pca.explained_variance_ratio_.sum() * 100

    fig_3 = px.scatter_3d(components_3,
                          x=0,
                          y=1,
                          z=2,
                          color=yw,
                          title=f'Total Explained Variance: {total_var:.2f}%',
                          labels={
                              '0': 'PC 1',
                              '1': 'PC 2',
                              '2': 'PC 3'
                          })

    fig_3.show()
    #need to upload csv only

    fig = px.scatter(components, x=0, y=1, color=yw)
    fig.show()
    ###

    wwww.layout = html.Div([
        html.H1("Demo"),
        html.Div(
            [
                html.P([d + ":",
                        dcc.Dropdown(id=d, options=col_options)])
                for d in dimensions
            ],
            style={
                "width": "25%",
                "float": "left"
            },
        ),
        dcc.Graph(id="graph",
                  style={
                      "width": "75%",
                      "display": "inline-block"
                  }),
    ])

    print('dimsum ', dimensions)

    @wwww.callback(Output("graph", "figure"),
                   [Input(d, "value") for d in dimensions])
    def make_figure(color):
        print('ccc ', color)
        if color == None:
            my_color = None
        else:
            my_color = data1[color]
        return px.scatter(
            components,
            x=0,
            y=1,
            color=my_color,
            height=700,
        )

# jj.layout = html.Div([dcc.Graph(figure=fig)])
#www.layout = html.Div([dcc.Graph(figure=fig_3)])

    print("done")

    return wwww.index()
Ejemplo n.º 13
0
def Plot():
    wb = xw.Book.caller()
    df = From_pkl()

    Animation = wb.sheets('Dash').range('B6:B7').value
    inputs = wb.sheets('Dash').range('B12:M12').value
    Layout = wb.sheets('Dash').range('B9:F9').value

    Filter = wb.sheets('Dash').range('G3').value

    af = Animation[0]
    ag = Animation[1]

    Title = Layout[0]
    hover_name = Layout[1]
    Log_x = Layout[3]
    Log_y = Layout[4]

    if Filter is not None:
        df = df.query(Filter)

    if inputs[0] == 'scatter':
        Plot = px.scatter(df,
                          title=Title,
                          x=inputs[1],
                          y=inputs[2],
                          color=inputs[3],
                          size=inputs[4],
                          facet_row=inputs[5],
                          facet_col=inputs[6],
                          hover_name=hover_name,
                          animation_frame=af,
                          animation_group=ag,
                          log_x=Log_x,
                          log_y=Log_y,
                          trendline=inputs[7],
                          marginal_x=inputs[8],
                          marginal_y=inputs[9])

    elif inputs[0] == 'line':
        Plot = px.line(df,
                       title=Title,
                       x=inputs[1],
                       y=inputs[2],
                       color=inputs[3],
                       log_x=Log_x,
                       log_y=Log_y,
                       facet_row=inputs[4],
                       facet_col=inputs[5],
                       line_group=inputs[6],
                       line_dash=inputs[7])

    elif inputs[0] == 'scatter matrix':
        Plot = px.scatter_matrix(df, title=Title, color=inputs[1])

    elif inputs[0] == 'bar':
        Plot = px.bar(df,
                      x=inputs[1],
                      title=Title,
                      y=inputs[2],
                      color=inputs[3],
                      log_x=Log_x,
                      log_y=Log_y,
                      facet_row=inputs[4],
                      facet_col=inputs[5])

    elif inputs[0] == 'density':
        Plot = px.density_contour(
            df,
            title=Title,
            x=inputs[1],
            y=inputs[2],
            color=inputs[3],
            facet_row=inputs[4],
            facet_col=inputs[5],
            marginal_x=inputs[8],
            marginal_y=inputs[7],
            log_x=Log_x,
            log_y=Log_y,
        )

    elif inputs[0] == 'box':
        Plot = px.box(df,
                      title=Title,
                      x=inputs[1],
                      y=inputs[2],
                      color=inputs[3],
                      log_x=Log_x,
                      log_y=Log_y,
                      facet_row=inputs[4],
                      facet_col=inputs[5])

    elif inputs[0] == 'histogram':
        Plot = px.histogram(df,
                            title=Title,
                            x=inputs[1],
                            y=inputs[2],
                            log_x=Log_x,
                            log_y=Log_y,
                            color=inputs[3],
                            facet_row=inputs[4],
                            facet_col=inputs[5],
                            histfunc=inputs[6],
                            marginal=inputs[8])

    elif inputs[0] == 'violin':
        Plot = px.violin(df,
                         title=Title,
                         x=inputs[1],
                         y=inputs[2],
                         color=inputs[3],
                         facet_row=inputs[4],
                         log_x=Log_x,
                         log_y=Log_y,
                         facet_col=inputs[5])

    elif inputs[0] == '3d scatter':
        Plot = px.scatter_3d(df,
                             title=Title,
                             x=inputs[1],
                             y=inputs[2],
                             z=inputs[3],
                             log_x=Log_x,
                             log_y=Log_y,
                             color=inputs[4],
                             size=inputs[5],
                             hover_name=hover_name)

    elif inputs[0] == '3d line':
        Plot = px.line_3d(
            df,
            title=Title,
            x=inputs[1],
            y=inputs[2],
            z=inputs[3],
            log_x=Log_x,
            log_y=Log_y,
            color=inputs[4],
            size=inputs[5],
        )

    elif inputs[0] == 'scatter polar':
        Plot = px.scatter_polar(df,
                                title=Title,
                                r=inputs[1],
                                theta=inputs[2],
                                color=inputs[3],
                                log_x=Log_x,
                                log_y=Log_y,
                                symbol=inputs[4])

    elif inputs[0] == 'line polar':
        Plot = px.line_polar(df,
                             title=Title,
                             r=inputs[1],
                             theta=inputs[2],
                             log_x=Log_x,
                             log_y=Log_y,
                             color=inputs[2],
                             line_close=True)

    elif inputs[0] == 'bar polar':
        Plot = px.bar_polar(df,
                            title=Title,
                            r=inputs[1],
                            theta=inputs[2],
                            log_x=Log_x,
                            log_y=Log_y,
                            color=inputs[3])

    elif inputs[0] == 'parallel_categories':
        Plot = px.parallel_categories(df, title=Title, color=inputs[1])

    plotly.offline.plot(Plot)