Spaces:
Sleeping
Sleeping
File size: 11,866 Bytes
65a3718 |
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 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 |
import streamlit as st
import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler, LabelEncoder
from sklearn.linear_model import LogisticRegression, LinearRegression
from sklearn.tree import DecisionTreeClassifier, DecisionTreeRegressor
from sklearn.ensemble import RandomForestClassifier, RandomForestRegressor
from sklearn.svm import SVC, SVR
from sklearn.naive_bayes import GaussianNB, MultinomialNB
from sklearn.neighbors import KNeighborsClassifier, KNeighborsRegressor
from sklearn.neural_network import MLPClassifier, MLPRegressor
from sklearn.metrics import (
accuracy_score,
mean_squared_error,
mean_absolute_error,
r2_score,
classification_report
)
class MachineLearningApp:
def __init__(self):
st.set_page_config(
page_title="ML Model Selection App",
page_icon=":robot_face:",
layout="wide"
)
self.initialize_session_state()
def initialize_session_state(self):
"""Initialize all session state variables"""
initial_states = {
'data': None,
'X': None,
'y': None,
'model': None,
'scaler': None,
'label_encoder': None,
'problem_type': None,
'test_size': 0.2,
'selected_features': [],
'target_column': None,
'selected_model': None,
'model_results': None
}
for key, value in initial_states.items():
if key not in st.session_state:
st.session_state[key] = value
def sidebar_data_upload(self):
"""Sidebar for data upload"""
with st.sidebar:
st.header("๐ Data Upload")
uploaded_file = st.file_uploader(
"Choose a CSV or Excel file",
type=['csv', 'xlsx', 'xls']
)
return uploaded_file
def sidebar_feature_selection(self, df):
"""Sidebar for feature and target selection"""
with st.sidebar:
st.header("๐ Feature Selection")
if df is None:
st.warning("Please upload a dataset first.")
return None, None, None
numeric_cols = df.select_dtypes(include=['int64', 'float64']).columns.tolist()
categorical_cols = df.select_dtypes(include=['object']).columns.tolist()
selected_features = st.multiselect(
"Select Features",
options=list(df.columns),
default=numeric_cols
)
target_column = st.selectbox(
"Select Target Column",
options=list(df.columns)
)
test_size = st.slider(
"Test Set Percentage",
min_value=0.1,
max_value=0.5,
value=0.2,
step=0.05,
help="Percentage of data to use for testing"
)
return selected_features, target_column, test_size
def sidebar_model_selection(self, problem_type):
"""Sidebar for model selection"""
with st.sidebar:
st.header("๐ค Model Selection")
if problem_type == 'classification':
models = {
'Logistic Regression': LogisticRegression(),
'Decision Tree': DecisionTreeClassifier(),
'Random Forest': RandomForestClassifier(),
'SVM': SVC(),
'Naive Bayes (Gaussian)': GaussianNB(),
'Naive Bayes (Multinomial)': MultinomialNB(),
'K-Nearest Neighbors': KNeighborsClassifier(),
'Neural Network': MLPClassifier(max_iter=1000)
}
else:
models = {
'Linear Regression': LinearRegression(),
'Decision Tree': DecisionTreeRegressor(),
'Random Forest': RandomForestRegressor(),
'SVR': SVR(),
'K-Nearest Neighbors': KNeighborsRegressor(),
'Neural Network': MLPRegressor(max_iter=1000)
}
selected_model = st.selectbox(
"Choose a Model",
options=list(models.keys())
)
return models, selected_model
def sidebar_prediction_input(self, selected_features):
"""Sidebar for prediction input"""
with st.sidebar:
st.header("๐ฎ Prediction Input")
if st.session_state.model is None:
st.warning("Please train a model first.")
return None
prediction_inputs = {}
for feature in selected_features:
prediction_inputs[feature] = st.number_input(
f"Enter {feature}",
value=0.0,
step=0.1
)
if st.button("Predict"):
return prediction_inputs
return None
def load_and_display_data(self, uploaded_file):
"""Load data and display dataset information"""
if uploaded_file is not None:
try:
if uploaded_file.name.endswith('.csv'):
df = pd.read_csv(uploaded_file)
else:
df = pd.read_excel(uploaded_file)
st.session_state.data = df
col1, col2 = st.columns(2)
with col1:
st.subheader("๐ Dataset Preview")
st.dataframe(df.head())
with col2:
st.subheader("๐ Dataset Information")
st.write(f"Total Rows: {df.shape[0]}")
st.write(f"Total Columns: {df.shape[1]}")
col_types = df.dtypes.value_counts()
st.write("Column Types:")
for dtype, count in col_types.items():
st.text(f"{dtype}: {count} columns")
return df
except Exception as e:
st.error(f"Error loading file: {e}")
return None
def train_and_evaluate_model(self, X, y, test_size, models, selected_model_name):
"""Train and evaluate the selected model"""
results_container = st.container()
with results_container:
X_scaled = StandardScaler().fit_transform(X)
problem_type = 'classification' if y.dtype == 'object' else 'regression'
label_encoder = None
if problem_type == 'classification':
label_encoder = LabelEncoder()
y_encoded = label_encoder.fit_transform(y)
else:
y_encoded = y
X_train, X_test, y_train, y_test = train_test_split(
X_scaled, y_encoded, test_size=test_size, random_state=42
)
model = models[selected_model_name]
model.fit(X_train, y_train)
y_pred = model.predict(X_test)
st.header("๐ฌ Model Training Results")
col1, col2 = st.columns(2)
with col1:
st.subheader("๐ Model Performance")
if problem_type == 'classification':
accuracy = accuracy_score(y_test, y_pred)
st.metric("Accuracy", f"{accuracy:.2%}")
st.subheader("Classification Report")
report = classification_report(
y_test, y_pred,
target_names=label_encoder.classes_ if label_encoder else None,
output_dict=True
)
for key, value in report.items():
if isinstance(value, dict):
st.text(f"{key}:")
for metric, score in value.items():
st.text(f" {metric}: {score:.2f}")
else:
mse = mean_squared_error(y_test, y_pred)
mae = mean_absolute_error(y_test, y_pred)
r2 = r2_score(y_test, y_pred)
st.metric("Mean Squared Error", f"{mse:.4f}")
st.metric("Mean Absolute Error", f"{mae:.4f}")
st.metric("Rยฒ Score", f"{r2:.4f}")
with col2:
st.subheader("๐ Model Details")
st.write(f"Selected Model: {selected_model_name}")
st.write(f"Problem Type: {problem_type}")
st.write(f"Test Set Size: {test_size:.0%}")
st.write(f"Features Used: {', '.join(X.columns)}")
st.write(f"Target Column: {y.name}")
st.session_state.model = model
st.session_state.scaler = StandardScaler().fit(X)
st.session_state.label_encoder = label_encoder
st.session_state.problem_type = problem_type
st.session_state.X = X
def make_prediction(self, prediction_inputs):
"""Make prediction on unseen data"""
if st.session_state.model is None:
st.error("Please train a model first.")
return
input_df = pd.DataFrame([prediction_inputs])
input_scaled = st.session_state.scaler.transform(input_df)
prediction = st.session_state.model.predict(input_scaled)
if st.session_state.label_encoder:
prediction = st.session_state.label_encoder.inverse_transform(prediction)
st.header("๐ฏ Prediction Result")
st.subheader("Input Data")
st.dataframe(input_df)
st.subheader("Predicted Value")
st.write(prediction[0])
def run(self):
"""Main application flow"""
uploaded_file = self.sidebar_data_upload()
st.title("๐ Predict on Custom Data using any ML Model")
df = self.load_and_display_data(uploaded_file)
if df is not None:
selected_features, target_column, test_size = self.sidebar_feature_selection(df)
if selected_features and target_column:
X = df[selected_features]
y = df[target_column]
problem_type = 'classification' if y.dtype == 'object' else 'regression'
models, selected_model = self.sidebar_model_selection(problem_type)
with st.sidebar:
if st.button("Train Model", type="primary"):
for key in ['model', 'scaler', 'label_encoder', 'problem_type']:
st.session_state[key] = None
self.train_and_evaluate_model(
X, y, test_size, models, selected_model
)
prediction_inputs = self.sidebar_prediction_input(selected_features)
if prediction_inputs:
self.make_prediction(prediction_inputs)
if __name__ == "__main__":
app = MachineLearningApp()
app.run() |