Streamlit refreshes automatically

Hi All, I’m using a ML algo to predict anomalies. from ui i can select dataset and no of signals (columns ). then it uses those columns to predict and show anomalies on plotly fig. This app works fine uunitl i select 7-8 columns , but when i start giving more columns it shows the result and disappear immeadiately

Hi @Suraj_Pattewar,

Thank you for sharing your question with the community!

Your post is missing a code snippet and a link to your app’s GitHub repo. Please check out our guidelines on how to post an effective question here and update your post to help the community answer your question.

I have such same problem, when I create a functionality on a single widget it works, but when I try to integrate the importing a function from another file, it refreshes the page after inputs.

Here is code from user_page file, needed to be imported after login successful.

import streamlit as st
import pandas as pd
import numpy as np
from sklearn.pipeline import Pipeline
from sklearn.impute import SimpleImputer
from sklearn.preprocessing import StandardScaler, OneHotEncoder
from sklearn.compose import ColumnTransformer
from sklearn.linear_model import LinearRegression
from sklearn.ensemble import RandomForestRegressor
from sklearn.metrics import r2_score, mean_squared_error
from sklearn.neural_network import MLPRegressor
from keras import Sequential
import pickle

def load_data(file):
    data = pd.read_csv(file)
    return data

def preprocess_data(df, numerical_features, categorical_features, target_feature):
    numerical_transformer = Pipeline(steps=[
        ('imputer', SimpleImputer(strategy='median')),
        ('scaler', StandardScaler())
    ])

    categorical_transformer = Pipeline(steps=[
        ('imputer', SimpleImputer(strategy='constant', fill_value='missing')),
        ('onehot', OneHotEncoder(handle_unknown='ignore'))
    ])

    preprocessor = ColumnTransformer(
        transformers=[
            ('num', numerical_transformer, numerical_features),
            ('cat', categorical_transformer, categorical_features)
        ])

    X = df.drop(target_feature, axis=1)
    y = df[target_feature]

    X_transformed = preprocessor.fit_transform(X)

    return X_transformed, y, preprocessor

def train_model(X, y, model_type):
    if model_type == 'Linear Regression':
        model = LinearRegression()
    elif model_type == 'Random Forest':
        model = RandomForestRegressor(n_estimators=100, random_state=42)
    elif model_type == 'ANN':
        model = MLPRegressor(hidden_layer_sizes=(100,50), max_iter=1000)
    else:
        model = LinearRegression()

    model.fit(X, y)

    return model


    # Save model to a file
    with open('model.pkl', 'wb') as file:
        pickle.dump(model, file)

    st.write("### Model Trained Successfully!")

    
def predict(model, X):
    y_pred = model.predict(X)
    return y_pred


def main():
    st.title('User Page')

    file = st.file_uploader('Upload your dataset', type=['csv'])

    if file is not None:
        df = load_data(file)
        st.write(df.head())

        numerical_features = st.multiselect('Select numerical features', df.select_dtypes(include=[np.number]).columns.tolist())
        categorical_features = st.multiselect('Select categorical features', df.select_dtypes(include=[np.object]).columns.tolist())
        target_feature = st.selectbox('Select target feature', df.columns.tolist())

        if len(numerical_features + categorical_features) == 0:
            st.warning('Please select at least one feature')
        else:
            X, y, preprocessor = preprocess_data(df, numerical_features, categorical_features, target_feature)

            model_type = st.selectbox('Select model type', ['Linear Regression', 'Random Forest', 'ANN'])

            if st.button('Train Model'):
                model = train_model(X, y, model_type)

                y_pred = predict(model, X)
                
                # Save model to a file
                with open('model.pkl', 'wb') as file:
                	pickle.dump(model, file)

                st.write(f'R2 Score: {r2_score(y, y_pred)}')
                st.write(f'Mean Squared Error: {mean_squared_error(y, y_pred)}')
                
                # Plot
                st.write("### Before Prediction")
                st.line_chart(y)
                
                st.write("### After Prediction")
                st.line_chart(y_pred)

                if st.button('Show Predictions'):
                    X_transformed = preprocessor.transform(df.drop(target_feature, axis=1))
                    df['Predicted Target'] = predict(model, X_transformed)
                    st.write(df.head())

if __name__ == '__main__':
    main()

1 Like

Tagging @jlampart in case this issue is related to this one.

Thanks,
Charly

Yes, it does. Though mine it refreshes the page while it’s still locally not deployed on the cloud and I don’t know how to fix it.

Any, help please!!

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.