Spaces:
Sleeping
Sleeping
Download src/streamlit_app.py from Sahil0605/Predict_data: direct link, hf CLI and curl.
- Browser
- Download file 7.18 kB
-
https://huggingface.co/spaces/Sahil0605/Predict_data/resolve/main/src/streamlit_app.py
- Command line
-
hf download hf://spaces/Sahil0605/Predict_data/src/streamlit_app.py
-
curl -L -o streamlit_app.py https://huggingface.co/spaces/Sahil0605/Predict_data/resolve/main/src/streamlit_app.py
7.18 kB
| import streamlit as st | |
| import pandas as pd | |
| import pickle | |
| from sklearn.preprocessing import LabelEncoder | |
| from sklearn.model_selection import train_test_split | |
| from sklearn.linear_model import LinearRegression, LogisticRegression | |
| from sklearn.neighbors import KNeighborsClassifier | |
| from sklearn.tree import DecisionTreeClassifier | |
| from sklearn.metrics import accuracy_score, r2_score | |
| # ------------------- | |
| # Session State Setup | |
| # ------------------- | |
| defaults = { | |
| "uploaded_file_name": None, | |
| "df": None, | |
| "processed_df": None, | |
| "encoders": {}, | |
| "models": {}, | |
| "final_model": None, | |
| "problem_type": None, | |
| "target_encoder": None | |
| } | |
| for key, value in defaults.items(): | |
| if key not in st.session_state: | |
| st.session_state[key] = value | |
| # ------------------- | |
| # Sidebar Navigation | |
| # ------------------- | |
| st.sidebar.title("Navigation") | |
| page = st.sidebar.selectbox("Go to", [ | |
| "Upload File", | |
| "Preprocess Data", | |
| "Train & Select Model", | |
| "Create App" | |
| ]) | |
| # ------------------- | |
| # Upload File Page | |
| # ------------------- | |
| if page == "Upload File": | |
| st.title("Upload CSV or SQL File") | |
| uploaded_file = st.file_uploader("Upload a CSV or SQL file", type=["csv", "sql"]) | |
| if uploaded_file is not None: | |
| st.session_state.uploaded_file_name = uploaded_file.name | |
| if uploaded_file.name.endswith(".csv"): | |
| st.session_state.df = pd.read_csv(uploaded_file) | |
| st.dataframe(st.session_state.df) | |
| elif uploaded_file.name.endswith(".sql"): | |
| sql_content = uploaded_file.read().decode("utf-8") | |
| st.text_area("SQL Content", sql_content, height=300) | |
| st.success("File loaded into memory!") | |
| # ------------------- | |
| # Preprocess Data Page | |
| # ------------------- | |
| elif page == "Preprocess Data": | |
| st.title("Preprocess Uploaded CSV") | |
| if st.session_state.df is not None: | |
| st.write("Current Data:") | |
| st.dataframe(st.session_state.df) | |
| # Drop missing | |
| missing_placeholders = [ | |
| "?", "NA", "N/A", "na", "null", "NULL", "none", "None", | |
| "missing", "Missing", "not available", "Not Available", | |
| "--", "---", "-", "_", "" | |
| ] | |
| if st.button("Drop Missing / Placeholder Values"): | |
| df = st.session_state.df.replace(missing_placeholders, pd.NA) | |
| df = df.dropna() | |
| st.session_state.df = df | |
| st.success("Missing values dropped!") | |
| # Drop selected columns | |
| col_to_drop = st.multiselect("Select columns to drop", st.session_state.df.columns) | |
| if st.button("Drop Selected Columns"): | |
| st.session_state.df = st.session_state.df.drop(columns=col_to_drop) | |
| st.success(f"Dropped columns: {col_to_drop}") | |
| # Label encode | |
| if st.button("Label Encode Object Columns"): | |
| st.session_state.encoders = {} | |
| for col in st.session_state.df.select_dtypes(include=['object']).columns: | |
| le = LabelEncoder() | |
| st.session_state.df[col] = le.fit_transform(st.session_state.df[col].astype(str)) | |
| st.session_state.encoders[col] = le | |
| st.success("Object columns label-encoded!") | |
| # Save processed | |
| if st.button("Save Preprocessed Data"): | |
| st.session_state.processed_df = st.session_state.df.copy() | |
| st.success("Preprocessed data saved in memory!") | |
| else: | |
| st.warning("Please upload a CSV first.") | |
| # ------------------- | |
| # Train & Select Model Page | |
| # ------------------- | |
| elif page == "Train & Select Model": | |
| st.title("Train Models and Select the Best One") | |
| if st.session_state.processed_df is not None: | |
| df = st.session_state.processed_df | |
| target_col = st.selectbox("Select target column", df.columns) | |
| if target_col: | |
| X = df.drop(columns=[target_col]) | |
| y = df[target_col] | |
| # Detect problem type | |
| if y.dtype == "object" or len(y.unique()) <= 20: | |
| st.session_state.problem_type = "classification" | |
| else: | |
| st.session_state.problem_type = "regression" | |
| # Train/test split | |
| test_size = st.slider("Test size (%)", 20, 50, 30, step=5) | |
| X_train, X_test, y_train, y_test = train_test_split( | |
| X, y, test_size=test_size/100, random_state=42 | |
| ) | |
| results = {} | |
| st.session_state.models = {} | |
| if st.session_state.problem_type == "classification": | |
| models = { | |
| "Logistic Regression": LogisticRegression(max_iter=500), | |
| "KNN": KNeighborsClassifier(), | |
| "Decision Tree": DecisionTreeClassifier() | |
| } | |
| for name, model in models.items(): | |
| model.fit(X_train, y_train) | |
| preds = model.predict(X_test) | |
| acc = accuracy_score(y_test, preds) | |
| results[name] = acc | |
| st.session_state.models[name] = model | |
| else: | |
| models = { | |
| "Linear Regression": LinearRegression(), | |
| "Decision Tree": DecisionTreeClassifier() | |
| } | |
| for name, model in models.items(): | |
| model.fit(X_train, y_train) | |
| preds = model.predict(X_test) | |
| score = r2_score(y_test, preds) | |
| results[name] = score | |
| st.session_state.models[name] = model | |
| # Show results | |
| st.subheader("Model Scores") | |
| for name, score in results.items(): | |
| st.write(f"{name}: {score:.4f}") | |
| selected_model = st.selectbox("Select model to save", list(results.keys())) | |
| if st.button("Save Selected Model"): | |
| st.session_state.final_model = st.session_state.models[selected_model] | |
| st.success("Model saved in memory!") | |
| else: | |
| st.warning("Please preprocess a file first.") | |
| # ------------------- | |
| # Create App Page | |
| # ------------------- | |
| elif page == "Create App": | |
| st.title("Use Model for Prediction") | |
| if st.session_state.final_model is not None and st.session_state.processed_df is not None: | |
| df = st.session_state.processed_df | |
| target_col = st.selectbox("Select target column", df.columns) | |
| X = df.drop(columns=[target_col]) | |
| user_input = {} | |
| for col in X.columns: | |
| if col in st.session_state.encoders: | |
| options = st.session_state.encoders[col].classes_.tolist() | |
| val = st.selectbox(f"Select {col}", options) | |
| user_input[col] = st.session_state.encoders[col].transform([val])[0] | |
| else: | |
| val = st.number_input(f"Enter {col}", value=float(X[col].mean())) | |
| user_input[col] = val | |
| if st.button("Predict"): | |
| input_df = pd.DataFrame([user_input]) | |
| prediction = st.session_state.final_model.predict(input_df) | |
| st.subheader("Prediction") | |
| st.write(prediction[0]) | |
| else: | |
| st.warning("Please train and save a model first.") | |