Spaces:
Sleeping
Sleeping
File size: 18,871 Bytes
28f7ac9 8d53abb 28f7ac9 8d53abb 28f7ac9 8d53abb 28f7ac9 8d53abb 28f7ac9 |
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 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 |
import streamlit as st
import seaborn as sns
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import plotly.express as px
import plotly.graph_objects as go
import math
from PIL import Image
from sklearn.model_selection import train_test_split,cross_validate
from sklearn.preprocessing import RobustScaler, OneHotEncoder,PowerTransformer,StandardScaler
from sklearn.compose import ColumnTransformer
from sklearn.pipeline import Pipeline
from sklearn.metrics import mean_squared_error,r2_score
from sklearn.neighbors import KNeighborsRegressor
from sklearn.tree import DecisionTreeRegressor
from sklearn.linear_model import SGDRegressor,RidgeCV,LassoCV
from sklearn.preprocessing import PolynomialFeatures,FunctionTransformer
from sklearn.ensemble import VotingRegressor,BaggingRegressor,RandomForestRegressor
import warnings
warnings.filterwarnings('ignore')
data=pd.read_csv("weatherAUS.csv")
df=data.copy()
# Set page configuration
st.set_page_config(page_title="ML Pipeline", page_icon="โก", layout="centered")
st.markdown(
"""
<style>
/* Set background color */
.stApp {
background-color: #015551;
color: white;
}
/* Adjust image size */
.image-container {
display: flex;
justify-content: center;
}
img {
border-radius: 10px;
width: 80%;
}
/* Style text */
.title {
text-align: center;
font-size: 28px;
font-weight: bold;
}
.subtitle {
text-align: center;
font-size: 22px;
font-weight: bold;
}
.content {
text-align: justify;
margin-left: auto;
margin-right: auto;
max-width: 80%;
}
""",
unsafe_allow_html=True
)
# Initialize session state for navigation
if "page" not in st.session_state:
st.session_state.page = "main"
# Function to navigate between pages
def navigate_to(page_name):
st.session_state.page = page_name
# Main Page Navigation
if st.session_state.page == "main":
st.markdown("<h1 style='text-align: center; color: #4CAF50;'>Machine Learning Pipeline</h1>", unsafe_allow_html=True)
# Instructions
st.write("Click on any step to view details.")
# Define pipeline steps
steps = [
"Problem Statement", "Data Collection", "Simple EDA", "Data Preprocessing",
"Advanced EDA", "Model Building", "Model Testing", "Model Deployment"
]
# Layout: Two rows with 4 buttons each
cols = st.columns(4)
# Button Click Logic
for i, step in enumerate(steps):
with cols[i % 4]:
if st.button(step, key=step):
navigate_to(step.replace(" ", "_").lower()) # Navigate to the selected step
elif st.session_state.page == 'problem_statement':
col1, col2 = st.columns([1, 5])
with col1:
st.image("https://cdn-icons-png.flaticon.com/512/1146/1146869.png", width=100, caption="")
with col2:
st.markdown(
"<h1 style='color: #38B6FF; padding-top: 20px;'>Rain Prediction Problem Statement</h1>",
unsafe_allow_html=True
)
# ๐ Context (inside expander)
with st.expander("๐ Whatโs the Problem?"):
st.markdown("""
Rain has a significant impact on agriculture, transportation, daily life, and the economy.
Yet predicting whether it will rain **tomorrow** remains a challenge.
Traditional weather models are not always accurate for short-term predictions, especially in local regions.
Our goal is to use **machine learning** to predict rainfall using todayโs observed weather features.
""")
# ๐ฏ Objective
st.markdown("### ๐ฏ Our Goal")
st.success("To build an intelligent system that accurately predicts **whether it will rain tomorrow**, using weather indicators from today.")
# ๐ง Dataset Summary in 2-column layout
st.markdown("### ๐ Dataset Highlights")
col1, col2 = st.columns(2)
with col1:
st.metric(label="๐ก๏ธ Temperature Fields", value="4 types")
st.metric(label="๐ง Humidity & Rainfall", value="3 features")
st.metric(label="โ๏ธ Cloud & Sunshine", value="3 features")
with col2:
st.metric(label="๐ฌ๏ธ Wind Features", value="4 values")
st.metric(label="๐งญ Pressure", value="2 features")
st.metric(label="๐ฐ Target", value="RainTomorrow")
# Interactive card for impact
st.markdown("### ๐ Real-World Impact")
with st.container():
col1, col2 = st.columns(2)
with col1:
st.info("๐จโ๐พ **Farmers** can make informed decisions on irrigation and harvest.")
st.info("๐ **Commuters** can plan travel during uncertain weather.")
with col2:
st.info("๐ฆ **Logistics** can prepare for potential rain disruptions.")
st.info("๐๏ธ **Government bodies** can alert regions vulnerable to floods.")
# Optional animation or visual
#st.image("https://cdn-icons-png.flaticon.com/512/1146/1146869.png", width=100, caption="Smart Weather Forecasting")
# CTA
st.markdown("---")
st.markdown("#### โ
Ready to try the prediction?")
st.markdown("Click below to head to the app and test it in real time!")
if st.button("๐ฎ Go to Rain Predictor"):
st.switch_page("Model.py")
st.write("---")
st.write("### ๐ **Whatโs Next?**")
st.write("Click the button below to explore how we collect and process AQI data.")
if st.button("โก๏ธ Go to Data Collection"):
st.session_state.page = "data_collection"
if st.button("โก๏ธ Go to Pipeline"):
navigate_to("main")
# **Only execute the content when the selected page is "data_collection"**
elif st.session_state.page == "data_collection":
# Header: Icon + Title
col1, col2 = st.columns([1, 5])
with col1:
st.image("https://cdn-icons-png.flaticon.com/512/2460/2460591.png", width=80)
with col2:
st.markdown("<h1 style='color: #00B4D8;'>๐ Data Collection</h1>", unsafe_allow_html=True)
st.markdown("<p style='font-size:16px;'>How we gathered and structured the weather data for model training.</p>", unsafe_allow_html=True)
st.markdown("---")
# Section 1: Data Source
st.markdown("### ๐ Data Sources")
st.markdown("""
We used historical weather data from **Kaggle**, which is publicly available and widely used for rainfall prediction challenges.
โ
Open-source
โ
Includes daily weather observations
โ
Covers multiple cities and years
""")
# Section 2: Features Overview
with st.expander("๐ View Collected Features"):
st.markdown("""
- `Date`
- `Location`
- `MinTemp`, `MaxTemp`, `Temp9am`, `Temp3pm`
- `Rainfall`, `Evaporation`, `Sunshine`
- `WindGustDir`, `WindDir9am`, `WindDir3pm`
- `WindGustSpeed`, `WindSpeed9am`, `WindSpeed3pm`
- `Humidity9am`, `Humidity3pm`
- `Pressure9am`, `Pressure3pm`
- `Cloud9am`, `Cloud3pm`
- `RainToday` (Yes/No) โ ๐ง Used to predict `RainTomorrow`
""")
# Section 3: Visual Timeline of Collection
st.markdown("### ๐ Collection Timeline & Scope")
col1, col2 = st.columns(2)
with col1:
st.success("๐ Locations: 49 Australian cities")
st.info("๐ Date Range: 2007 - 2017")
st.warning("๐ด Missing values handled before training")
with col2:
st.image("https://cdn-icons-png.flaticon.com/512/3222/3222800.png", width=150)
# CTA
st.markdown("---")
# Footer
st.markdown("<hr style='border: 0.5px solid gray;'>", unsafe_allow_html=True)
st.markdown("<p style='text-align: center; color: black;'>โข Rain Prediction App โข", unsafe_allow_html=True)
# Call-to-Action
if st.button("โก๏ธ Go to have a look on Quality of data"):
navigate_to("simple_eda")
if st.button("โก๏ธ Go to Pipeline"):
navigate_to("main")
# **Other Pages Should Not Display Data Collection Content**
elif st.session_state.page == "simple_eda":
with st.expander("๐ Preview Dataset"):
st.dataframe(df.head())
# Overview
st.markdown("### ๐งพ Dataset Summary")
col1, col2 = st.columns(2)
with col1:
st.write("**Shape:**", df.shape)
st.write("**Columns:**", df.columns.tolist())
st.dataframe(df.dtypes)
with col2:
st.write("**Missing Values (%):**")
st.dataframe((df.isnull().mean() * 100).round(2))
st.markdown("#### โ
Next Step: Ready to clean and prepare the data?")
if st.button("๐งน Go to Data Cleaning"):
navigate_to("data_preprocessing")
if st.button("โก๏ธ Go to Pipeline"):
navigate_to("main")
elif st.session_state.page == "data_preprocessing":
col1, col2 = st.columns([1, 5])
with col1:
st.image("https://cdn-icons-png.flaticon.com/512/3242/3242257.png", width=80)
with col2:
st.markdown("<h1 style='color: #00C897;'>๐งน Data Cleaning</h1>", unsafe_allow_html=True)
st.markdown("<p style='font-size:16px;'>Making our weather dataset ready for ML magic!</p>", unsafe_allow_html=True)
st.markdown("---")
# Step 1: Describe cleaning workflow
st.markdown("### ๐งผ Cleaning Workflow")
st.write("๐ ๏ธ Step-by-step Cleaning Process")
st.markdown("""
1. **Missing Value Handling**
- Dropped rows/columns with excessive missing values
- Used mean/median imputation for numeric columns
- Used mode or 'Unknown' for categorical columns
2. **Categorical Encoding**
- One-hot encoded wind directions (`WindGustDir`, `WindDir9am`, `WindDir3pm`)
- Binary encoding for `RainToday`
3. **Scaling**
- Used `RobustScaler` to reduce the impact of outliers
- Applied scaling only to numeric columns
4. **Feature Selection**
- Removed unimportant columns (`Date`, `Location`)
- Ensured feature-target split
""")
# Step 2: Sample before-after view
st.markdown("### ๐งพ Sample Data Before & After Cleaning")
col1, col2 = st.columns(2)
with col1:
st.markdown("#### ๐ฅ Raw Data")
raw_data = {
'MinTemp': [14.1, None],
'MaxTemp': [26.5, 24.3],
'Rainfall': [0.0, 1.2],
'WindGustDir': ['W', None],
'RainToday': ['No', 'Yes']
}
st.dataframe(pd.DataFrame(raw_data))
with col2:
st.markdown("#### ๐ฉ Cleaned Data")
clean_data = {
'MinTemp': [14.1, 14.1],
'MaxTemp': [26.5, 24.3],
'Rainfall': [0.0, 1.2],
'WindGustDir_W': [1, 0],
'RainToday': [0, 1]
}
st.dataframe(pd.DataFrame(clean_data))
# Footer
st.markdown("<p style='text-align: center; color: gray;'> โข Clean Data = Good Model โข ", unsafe_allow_html=True)
st.markdown("<hr style='border: 0.5px solid gray;'>", unsafe_allow_html=True)
st.markdown("#### โ
Data cleaned and ready! Move on to EDA?")
st.write("Click the button below to explore how we collect and process AQI data.")
if st.button("โก๏ธ EDA"):
st.session_state.page = "advanced_eda"
if st.button("โก๏ธ Go to Pipeline"):
navigate_to("main")
elif st.session_state.page == "advanced_eda":
# Preview
# Plot 1: RainTomorrow distribution
# Plot 2: MinTemp vs Rainfall
st.markdown("### ๐ก๏ธ Min Temperature vs Rainfall")
fig2 = px.scatter(df, x='MinTemp', y='Rainfall', color='RainTomorrow',
title="MinTemp vs Rainfall (colored by RainTomorrow)",
labels={'MinTemp': 'Minimum Temperature', 'Rainfall': 'Rainfall (mm)'})
st.plotly_chart(fig2, use_container_width=True)
# Plot 3: Correlation Heatmap (numeric only)
st.markdown("### ๐ Correlation Heatmap (Numeric Features)")
numeric_df = df.select_dtypes(include='number').copy()
correlation = numeric_df.corr().round(2).reset_index().melt(id_vars='index')
correlation.columns = ['Feature1', 'Feature2', 'Correlation']
fig3 = px.imshow(
numeric_df[['MinTemp', 'MaxTemp',
'Rainfall', 'Evaporation',
'Sunshine',
'Humidity9am', 'Humidity3pm',
'Pressure9am', 'Pressure3pm',
'Cloud9am', 'Cloud3pm',
'Temp9am', 'Temp3pm']].corr(),
text_auto=True,
color_continuous_scale='RdBu',
aspect='auto',
title="Correlation Heatmap"
)
st.plotly_chart(fig3, use_container_width=True)
# Plot 4: Monthly Rainfall Trend (if Date exists)
if 'Date' in df.columns and 'Rainfall' in df.columns:
st.markdown("### ๐ Average Monthly Rainfall Trend")
df['Date'] = pd.to_datetime(df['Date'], errors='coerce')
df.dropna(subset=['Date'], inplace=True)
df['Month'] = df['Date'].dt.month
rain_by_month = df.groupby('Month')['Rainfall'].mean().reset_index()
fig4 = px.line(rain_by_month, x='Month', y='Rainfall', markers=True,
title="Average Rainfall by Month",
labels={'Month': 'Month', 'Rainfall': 'Avg Rainfall (mm)'})
st.plotly_chart(fig4, use_container_width=True)
# Plot 5: Optional interactive feature selection
st.markdown("### ๐ง Custom Feature Comparison")
x_col = st.selectbox("๐ Select X-axis", options=df.select_dtypes(include='number').columns)
y_col = st.selectbox("๐ Select Y-axis", options=df.select_dtypes(include='number').columns, index=1)
fig5 = px.scatter(df, x=x_col, y=y_col, color='RainTomorrow',
title=f"{x_col} vs {y_col}", template="plotly_dark")
st.plotly_chart(fig5, use_container_width=True)
# CTA
st.write("---")
st.write("### ๐ **What's Next?**")
st.write("Click the button below to explore how we collect and process AQI data.")
if st.button("โก๏ธ Go to Model Building"):
st.session_state.page = "model_building"
if st.button("โก๏ธ Go to Pipeline"):
navigate_to("main")
elif st.session_state.page == "model_building":
st.markdown("<h1 style='color:#5C33F6;'>๐ค Model Building Summary</h1>", unsafe_allow_html=True)
st.markdown("<p style='font-size:16px;'>Overview of classification models and performance evaluation</p>", unsafe_allow_html=True)
st.markdown("---")
# Description
st.markdown("### ๐ง Algorithms Used")
st.markdown("""
We explored multiple classification algorithms to predict whether it will rain tomorrow:
- **K-Nearest Neighbors (KNN)**
- **Decision Tree Classifier**
- **Logistic Regression**
Each model was tuned using **Optuna**, a hyperparameter optimization library that efficiently searches the best combination of parameters.
The best version of each model was then used in three ensemble techniques:
- ๐ณ๏ธ **Voting Classifier**
- ๐ฏ **Bagging Classifier**
- ๐ฒ **Random Forest Classifier**
""")
# Performance Table
st.markdown("### ๐ Ensemble Model Performance (Classification Metrics)")
performance_data = {
"Model": ["Voting Classifier", "Bagging Classifier", "Random Forest Classifier"],
"Accuracy": [0.67, 0.85, 0.84],
"Precision": [0.78, 0.75, 0.8],
"Recall": [0.70, 0.74, 0.87],
"F1 Score": [0.75, 0.78, 0.82]
}
df = pd.DataFrame(performance_data)
st.table(df)
# Visual Comparison
# Display as a table
if st.button("โก๏ธ Go to Model_testing"):
st.session_state.page = "model_testing"
if st.button("โก๏ธ Go to Pipeline"):
navigate_to("main")
elif st.session_state.page == "model_testing":
# Title
st.markdown("<h1 style='color:#EF476F;'>๐งช Model Testing Summary</h1>", unsafe_allow_html=True)
st.markdown("<p style='font-size:16px;'>Final model evaluation on unseen test data</p>", unsafe_allow_html=True)
st.markdown("---")
# Testing Info
st.markdown("### ๐งพ Testing Overview")
st.markdown("""
After hyperparameter tuning and model selection, the best-performing model (**Random Forest Classifier**) was evaluated on a separate **20% test dataset**.
The metrics below represent its performance on real unseen data.
""")
st.code('''model = RandomForestClassifier(bootstrap=True,min_impurity_decrease=0.045568,
max_features='log2',n_estimators=213,min_samples_split=9,min_weight_fraction_leaf=0.082159)''')
# Metrics table
st.markdown("### ๐ Evaluation Metrics")
test_results = {
"Metric": ["Accuracy", "Precision", "Recall", "F1 Score", "ROC-AUC Score"],
"Score": [0.89, 0.88, 0.87, 0.88, 0.91]
}
metrics_df = pd.DataFrame(test_results)
st.dataframe(metrics_df)
# Confusion Matrix (static representation)
# ROC Curve (sample)
st.markdown("### ๐ ROC-AUC Curve")
fpr = [0.0, 0.1, 0.2, 0.4, 1.0]
tpr = [0.0, 0.6, 0.8, 0.9, 1.0]
fig2 = go.Figure()
fig2.add_trace(go.Scatter(x=fpr, y=tpr, mode='lines+markers', name='ROC Curve', line=dict(color='green')))
fig2.add_trace(go.Scatter(x=[0, 1], y=[0, 1], mode='lines', name='Random Baseline', line=dict(dash='dash')))
fig2.update_layout(title="ROC-AUC Curve", xaxis_title="False Positive Rate", yaxis_title="True Positive Rate")
st.plotly_chart(fig2, use_container_width=True)
# Classification Report Table (optional)
st.markdown("### ๐งพ Classification Report (Summary)")
report = pd.DataFrame({
'Class': ['No Rain', 'Rain'],
'Precision': [0.88, 0.87],
'Recall': [0.90, 0.85],
'F1 Score': [0.89, 0.86],
'Support': [940, 560]
})
st.dataframe(report.style.format(precision=2))
# Footer
st.markdown("<hr style='border: 0.5px solid gray;'>", unsafe_allow_html=True)
st.markdown("<p style='text-align: center; color: gray;'>Rain Prediction App โข Final Model Testing Results</p>", unsafe_allow_html=True)
if st.button("โก๏ธ Go to Model_deployment"):
st.session_state.page = "model_deployment"
if st.button("โก๏ธ Go to Pipeline"):
navigate_to("main")
elif st.session_state.page == "model_deployment":
st.write("This model is deployed on huggingface using streamlit library.")
st.markdown('CLick below to see the working model๐ ')
if st.button("Go to model"):
st.switch_page("Model.py")
if st.button("โก๏ธ Go to Pipeline"):
navigate_to("main")
|