Spaces:
Sleeping
Sleeping
File size: 7,179 Bytes
10b0bce 2b24720 45a0991 2b24720 ee36296 2b24720 ee36296 000fb26 ee36296 2b24720 abaca12 ee36296 2b24720 abaca12 ee36296 2b24720 abaca12 2b24720 ee36296 abaca12 2b24720 ee36296 000fb26 ee36296 2b24720 abaca12 2b24720 ee36296 2b24720 ee36296 abaca12 2b24720 ee36296 2b24720 ee36296 2b24720 abaca12 2b24720 abaca12 2b24720 ee36296 abaca12 2b24720 abaca12 2b24720 ee36296 000fb26 ee36296 2b24720 abaca12 2b24720 ee36296 2b24720 abaca12 2b24720 abaca12 2b24720 ee36296 abaca12 ee36296 2b24720 abaca12 2b24720 abaca12 2b24720 abaca12 2b24720 45a0991 2b24720 abaca12 2b24720 ee36296 abaca12 2b24720 abaca12 2b24720 abaca12 2b24720 abaca12 2b24720 ee36296 000fb26 ee36296 2b24720 abaca12 2b24720 abaca12 2b24720 abaca12 2b24720 abaca12 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 | 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.")
|