saikumar27 commited on
Commit
3f33a47
·
verified ·
1 Parent(s): e6dae60

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +15 -428
app.py CHANGED
@@ -1,435 +1,22 @@
1
- import streamlit as st
2
  import pandas as pd
3
  import numpy as np
4
- import plotly.express as px
5
- import plotly.graph_objects as go
6
- from sklearn.model_selection import train_test_split
7
- from sklearn.preprocessing import StandardScaler
8
- from sklearn.metrics import mean_squared_error, r2_score, accuracy_score, classification_report
9
- from sklearn.ensemble import RandomForestRegressor, RandomForestClassifier
10
- from sklearn.linear_model import LinearRegression, LogisticRegression
11
- from sklearn.svm import SVR, SVC
12
- from pydantic import BaseModel, Field
13
- import pickle
14
- import base64
15
- from fpdf import FPDF
16
- import io
17
- from PIL import Image
18
- from st_aggrid import AgGrid, GridOptionsBuilder
19
 
20
- # Set page config
21
- st.set_page_config(page_title="Comprehensive Data Analysis Dashboard", layout="wide")
22
-
23
- # Custom CSS to enhance the visual appeal
24
- st.markdown("""
25
- <style>
26
- .reportview-container {
27
- background: #1E1E1E;
28
- color: #FFFFFF;
29
- }
30
- .main .block-container {
31
- padding-top: 2rem;
32
- padding-bottom: 2rem;
33
- }
34
- h1, h2, h3, h4 {
35
- color: #FFFFFF;
36
- }
37
- .stButton>button {
38
- color: #FFFFFF;
39
- background-color: #4CAF50;
40
- border-radius: 5px;
41
- }
42
- .stTextInput>div>div>input {
43
- color: #FFFFFF;
44
- background-color: #2E2E2E;
45
- border-radius: 5px;
46
- }
47
- .stSelectbox>div>div>select {
48
- color: #FFFFFF;
49
- background-color: #2E2E2E;
50
- }
51
- .stExpander {
52
- background-color: #2E2E2E;
53
- border-radius: 5px;
54
- margin-bottom: 1rem;
55
- }
56
- .css-145kmo2 {
57
- color: #FFFFFF;
58
- }
59
- .css-1d391kg {
60
- color: #FFFFFF;
61
- }
62
- </style>
63
- """, unsafe_allow_html=True)
64
-
65
- # Initialize session state
66
- if 'data' not in st.session_state:
67
- st.session_state.data = None
68
- if 'original_data' not in st.session_state:
69
- st.session_state.original_data = None
70
- if 'model' not in st.session_state:
71
- st.session_state.model = None
72
- if 'scaler' not in st.session_state:
73
- st.session_state.scaler = None
74
- if 'features' not in st.session_state:
75
- st.session_state.features = None
76
- if 'models' not in st.session_state:
77
- st.session_state.models = {}
78
-
79
- # Functions
80
- @st.cache_data
81
- def load_data(file):
82
- try:
83
- data = pd.read_csv(file)
84
- return data
85
- except Exception as e:
86
- st.error(f"Error loading data: {str(e)}")
87
- return None
88
-
89
- def get_column_types(data):
90
- return {
91
- 'numeric': data.select_dtypes(include=[np.number]).columns.tolist(),
92
- 'categorical': data.select_dtypes(include=['object']).columns.tolist()
93
- }
94
-
95
- def remove_nan(data):
96
- return data.dropna()
97
-
98
- def train_model(X, y, model_type, params):
99
- try:
100
- X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
101
- scaler = StandardScaler()
102
- X_train_scaled = scaler.fit_transform(X_train)
103
- X_test_scaled = scaler.transform(X_test)
104
-
105
- if model_type == "Random Forest Regressor":
106
- model = RandomForestRegressor(**params)
107
- elif model_type == "Linear Regression":
108
- model = LinearRegression(**params)
109
- elif model_type == "SVR":
110
- model = SVR(**params)
111
- elif model_type == "Random Forest Classifier":
112
- model = RandomForestClassifier(**params)
113
- elif model_type == "Logistic Regression":
114
- model = LogisticRegression(**params)
115
- else: # SVC
116
- model = SVC(**params)
117
-
118
- model.fit(X_train_scaled, y_train)
119
-
120
- y_pred = model.predict(X_test_scaled)
121
- if model_type in ["Random Forest Regressor", "Linear Regression", "SVR"]:
122
- mse = mean_squared_error(y_test, y_pred)
123
- r2 = r2_score(y_test, y_pred)
124
- return model, scaler, mse, r2, None
125
- else:
126
- accuracy = accuracy_score(y_test, y_pred)
127
- report = classification_report(y_test, y_pred)
128
- return model, scaler, accuracy, None, report
129
- except Exception as e:
130
- st.error(f"Error during model training: {str(e)}")
131
- return None, None, None, None, None
132
-
133
- def save_model(model, scaler):
134
- model_pickle = pickle.dumps(model)
135
- scaler_pickle = pickle.dumps(scaler)
136
- return model_pickle, scaler_pickle
137
-
138
- def create_download_link(val, filename):
139
- b64 = base64.b64encode(val)
140
- return f'<a href="data:application/octet-stream;base64,{b64.decode()}" download="{filename}">Download file</a>'
141
-
142
- def create_pdf(data, visualizations, model_results):
143
- pdf = FPDF()
144
- pdf.add_page()
145
-
146
- # Add title
147
- pdf.set_font("Arial", "B", 16)
148
- pdf.cell(0, 10, "Data Analysis Report", ln=True, align="C")
149
- pdf.ln(10)
150
-
151
- # Add data overview
152
- pdf.set_font("Arial", "B", 14)
153
- pdf.cell(0, 10, "Data Overview", ln=True)
154
- pdf.set_font("Arial", "", 12)
155
- pdf.multi_cell(0, 10, f"Number of rows: {data.shape[0]}\nNumber of columns: {data.shape[1]}")
156
- pdf.ln(10)
157
-
158
- # Add visualizations
159
- pdf.set_font("Arial", "B", 14)
160
- pdf.cell(0, 10, "Visualizations", ln=True)
161
- for title, img_bytes in visualizations.items():
162
- pdf.set_font("Arial", "B", 12)
163
- pdf.cell(0, 10, title, ln=True)
164
- img = Image.open(img_bytes)
165
- img_path = f"temp_{title.replace(' ', '_')}.png"
166
- img.save(img_path)
167
- pdf.image(img_path, x=10, w=190)
168
- pdf.ln(10)
169
-
170
- # Add model results
171
- pdf.set_font("Arial", "B", 14)
172
- pdf.cell(0, 10, "Model Results", ln=True)
173
- pdf.set_font("Arial", "", 12)
174
- for key, value in model_results.items():
175
- pdf.multi_cell(0, 10, f"{key}: {value}")
176
-
177
- return pdf.output(dest="S").encode("latin-1")
178
-
179
- # Pydantic model for config
180
- class AppConfig(BaseModel):
181
- title: str = Field("Comprehensive Data Analysis Dashboard", description="The title of the app")
182
- max_file_size: int = Field(200, description="Maximum file size in MB")
183
-
184
- # Create an instance of the config
185
- config = AppConfig()
186
-
187
- # Main App
188
- st.title(config.title)
189
-
190
- # Data Upload and Preprocessing Section
191
- st.header("1. Data Upload and Preprocessing")
192
- uploaded_file = st.file_uploader("Choose a CSV file", type="csv")
193
-
194
- if uploaded_file is not None:
195
- file_size = uploaded_file.size / (1024 * 1024) # Convert to MB
196
- if file_size > config.max_file_size:
197
- st.error(f"File size exceeds the maximum limit of {config.max_file_size}MB.")
198
- else:
199
- data = load_data(uploaded_file)
200
- if data is not None:
201
- st.session_state.original_data = data.copy()
202
- st.success("Data loaded successfully!")
203
-
204
- # Remove rows with any null values
205
- data = remove_nan(data)
206
- st.session_state.data = data
207
-
208
- with st.expander("View Data Sample"):
209
- st.write(data.head())
210
-
211
- with st.expander("View Data Overview"):
212
- st.write("Data Shape:", data.shape)
213
- st.write("Column Info:")
214
- st.write(data.dtypes)
215
- st.write("Summary Statistics:")
216
- st.write(data.describe())
217
-
218
- st.success(f"Rows with NaN values have been removed. New data shape: {data.shape}")
219
-
220
- # Data Visualization Section
221
- if st.session_state.data is not None:
222
- st.header("2. Data Visualization")
223
- column_types = get_column_types(st.session_state.data)
224
-
225
- chart_types = ["Scatter Plot", "Line Chart", "Bar Chart", "Box Plot", "Histogram", "Heatmap", "3D Scatter", "Violin Plot"]
226
- visualizations = {}
227
 
