Delete models/ppa.py
Browse files- models/ppa.py +0 -427
models/ppa.py
DELETED
|
@@ -1,427 +0,0 @@
|
|
| 1 |
-
import streamlit as st
|
| 2 |
-
import streamlit.components.v1 as components
|
| 3 |
-
import pandas as pd
|
| 4 |
-
import numpy as np
|
| 5 |
-
import joblib
|
| 6 |
-
import plotly.graph_objects as go
|
| 7 |
-
from feature_pipeline import create_features
|
| 8 |
-
from sklearn.metrics import r2_score, mean_squared_error, mean_absolute_error
|
| 9 |
-
|
| 10 |
-
# --- 1. PAGE CONFIGURATION ---
|
| 11 |
-
st.set_page_config(
|
| 12 |
-
page_title="Group 5 Hanoi Weather Hub",
|
| 13 |
-
page_icon="☀️",
|
| 14 |
-
layout="wide"
|
| 15 |
-
)
|
| 16 |
-
|
| 17 |
-
# --- CONSTANTS ---
|
| 18 |
-
PLOT_COLORS = {'past': '#005aa7', 'forecast': "#1547eb", 'actual': "#d0b51b"}
|
| 19 |
-
|
| 20 |
-
# --- FEATURE DESCRIPTIONS (50 FEATURES) ---
|
| 21 |
-
FEATURE_DESCRIPTIONS = {
|
| 22 |
-
'cos_day_of_year': "Cosine of the day of the year. Captures the main seasonal cycle.",
|
| 23 |
-
'temp': "The average temperature of the current day (°C). The most important feature.",
|
| 24 |
-
'temp_ewm_14': "14-day Exponentially Weighted Moving Average of temperature.",
|
| 25 |
-
'season_Winter': "A binary flag (1 if Winter, 0 otherwise).",
|
| 26 |
-
'winddir_cos': "Cosine of the wind direction. Helps model understand east vs. west wind components.",
|
| 27 |
-
'temp_ewm_7': "7-day Exponentially Weighted Moving Average of temperature.",
|
| 28 |
-
'temp_ewm_30': "30-day Exponentially Weighted Moving Average of temperature.",
|
| 29 |
-
'temp_diff_1': "Difference between today's and yesterday's temperature.",
|
| 30 |
-
'sin_day_of_year': "Sine of the day of the year. Pinpoints the exact time of year.",
|
| 31 |
-
'solarradiation': "Amount of solar energy received. A primary driver of heat.",
|
| 32 |
-
'windgust': "The highest instantaneous wind speed recorded during the day (km/h).",
|
| 33 |
-
'windspeed': "The average wind speed for the day (km/h).",
|
| 34 |
-
'wind_vector_ew': "East-West wind vector component, calculated from wind speed and direction.",
|
| 35 |
-
'temp_diff_7': "The difference in temperature compared to 7 days ago.",
|
| 36 |
-
'fft_sin_freq_1': "A cyclical feature from Fourier analysis for a dominant cycle.",
|
| 37 |
-
'temp_roll_min_3': "The minimum temperature recorded over the past 3 days.",
|
| 38 |
-
'fft_sin_freq_2': "A cyclical feature for the second most dominant cycle.",
|
| 39 |
-
'humidity_lag_9': "Humidity from 9 days ago.",
|
| 40 |
-
'windspeed_diff_7': "The difference in wind speed compared to 7 days ago.",
|
| 41 |
-
'humidity_ewm_30': "30-day Exponentially Weighted Moving Average of humidity.",
|
| 42 |
-
'day_of_month': "The day of the month (1-31).",
|
| 43 |
-
'temp_roll_min_7': "The minimum temperature recorded over the past 7 days.",
|
| 44 |
-
'precip_ewm_30': "30-day Exponentially Weighted Moving Average of precipitation.",
|
| 45 |
-
'humidity_ewm_14': "14-day Exponentially Weighted Moving Average of humidity.",
|
| 46 |
-
'humidity': "The relative humidity of the air (%).",
|
| 47 |
-
'temp_range': "Difference between the daily max (tempmax) and min (tempmin) temperature.",
|
| 48 |
-
'temp_resid_yearly': "The residual (noise) component from temperature's seasonal decomposition.",
|
| 49 |
-
'humidity_roll_std_7': "7-day rolling standard deviation of humidity.",
|
| 50 |
-
'fft_cos_freq_1': "A cyclical feature paired with fft_sin_freq_1.",
|
| 51 |
-
'windspeed_roll_min_30': "The minimum wind speed recorded in the past 30 days.",
|
| 52 |
-
'precipcover': "Percentage of the day with precipitation cover.",
|
| 53 |
-
'windspeed_lag_7': "Wind speed from 7 days ago.",
|
| 54 |
-
'precip_diff_1': "Difference between today's and yesterday's precipitation.",
|
| 55 |
-
'season_Spring': "A binary flag (1 if Spring, 0 otherwise).",
|
| 56 |
-
'precip_lag_3': "Precipitation from 3 days ago.",
|
| 57 |
-
'temp_lag_1': "The average temperature from the previous day.",
|
| 58 |
-
'precip_diff_7': "The difference in precipitation compared to 7 days ago.",
|
| 59 |
-
'precip': "The amount of precipitation (rain) recorded (mm).",
|
| 60 |
-
'cloudcover_roll_std_3': "3-day rolling standard deviation of cloud cover.",
|
| 61 |
-
'season_Fall': "A binary flag (1 if Fall, 0 otherwise).",
|
| 62 |
-
'windspeed_ewm_30': "30-day Exponentially Weighted Moving Average of wind speed.",
|
| 63 |
-
'precip_roll_min_3': "The minimum precipitation recorded in the past 3 days.",
|
| 64 |
-
'cloudcover_roll_std_30': "30-day rolling standard deviation of cloud cover.",
|
| 65 |
-
'precipprob': "The probability of precipitation occurring (%).",
|
| 66 |
-
'temp_roll_std_3': "3-day rolling standard deviation of temperature.",
|
| 67 |
-
'humidity_diff_7': "The difference in humidity compared to 7 days ago.",
|
| 68 |
-
'windspeed_roll_std_3': "3-day rolling standard deviation of wind speed.",
|
| 69 |
-
'windspeed_lag_3': "Wind speed from 3 days ago.",
|
| 70 |
-
'humidity_roll_std_3': "3-day rolling standard deviation of humidity.",
|
| 71 |
-
'icon_clear-day': "A binary flag if the weather icon was 'clear-day'."
|
| 72 |
-
}
|
| 73 |
-
|
| 74 |
-
# --- 2. CUSTOM CSS FOR STYLING ---
|
| 75 |
-
def load_css():
|
| 76 |
-
# This block contains your original CSS to keep the UI consistent.
|
| 77 |
-
st.markdown("""
|
| 78 |
-
<style>
|
| 79 |
-
/* ===== Background gradient ===== */
|
| 80 |
-
[data-testid="stAppViewContainer"] {
|
| 81 |
-
background-image: linear-gradient(to bottom, #d4e1da 20%, #005aa7 100%) !important;
|
| 82 |
-
background-attachment: fixed !important;
|
| 83 |
-
background-size: cover !important;
|
| 84 |
-
}
|
| 85 |
-
/* ===== Global text ===== */
|
| 86 |
-
.stApp, h1, h2, h3, p, label {
|
| 87 |
-
color: #0A1931;
|
| 88 |
-
}
|
| 89 |
-
/* ===== Tabs ===== */
|
| 90 |
-
button[data-baseweb="tab"][aria-selected="true"] {
|
| 91 |
-
background-color: #FFFFFF !important;
|
| 92 |
-
color: #005aa7 !important;
|
| 93 |
-
padding: 10px 16px !important;
|
| 94 |
-
border-radius: 10px 10px 0 0 !important;
|
| 95 |
-
font-weight: 700 !important;
|
| 96 |
-
border-bottom: 3px solid #e53935 !important;
|
| 97 |
-
}
|
| 98 |
-
button[data-baseweb="tab"][aria-selected="false"] {
|
| 99 |
-
background-color: rgba(255,255,255,0.3) !important;
|
| 100 |
-
color: #284270 !important;
|
| 101 |
-
padding: 10px 16px !important;
|
| 102 |
-
}
|
| 103 |
-
/* ===== Metrics: Forecast titles, main numbers, and Actual (delta) ===== */
|
| 104 |
-
[data-testid="stMetricLabel"] p,
|
| 105 |
-
div[data-testid="stMetricValue"] {
|
| 106 |
-
font-weight: 700 !important;
|
| 107 |
-
text-shadow: 1px 1px 3px rgba(0,0,0,0.3);
|
| 108 |
-
}
|
| 109 |
-
div[data-testid="stMetricLabel"] p:contains("Forecast for") {
|
| 110 |
-
color: #ffffff !important;
|
| 111 |
-
font-size: 2.2rem !important;
|
| 112 |
-
font-weight: 800 !important;
|
| 113 |
-
text-shadow: 1px 1px 3px rgba(0,0,0,0.3);
|
| 114 |
-
background: none !important;
|
| 115 |
-
border: none !important;
|
| 116 |
-
}
|
| 117 |
-
div[data-testid="stMetricValue"] {
|
| 118 |
-
color: #fefefe !important;
|
| 119 |
-
font-size: 1.9rem !important;
|
| 120 |
-
text-shadow: 1px 1px 6px rgba(0,0,0,0.5);
|
| 121 |
-
}
|
| 122 |
-
div[data-testid="stMetricLabel"] p {
|
| 123 |
-
color: #dce9ff !important;
|
| 124 |
-
font-weight: 700 !important;
|
| 125 |
-
letter-spacing: 0.3px;
|
| 126 |
-
}
|
| 127 |
-
div[data-testid="stMetricLabel"] p {
|
| 128 |
-
color: #e8f1ff !important;
|
| 129 |
-
font-size: 1.4rem !important;
|
| 130 |
-
font-weight: 700 !important;
|
| 131 |
-
text-shadow: none !important;
|
| 132 |
-
background: rgba(0, 0, 0, 0.15);
|
| 133 |
-
padding: 4px 8px;
|
| 134 |
-
border-radius: 6px;
|
| 135 |
-
}
|
| 136 |
-
div[data-testid="stMetricValue"] {
|
| 137 |
-
color: #ffffff !important;
|
| 138 |
-
font-size: 1.8rem !important;
|
| 139 |
-
text-shadow: 0 0 3px rgba(0,0,0,0.3);
|
| 140 |
-
background: rgba(0,0,0,0.15);
|
| 141 |
-
border-radius: 6px;
|
| 142 |
-
padding: 6px 10px;
|
| 143 |
-
}
|
| 144 |
-
div[data-testid="stMetricValue"] {
|
| 145 |
-
color: #fefefe !important;
|
| 146 |
-
font-size: 1.4rem !important;
|
| 147 |
-
text-shadow: 1px 1px 6px rgba(0,0,0,0.5);
|
| 148 |
-
}
|
| 149 |
-
div[data-testid="stMetricLabel"] p {
|
| 150 |
-
color: #dce9ff !important;
|
| 151 |
-
font-weight: 700 !important;
|
| 152 |
-
letter-spacing: 0.3px;
|
| 153 |
-
}
|
| 154 |
-
div[data-testid="stMetricValue"],
|
| 155 |
-
div[data-testid="stMetricLabel"] p {
|
| 156 |
-
filter: drop-shadow(0 0 3px rgba(255,255,255,0.4));
|
| 157 |
-
}
|
| 158 |
-
/* ===== Custom feature cards (Tab 2) ===== */
|
| 159 |
-
.custom-card-transparent {
|
| 160 |
-
background: linear-gradient(145deg, rgba(255,255,255,0.12), rgba(0,0,0,0.25));
|
| 161 |
-
border: 1px solid rgba(255,255,255,0.25);
|
| 162 |
-
border-radius: 12px;
|
| 163 |
-
padding: 14px;
|
| 164 |
-
text-align: center;
|
| 165 |
-
transition: all 0.25s ease;
|
| 166 |
-
box-shadow: 0 2px 8px rgba(0,0,0,0.15);
|
| 167 |
-
width: 95%;
|
| 168 |
-
margin: 0 auto;
|
| 169 |
-
}
|
| 170 |
-
.custom-card-transparent:hover {
|
| 171 |
-
transform: translateY(-3px);
|
| 172 |
-
box-shadow: 0 4px 12px rgba(0,0,0,0.25);
|
| 173 |
-
filter: brightness(1.1);
|
| 174 |
-
}
|
| 175 |
-
.custom-card-transparent h2 {
|
| 176 |
-
color: #fefefe !important;
|
| 177 |
-
font-size: 1.6rem !important;
|
| 178 |
-
font-weight: 700 !important;
|
| 179 |
-
text-shadow: 0 0 4px rgba(255,255,255,0.25);
|
| 180 |
-
margin-top: 10px;
|
| 181 |
-
}
|
| 182 |
-
.feature-tag-final {
|
| 183 |
-
background-color: #1c3d70 !important;
|
| 184 |
-
padding: 5px 10px;
|
| 185 |
-
border-radius: 8px;
|
| 186 |
-
font-size: 0.9rem;
|
| 187 |
-
font-weight: 600;
|
| 188 |
-
color: #e3eeff !important;
|
| 189 |
-
text-shadow: 0 0 2px rgba(255,255,255,0.15);
|
| 190 |
-
display: inline-block;
|
| 191 |
-
margin-bottom: 3px;
|
| 192 |
-
}
|
| 193 |
-
/* ===== Restored missing pieces ===== */
|
| 194 |
-
div[data-testid="stExpander"] {
|
| 195 |
-
background-color: rgba(255, 255, 255, 0.85) !important;
|
| 196 |
-
border-radius: 12px !important;
|
| 197 |
-
border: 1px solid rgba(0, 90, 167, 0.25) !important;
|
| 198 |
-
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1) !important;
|
| 199 |
-
margin-top: 2rem;
|
| 200 |
-
}
|
| 201 |
-
div.st-emotion-cache-1e5k5x7 {
|
| 202 |
-
background-color: rgba(230, 240, 255, 0.5) !important;
|
| 203 |
-
border-radius: 15px !important;
|
| 204 |
-
padding: 1rem 0.5rem !important;
|
| 205 |
-
border: 1px solid rgba(255, 255, 255, 0.3);
|
| 206 |
-
box-shadow: 0 4px 12px rgba(0,0,0,0.1);
|
| 207 |
-
margin: 1rem 0;
|
| 208 |
-
}
|
| 209 |
-
div.st-emotion-cache-1e5k5x7 div[data-testid="stMetricValue"] {
|
| 210 |
-
color: white !important;
|
| 211 |
-
text-shadow: 1px 1px 3px rgba(0,0,0,0.4);
|
| 212 |
-
}
|
| 213 |
-
div.st-emotion-cache-1e5k5x7 div[data-testid="stMetricLabel"] p {
|
| 214 |
-
color: #0A1931 !important;
|
| 215 |
-
font-weight: 600 !important;
|
| 216 |
-
}
|
| 217 |
-
button[data-baseweb="tab"][aria-selected="true"] {
|
| 218 |
-
border-bottom: 2px solid rgba(229,57,53,0.9) !important;
|
| 219 |
-
}
|
| 220 |
-
div[data-testid="stMetricLabel"] p:contains("Forecast for") {
|
| 221 |
-
color: #ffffff !important;
|
| 222 |
-
font-size: 2.2rem !important;
|
| 223 |
-
font-weight: 800 !important;
|
| 224 |
-
text-shadow: 1px 1px 3px rgba(0,0,0,0.3);
|
| 225 |
-
background: none !important;
|
| 226 |
-
border: none !important;
|
| 227 |
-
}
|
| 228 |
-
div[data-testid="stMetricValue"] {
|
| 229 |
-
color: #ffffff !important;
|
| 230 |
-
font-size: 2.2rem !important;
|
| 231 |
-
font-weight: 800 !important;
|
| 232 |
-
text-shadow: 2px 2px 5px rgba(0,0,0,0.4);
|
| 233 |
-
background: none !important;
|
| 234 |
-
border: none !important;
|
| 235 |
-
padding: 0 !important;
|
| 236 |
-
}
|
| 237 |
-
[data-testid="stMetricDelta"] {
|
| 238 |
-
font-size: 1.2rem !important;
|
| 239 |
-
font-weight: 700 !important;
|
| 240 |
-
color: #ffea7a !important;
|
| 241 |
-
text-shadow: 1px 1px 3px rgba(0,0,0,0.4);
|
| 242 |
-
}
|
| 243 |
-
div[data-testid="stMetricLabel"] p {
|
| 244 |
-
font-size: 1.5rem !important;
|
| 245 |
-
font-weight: 700 !important;
|
| 246 |
-
color: #06285a !important;
|
| 247 |
-
text-shadow: none !important;
|
| 248 |
-
background: none !important;
|
| 249 |
-
}
|
| 250 |
-
div[data-testid="stMetricValue"],
|
| 251 |
-
div[data-testid="stMetricLabel"] p {
|
| 252 |
-
filter: none !important;
|
| 253 |
-
}
|
| 254 |
-
/* ===== Custom Styling for Date INPUT FIELD ONLY ===== */
|
| 255 |
-
div[data-testid="stDateInput"] input {
|
| 256 |
-
background-color: #f0f2f6 !important;
|
| 257 |
-
color: #0A1931 !important;
|
| 258 |
-
border: 0.5px solid #cccccc !important;
|
| 259 |
-
border-radius: 4px;
|
| 260 |
-
padding: 8px 10px;
|
| 261 |
-
box-shadow: inset 0 1px 2px rgba(75, 98, 138);
|
| 262 |
-
transition: border-color 0.2s ease, box-shadow 0.2s ease;
|
| 263 |
-
}
|
| 264 |
-
div[data-testid="stDateInput"] button {
|
| 265 |
-
display: none !important;
|
| 266 |
-
}
|
| 267 |
-
div[data-testid="stDateInput"] input:hover,
|
| 268 |
-
div[data-testid="stDateInput"] input:focus {
|
| 269 |
-
border-color: #1547eb !important;
|
| 270 |
-
box-shadow: inset 0 1px 1px rgba(0,0,0,0.1), 0 0 0 2px rgba(21, 71, 235, 0.2);
|
| 271 |
-
}
|
| 272 |
-
</style>
|
| 273 |
-
""", unsafe_allow_html=True)
|
| 274 |
-
|
| 275 |
-
# --- 3. DATA & MODEL LOADING ---
|
| 276 |
-
@st.cache_data
|
| 277 |
-
def load_data_and_artifacts():
|
| 278 |
-
raw_df = pd.read_csv('data/Hanoi Daily 10 years.csv')
|
| 279 |
-
y_test_df = pd.read_csv('data/y_test.csv', index_col='datetime', parse_dates=True)
|
| 280 |
-
feature_importances = pd.read_csv('artifacts/feature_importances.csv')
|
| 281 |
-
return raw_df, y_test_df, feature_importances
|
| 282 |
-
|
| 283 |
-
@st.cache_resource
|
| 284 |
-
def load_model_and_features():
|
| 285 |
-
model = joblib.load('artifacts/hanoi_temp_predictor.joblib')
|
| 286 |
-
selected_features = joblib.load('artifacts/selected_features.joblib')
|
| 287 |
-
return model, selected_features
|
| 288 |
-
|
| 289 |
-
@st.cache_data
|
| 290 |
-
def get_processed_data(_raw_df):
|
| 291 |
-
return create_features(_raw_df)
|
| 292 |
-
|
| 293 |
-
# --- 4. MAIN APP LOGIC ---
|
| 294 |
-
load_css()
|
| 295 |
-
st.title("☀️ Group 5 Hanoi Weather Hub")
|
| 296 |
-
st.write("An interactive dashboard to forecast Hanoi's temperature for the next 5 days.")
|
| 297 |
-
|
| 298 |
-
raw_df, y_test, feature_importances = load_data_and_artifacts()
|
| 299 |
-
model, selected_features = load_model_and_features()
|
| 300 |
-
|
| 301 |
-
with st.spinner("Running feature engineering pipeline... This may take a moment."):
|
| 302 |
-
processed_df = get_processed_data(raw_df)
|
| 303 |
-
|
| 304 |
-
col1, col2 = st.columns([1, 2])
|
| 305 |
-
with col1:
|
| 306 |
-
selected_date = st.date_input(
|
| 307 |
-
label="Select a date to forecast from:",
|
| 308 |
-
value=processed_df.index.max(),
|
| 309 |
-
min_value=processed_df.index.min(),
|
| 310 |
-
max_value=processed_df.index.max(),
|
| 311 |
-
format="YYYY-MM-DD"
|
| 312 |
-
)
|
| 313 |
-
|
| 314 |
-
tab1, tab2, tab3 = st.tabs(["📈 Interactive Forecast", "🧠 Forecast Deep Dive", "📊 Model Performance"])
|
| 315 |
-
|
| 316 |
-
with tab1:
|
| 317 |
-
selected_date_ts = pd.Timestamp(selected_date)
|
| 318 |
-
st.header(f"5-Day Forecast from {selected_date_ts.strftime('%Y-%m-%d')}")
|
| 319 |
-
|
| 320 |
-
# Check if selected date exists in the processed dataframe
|
| 321 |
-
if selected_date_ts not in processed_df.index:
|
| 322 |
-
st.error("Selected date is not available in the dataset after processing. Please choose a different date.")
|
| 323 |
-
else:
|
| 324 |
-
input_data = processed_df.loc[[selected_date_ts]]
|
| 325 |
-
input_features = input_data[selected_features]
|
| 326 |
-
prediction = model.predict(input_features)[0]
|
| 327 |
-
actual_values = []
|
| 328 |
-
is_in_test_set = selected_date_ts in y_test.index
|
| 329 |
-
|
| 330 |
-
if is_in_test_set:
|
| 331 |
-
st.info("This is a backtest. 'Actual' values are shown for comparison.", icon="ℹ️")
|
| 332 |
-
actual_values = y_test.loc[selected_date_ts].values
|
| 333 |
-
else:
|
| 334 |
-
st.warning("This is a live forecast. 'Actual' values are not yet available.", icon="⚠️")
|
| 335 |
-
|
| 336 |
-
pred_cols = st.columns(5)
|
| 337 |
-
forecast_dates = pd.date_range(start=selected_date_ts, periods=6, freq='D')[1:]
|
| 338 |
-
for i, date in enumerate(forecast_dates):
|
| 339 |
-
delta_text = ""
|
| 340 |
-
if is_in_test_set and len(actual_values) > i:
|
| 341 |
-
delta_text = f"Actual: {actual_values[i]:.1f}°C"
|
| 342 |
-
pred_cols[i].metric(label=f"Forecast for {date.strftime('%b %d')}", value=f"{prediction[i]:.1f}°C", delta=delta_text, delta_color="off")
|
| 343 |
-
|
| 344 |
-
st.subheader("Visualizations")
|
| 345 |
-
st.markdown("#### Historical Context: Past 30 Days")
|
| 346 |
-
hist_data = processed_df.loc[selected_date_ts - pd.Timedelta(days=30):selected_date_ts, 'temp']
|
| 347 |
-
fig_hist = go.Figure()
|
| 348 |
-
fig_hist.add_trace(go.Scatter(x=hist_data.index, y=hist_data, mode='lines', name='Past 30 Days', line=dict(color='#636EFA')))
|
| 349 |
-
fig_hist.update_layout(title={'text': "<b>Actual Temperature - Past 30 Days</b>", 'x': 0.5}, xaxis_title="Date", yaxis_title="Temperature (°C)", paper_bgcolor="#fafbfc", plot_bgcolor="#e5ecf6")
|
| 350 |
-
components.html(fig_hist.to_html(include_plotlyjs='cdn'), height=450)
|
| 351 |
-
|
| 352 |
-
if is_in_test_set:
|
| 353 |
-
st.markdown("#### Forecast vs. Actual Comparison")
|
| 354 |
-
fig_comp = go.Figure()
|
| 355 |
-
fig_comp.add_trace(go.Scatter(x=forecast_dates, y=prediction, mode='lines+markers', name='5-Day Forecast', line=dict(color=PLOT_COLORS['forecast'])))
|
| 356 |
-
if len(actual_values) > 0:
|
| 357 |
-
fig_comp.add_trace(go.Scatter(x=forecast_dates, y=actual_values, mode='lines+markers', name='5-Day Actual', line=dict(color=PLOT_COLORS['actual'])))
|
| 358 |
-
fig_comp.update_layout(title={'text': "<b>5-Day Forecast vs. Actual Temperature</b>", 'x': 0.5}, xaxis_title="Date", yaxis_title="Temperature (°C)", paper_bgcolor='#fafbfc', plot_bgcolor='#e5ecf6')
|
| 359 |
-
components.html(fig_comp.to_html(include_plotlyjs='cdn'), height=450)
|
| 360 |
-
|
| 361 |
-
with tab2:
|
| 362 |
-
st.header("What were the most important factors for this forecast?")
|
| 363 |
-
st.write(f"For the forecast made on {selected_date.strftime('%Y-%m-%d')}, the model paid most attention to these factors:")
|
| 364 |
-
|
| 365 |
-
top_5_features = feature_importances.head(5)['Feature'].tolist()
|
| 366 |
-
key_factor_cols = st.columns(len(top_5_features))
|
| 367 |
-
|
| 368 |
-
for i, feature in enumerate(top_5_features):
|
| 369 |
-
value = processed_df.loc[pd.Timestamp(selected_date), feature]
|
| 370 |
-
with key_factor_cols[i]:
|
| 371 |
-
st.markdown(f"""
|
| 372 |
-
<div class="custom-card-transparent">
|
| 373 |
-
<span class="feature-tag-final">{feature}</span>
|
| 374 |
-
<h2>{value:.2f}</h2>
|
| 375 |
-
</div>
|
| 376 |
-
""", unsafe_allow_html=True)
|
| 377 |
-
|
| 378 |
-
st.markdown("<br>", unsafe_allow_html=True)
|
| 379 |
-
st.subheader("Overall Feature Importance")
|
| 380 |
-
top_10_df = feature_importances.head(10)
|
| 381 |
-
fig_imp = go.Figure(go.Bar(
|
| 382 |
-
x=top_10_df['Importance_Mean'],
|
| 383 |
-
y=top_10_df['Feature'],
|
| 384 |
-
orientation='h',
|
| 385 |
-
marker_color='#005aa7'
|
| 386 |
-
))
|
| 387 |
-
fig_imp.update_layout(
|
| 388 |
-
title={'text': '<b>Top 10 Most Important Features (Overall)</b>', 'x': 0.5},
|
| 389 |
-
xaxis_title='Permutation Importance Score',
|
| 390 |
-
yaxis={'title': '', 'autorange': "reversed"},
|
| 391 |
-
margin=dict(l=150, r=20, t=50, b=70),
|
| 392 |
-
paper_bgcolor='#fafbfc', plot_bgcolor='#e5ecf6'
|
| 393 |
-
)
|
| 394 |
-
components.html(fig_imp.to_html(include_plotlyjs='cdn'), height=520)
|
| 395 |
-
st.markdown("<br>", unsafe_allow_html=True)
|
| 396 |
-
|
| 397 |
-
st.header("Feature Glossary")
|
| 398 |
-
with st.expander(f"Click to learn about all {len(FEATURE_DESCRIPTIONS)} model features", expanded=False):
|
| 399 |
-
glossary_df = pd.DataFrame(
|
| 400 |
-
FEATURE_DESCRIPTIONS.items(),
|
| 401 |
-
columns=['Feature', 'Description']
|
| 402 |
-
).sort_values(by='Feature').reset_index(drop=True)
|
| 403 |
-
st.table(glossary_df)
|
| 404 |
-
|
| 405 |
-
with tab3:
|
| 406 |
-
st.header("Model Performance on the Entire Test Set")
|
| 407 |
-
X_test_filtered = processed_df.loc[y_test.index][selected_features]
|
| 408 |
-
y_pred_test = model.predict(X_test_filtered)
|
| 409 |
-
|
| 410 |
-
macro_r2 = r2_score(y_test, y_pred_test)
|
| 411 |
-
macro_rmse = np.sqrt(mean_squared_error(y_test, y_pred_test))
|
| 412 |
-
macro_mae = mean_absolute_error(y_test, y_pred_test)
|
| 413 |
-
|
| 414 |
-
m_cols = st.columns(3)
|
| 415 |
-
m_cols[0].metric("Average R2 Score", f"{macro_r2:.3f}")
|
| 416 |
-
m_cols[1].metric("Average RMSE", f"{macro_rmse:.3f}°C")
|
| 417 |
-
m_cols[2].metric("Average MAE", f"{macro_mae:.3f}°C")
|
| 418 |
-
|
| 419 |
-
st.subheader("Prediction vs. Actual Values")
|
| 420 |
-
y_test_flat = y_test.values.flatten()
|
| 421 |
-
y_pred_flat = y_pred_test.flatten()
|
| 422 |
-
|
| 423 |
-
fig_scatter = go.Figure()
|
| 424 |
-
fig_scatter.add_trace(go.Scatter(x=y_test_flat, y=y_pred_flat, mode='markers', marker=dict(color="rgba(73, 82, 199, 0.6)"), name='Predictions'))
|
| 425 |
-
fig_scatter.add_trace(go.Scatter(x=[y_test_flat.min(), y_test_flat.max()], y=[y_test_flat.min(), y_test_flat.max()], mode='lines', line=dict(color='#EF553B', dash='dash'), name='Perfect Prediction Line'))
|
| 426 |
-
fig_scatter.update_layout(title={'text': "<b>How well do predictions match actual values?</b>", 'x': 0.5}, xaxis_title="Actual Temperature (°C)", yaxis_title="Predicted Temperature (°C)", paper_bgcolor='#fafbfc', plot_bgcolor='#e5ecf6')
|
| 427 |
-
components.html(fig_scatter.to_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