228
- for chart_type in chart_types:
229
- st.subheader(chart_type)
230
- col1, col2 = st.columns(2)
231
- with col1:
232
- x_column = st.selectbox(f"Select X-axis for {chart_type}", column_types['numeric'] + column_types['categorical'], key=f"x_{chart_type}")
233
- with col2:
234
- y_column = st.selectbox(f"Select Y-axis for {chart_type}", column_types['numeric'], key=f"y_{chart_type}")
235
 
236
- if chart_type == "Scatter Plot":
237
- fig = px.scatter(st.session_state.data, x=x_column, y=y_column, title=f"{x_column} vs {y_column}")
238
- elif chart_type == "Line Chart":
239
- fig = px.line(st.session_state.data, x=x_column, y=y_column, title=f"{x_column} vs {y_column}")
240
- elif chart_type == "Bar Chart":
241
- fig = px.bar(st.session_state.data, x=x_column, y=y_column, title=f"{x_column} vs {y_column}")
242
- elif chart_type == "Box Plot":
243
- fig = px.box(st.session_state.data, x=x_column, y=y_column, title=f"{x_column} vs {y_column}")
244
- elif chart_type == "Histogram":
245
- fig = px.histogram(st.session_state.data, x=x_column, title=f"Histogram of {x_column}")
246
- elif chart_type == "Heatmap":
247
- corr = st.session_state.data[column_types['numeric']].corr()
248
- fig = px.imshow(corr, title="Correlation Heatmap")
249
- elif chart_type == "3D Scatter":
250
- z_column = st.selectbox(f"Select Z-axis for {chart_type}", column_types['numeric'], key=f"z_{chart_type}")
251
- fig = px.scatter_3d(st.session_state.data, x=x_column, y=y_column, z=z_column, title=f"3D Scatter: {x_column} vs {y_column} vs {z_column}")
252
- else: # Violin Plot
253
- fig = px.violin(st.session_state.data, x=x_column, y=y_column, title=f"Violin Plot: {x_column} vs {y_column}")
254
-
255
- fig.update_layout(
256
- plot_bgcolor='rgba(0,0,0,0)',
257
- paper_bgcolor='rgba(0,0,0,0)',
258
- font_color='#FFFFFF'
259
- )
260
- st.plotly_chart(fig, use_container_width=True)
261
-
262
- # Save the plot for PDF
263
- img_bytes = fig.to_image(format="png")
264
- visualizations[chart_type] = io.BytesIO(img_bytes)
265
-
266
- # Model Training Section
267
- if st.session_state.data is not None:
268
- st.header("3. Model Training and Evaluation")
269
-
270
- col1, col2, col3 = st.columns(3)
271
- with col1:
272
- target_column = st.selectbox("Select target column", column_types['numeric'])
273
- with col2:
274
- features = st.multiselect("Select features", column_types['numeric'], default=column_types['numeric'])
275
- st.session_state.features = features
276
- with col3:
277
- model_type = st.selectbox("Select model type", ["Random Forest Regressor", "Linear Regression", "SVR", "Random Forest Classifier", "Logistic Regression", "SVC"])
278
-
279
- # Model parameters
280
- st.subheader("Model Parameters")
281
- if model_type == "Random Forest Regressor" or model_type == "Random Forest Classifier":
282
- n_estimators = st.slider("Number of estimators", 10, 200, 100)
283
- max_depth = st.slider("Max depth", 1, 20, 5)
284
- params = {"n_estimators": n_estimators, "max_depth": max_depth}
285
- elif model_type == "Linear Regression":
286
- params = {} # Linear Regression doesn't have hyperparameters to tune
287
- elif model_type == "SVR" or model_type == "SVC":
288
- C = st.slider("C (Regularization parameter)", 0.01, 10.0, 1.0)
289
- kernel = st.selectbox("Kernel", ["rbf", "linear", "poly"])
290
- params = {"C": C, "kernel": kernel}
291
- else: # Logistic Regression
292
- C = st.slider("C (Regularization parameter)", 0.01, 10.0, 1.0)
293
- params = {"C": C}
294
-
295
- if st.button("Train Model", key="train_model"):
296
- X = st.session_state.data[features]
297
- y = st.session_state.data[target_column]
298
-
299
- with st.spinner("Training model..."):
300
- model, scaler, metric, r2, report = train_model(X, y, model_type, params)
301
- if model is not None:
302
- st.session_state.model = model
303
- st.session_state.scaler = scaler
304
- st.success("Model trained successfully!")
305
-
306
- model_results = {}
307
- if model_type in ["Random Forest Regressor", "Linear Regression", "SVR"]:
308
- st.metric("Mean Squared Error", f"{metric:.4f}")
309
- st.metric("R-squared Score", f"{r2:.4f}")
310
- model_results["Mean Squared Error"] = f"{metric:.4f}"
311
- model_results["R-squared Score"] = f"{r2:.4f}"
312
- else:
313
- st.metric("Accuracy", f"{metric:.4f}")
314
- st.text("Classification Report:")
315
- st.text(report)
316
- model_results["Accuracy"] = f"{metric:.4f}"
317
- model_results["Classification Report"] = report
318
-
319
- if hasattr(model, 'feature_importances_'):
320
- importance = model.feature_importances_
321
- feature_importance = pd.DataFrame({'Feature': features, 'Importance': importance})
322
- feature_importance = feature_importance.sort_values('Importance', ascending=False).reset_index(drop=True)
323
- st.subheader("Feature Importance")
324
- # Use Streamlit's native table display
325
- st.table(feature_importance)
326
- # Save feature importance as a table for PDF
327
- fig_importance = go.Figure(data=[go.Table(
328
- header=dict(values=list(feature_importance.columns),
329
- fill_color='paleturquoise',
330
- align='left'),
331
- cells=dict(values=[feature_importance.Feature, feature_importance.Importance],
332
- fill_color='lavender',align='left'))
333
- ])
334
- img_bytes = fig_importance.to_image(format="png")
335
- visualizations["Feature Importance"] = io.BytesIO(img_bytes)
336
-
337
- # Save model and scaler
338
- model_pickle, scaler_pickle = save_model(model, scaler)
339
- st.markdown(create_download_link(model_pickle, "trained_model.pkl"), unsafe_allow_html=True)
340
- st.markdown(create_download_link(scaler_pickle, "scaler.pkl"), unsafe_allow_html=True)
341
-
342
- # Generate PDF report
343
- pdf_buffer = create_pdf(st.session_state.data, visualizations, model_results)
344
- st.markdown(create_download_link(pdf_buffer, "data_analysis_report.pdf"), unsafe_allow_html=True)
345
-
346
- # Store model info for comparison
347
- st.session_state.models[model_type] = {
348
- 'model': model,
349
- 'scaler': scaler,
350
- 'metric': metric,
351
- 'r2': r2
352
- }
353
-
354
- # Prediction Section
355
- if st.session_state.model is not None and st.session_state.scaler is not None:
356
- st.header("4. Make Predictions")
357
-
358
- with st.expander("Enter values for prediction"):
359
- input_data = {}
360
- col1, col2 = st.columns(2)
361
- for i, feature in enumerate(st.session_state.features):
362
- with col1 if i % 2 == 0 else col2:
363
- input_data[feature] = st.number_input(f"Enter value for {feature}", value=float(st.session_state.data[feature].mean()))
364
 
365
- if st.button("Predict", key="make_prediction"):
366
- input_df = pd.DataFrame([input_data])
367
- input_scaled = st.session_state.scaler.transform(input_df)
368
- prediction = st.session_state.model.predict(input_scaled)
369
- st.success(f"Predicted value: {prediction[0]:.4f}")
370
-
371
- # Visualize prediction
372
- fig = go.Figure()
373
- fig.add_trace(go.Indicator(
374
- mode="number+delta",
375
- value=prediction[0],
376
- delta={'reference': st.session_state.data[target_column].mean(), 'relative': True},
377
- title={'text': "Prediction vs Mean"},
378
- domain={'x': [0, 1], 'y': [0, 1]}
379
- ))
380
- fig.update_layout(
381
- paper_bgcolor='rgba(0,0,0,0)',
382
- plot_bgcolor='rgba(0,0,0,0)',
383
- font_color='#FFFFFF'
384
- )
385
- st.plotly_chart(fig, use_container_width=True)
386
 
387
- # Model Comparison
388
- if len(st.session_state.models) > 1:
389
- st.header("5. Model Comparison")
390
-
391
- comparison_data = []
392
- for model_name, model_info in st.session_state.models.items():
393
- if model_info['r2'] is not None:
394
- comparison_data.append({
395
- 'Model': model_name,
396
- 'Metric': 'R-squared',
397
- 'Value': model_info['r2']
398
- })
399
- comparison_data.append({
400
- 'Model': model_name,
401
- 'Metric': 'MSE' if model_info['r2'] is not None else 'Accuracy',
402
- 'Value': model_info['metric']
403
- })
404
-
405
- comparison_df = pd.DataFrame(comparison_data)
406
- fig = px.bar(comparison_df, x='Model', y='Value', color='Metric', barmode='group',
407
- title='Model Comparison')
408
- fig.update_layout(
409
- paper_bgcolor='rgba(0,0,0,0)',
410
- plot_bgcolor='rgba(0,0,0,0)',
411
- font_color='#FFFFFF'
412
- )
413
- st.plotly_chart(fig, use_container_width=True)
414
-
415
- # Footer
416
- st.markdown("---")
417
- st.info("Comprehensive Data Analysis Dashboard v3.0")
418
-
419
- if __name__ == "__main__":
420
- st.sidebar.title("About")
421
- st.sidebar.info(
422
- "This dashboard allows you to upload data, preprocess it, visualize it, "
423
- "train machine learning models, make predictions, and compare different models. "
424
- "You can also download the trained model, scaler, and a PDF report of your analysis."
425
- )
426
- st.sidebar.title("Instructions")
427
- st.sidebar.info(
428
- "1. Upload your CSV file\n"
429
- "2. NaN values will be automatically removed\n"
430
- "3. Explore the data visualizations\n"
431
- "4. Train a model by selecting features and model type\n"
432
- "5. Make predictions using the trained model\n"
433
- "6. Compare different models (if multiple models are trained)\n"
434
- "7. Download the trained model, scaler, and PDF report"
435
- )
 
1
+ import streamlit as st
2
  import pandas as pd
3
  import numpy as np
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4
 
5
+ def load_data(uploaded_file):
6
+ file_extension = upload_file.name.split(".")[-1].lower()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7
 
8
+ if file_extension == "csv":
9
+ pd.read_csv(uploaded_file)
 
 
 
 
 
10
 
11
+ elif file_extension in ["xls","xlxs"]:
12
+ pd.read_excel(uploaded_file)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
13
 
14
+ elif file_extension == "xml":
15
+ pd.read_xml(uploaded_file)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
16
 
17
+ elif file_extension == "txt":
18
+ pd.read_csv(uploaded_file , delimiter = "\t" , header = None )
19
+ else :
20
+ st.error("unsupported format")
21
+ return None
22
+