Gumball2k5 commited on
Commit
686ee7d
·
verified ·
1 Parent(s): 5606474

Update src/streamlit_app.py

Browse files
Files changed (1) hide show
  1. src/streamlit_app.py +468 -38
src/streamlit_app.py CHANGED
@@ -1,40 +1,470 @@
1
- import altair as alt
2
- import numpy as np
3
- import pandas as pd
4
  import streamlit as st
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5
 
6
- """
7
- # Welcome to Streamlit!
8
-
9
- Edit `/streamlit_app.py` to customize this app to your heart's desire :heart:.
10
- If you have any questions, checkout our [documentation](https://docs.streamlit.io) and [community
11
- forums](https://discuss.streamlit.io).
12
-
13
- In the meantime, below is an example of what you can do with just a few lines of code:
14
- """
15
-
16
- num_points = st.slider("Number of points in spiral", 1, 10000, 1100)
17
- num_turns = st.slider("Number of turns in spiral", 1, 300, 31)
18
-
19
- indices = np.linspace(0, 1, num_points)
20
- theta = 2 * np.pi * num_turns * indices
21
- radius = indices
22
-
23
- x = radius * np.cos(theta)
24
- y = radius * np.sin(theta)
25
-
26
- df = pd.DataFrame({
27
- "x": x,
28
- "y": y,
29
- "idx": indices,
30
- "rand": np.random.randn(num_points),
31
- })
32
-
33
- st.altair_chart(alt.Chart(df, height=700, width=700)
34
- .mark_point(filled=True)
35
- .encode(
36
- x=alt.X("x", axis=None),
37
- y=alt.Y("y", axis=None),
38
- color=alt.Color("idx", legend=None, scale=alt.Scale()),
39
- size=alt.Size("rand", legend=None, scale=alt.Scale(range=[1, 150])),
40
- ))
 
 
 
 
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
+ # --- FEATURE DESCRIPTIONS (COMPLETE 46 FEATURES) ---
20
+ # This dictionary maps each of the 46 features used by the model to a user-friendly description.
21
+ FEATURE_DESCRIPTIONS = {
22
+ # Core & Cyclical Features
23
+ "temp": "The average temperature of the current day (°C).",
24
+ "cos_day_of_year": "Cosine of the day of the year. Captures the main seasonal cycle.",
25
+ "sin_day_of_year": "Sine of the day of the year. Works with cosine to pinpoint the exact time of year.",
26
+
27
+ # Temperature-based Features
28
+ "temp_ewm_30": "30-day Exponentially Weighted Moving Average of temperature. Represents the long-term temperature trend.",
29
+ "temp_ewm_7": "7-day Exponentially Weighted Moving Average of temperature. Represents the short-term temperature trend.",
30
+ "temp_diff_1": "Difference between today's and yesterday's temperature. Shows if it's warming up or cooling down.",
31
+ "temp_roll_min_7": "The minimum temperature recorded over the past 7 days.",
32
+ "temp_lag_1": "The average temperature from the previous day.",
33
+ "temp_range": "The difference between the maximum (tempmax) and minimum (tempmin) temperature of the day.",
34
+ "temp_resid_yearly": "The residual (irregular noise) component after removing trend and seasonality from the temperature series.",
35
+ "temp_trend_yearly": "The long-term trend component of the temperature (e.g., gradual warming over years).",
36
+
37
+ # Weather Condition Features
38
+ "solarradiation": "The amount of solar energy received per unit area. A primary driver of heat.",
39
+ "windgust": "The highest instantaneous wind speed recorded during the day (km/h).",
40
+ "cloudcover": "The percentage of the sky covered by clouds.",
41
+ "humidity": "The relative humidity of the air (%).",
42
+ "precip": "The amount of precipitation (rain) recorded (mm).",
43
+ "precipprob": "The probability of precipitation occurring (%).",
44
+ "visibility": "The distance at which objects can be clearly seen (km).",
45
+ "windspeed": "The average wind speed for the day (km/h).",
46
+
47
+ # Wind-related Features
48
+ "winddir_cos": "Cosine of the wind direction. Helps the model understand easterly vs. westerly wind components.",
49
+ "wind_vector_ew": "East-West wind vector component, calculated from wind speed and direction.",
50
+ "windspeed_roll_std_14": "Standard deviation of wind speed over the past 14 days, indicating wind volatility.",
51
+
52
+ # Interaction & Advanced Features
53
+ "interaction_wind_clearsky_effect": "An interaction term between wind speed and cloud cover, modeling the wind chill effect on clear days.",
54
+
55
+ # Seasonal & Holiday Features
56
+ "season_Winter": "A binary flag (1 if Winter, 0 otherwise).",
57
+ "season_Summer": "A binary flag (1 if Summer, 0 otherwise).",
58
+
59
+ # Lag Features (Past Values)
60
+ "precip_lag_3": "Precipitation from 3 days ago.",
61
+ "precip_lag_4": "Precipitation from 4 days ago.",
62
+ "precip_lag_5": "Precipitation from 5 days ago.",
63
+ "windspeed_lag_8": "Wind speed from 8 days ago.",
64
+
65
+ # Rolling Window Statistics (Recent History)
66
+ "precip_roll_mean_3": "The average precipitation over the past 3 days.",
67
+ "precip_roll_min_30": "The minimum precipitation recorded in the past 30 days.",
68
+ "cloudcover_roll_std_3": "Standard deviation of cloud cover over the past 3 days, indicating cloudiness stability.",
69
+ "humidity_roll_std_3": "Standard deviation of humidity over the past 3 days.",
70
+ "windspeed_roll_min_30": "The minimum wind speed recorded in the past 30 days.",
71
+ "windspeed_roll_max_30": "The maximum wind speed recorded in the past 30 days.",
72
+ "temp_roll_std_3": "Standard deviation of temperature over the past 3 days, indicating temperature stability.",
73
+ "temp_roll_std_7": "Standard deviation of temperature over the past 7 days.",
74
+
75
+ # Difference Features (Rate of Change)
76
+ "humidity_diff_7": "The difference between today's humidity and the humidity from 7 days ago.",
77
+ "windspeed_diff_7": "The difference between today's wind speed and the wind speed from 7 days ago.",
78
+ "cloudcover_diff_7": "The difference between today's cloud cover and the cloud cover from 7 days ago.",
79
+
80
+ # Fourier Features (Advanced Cycles)
81
+ "fft_cos_freq_1": "A cyclical feature derived from Fourier analysis, capturing a dominant underlying cycle in the temperature data.",
82
+ "fft_sin_freq_1": "A cyclical feature paired with fft_cos_freq_1 to pinpoint the phase of the dominant cycle.",
83
+ "fft_cos_freq_2": "A feature capturing the second most dominant underlying cycle.",
84
+ "fft_sin_freq_2": "A feature paired with fft_cos_freq_2.",
85
+
86
+ # Other
87
+ "Clear": "A binary flag indicating if the weather condition was 'Clear'."
88
+ }
89
+
90
+ # --- 2. CUSTOM CSS FOR STYLING ---
91
+ def load_css():
92
+ st.markdown("""
93
+ <style>
94
+ /* ===== Background gradient ===== */
95
+ [data-testid="stAppViewContainer"] {
96
+ background-image: linear-gradient(to bottom, #d4e1da 20%, #005aa7 100%) !important;
97
+ background-attachment: fixed !important;
98
+ background-size: cover !important;
99
+ }
100
+ /* ===== Global text ===== */
101
+ .stApp, h1, h2, h3, p, label {
102
+ color: #0A1931;
103
+ }
104
+ /* ===== Tabs ===== */
105
+ button[data-baseweb="tab"][aria-selected="true"] {
106
+ background-color: #FFFFFF !important;
107
+ color: #005aa7 !important;
108
+ padding: 10px 16px !important;
109
+ border-radius: 10px 10px 0 0 !important;
110
+ font-weight: 700 !important;
111
+ border-bottom: 3px solid #e53935 !important;
112
+ }
113
+ button[data-baseweb="tab"][aria-selected="false"] {
114
+ background-color: rgba(255,255,255,0.3) !important;
115
+ color: #284270 !important;
116
+ padding: 10px 16px !important;
117
+ }
118
+ /* ===== Metrics: Forecast titles, main numbers, and Actual (delta) ===== */
119
+ [data-testid="stMetricLabel"] p,
120
+ div[data-testid="stMetricValue"] {
121
+ font-weight: 700 !important;
122
+ text-shadow: 1px 1px 3px rgba(0,0,0,0.3);
123
+ }
124
+ div[data-testid="stMetricLabel"] p:contains("Forecast for") {
125
+ color: #ffffff !important;
126
+ font-size: 2.2rem !important;
127
+ font-weight: 800 !important;
128
+ text-shadow: 1px 1px 3px rgba(0,0,0,0.3);
129
+ background: none !important;
130
+ border: none !important;
131
+ }
132
+ div[data-testid="stMetricValue"] {
133
+ color: #fefefe !important;
134
+ font-size: 1.9rem !important;
135
+ text-shadow: 1px 1px 6px rgba(0,0,0,0.5);
136
+ }
137
+ div[data-testid="stMetricLabel"] p {
138
+ color: #dce9ff !important;
139
+ font-weight: 700 !important;
140
+ letter-spacing: 0.3px;
141
+ }
142
+ div[data-testid="stMetricLabel"] p {
143
+ color: #e8f1ff !important;
144
+ font-size: 1.4rem !important;
145
+ font-weight: 700 !important;
146
+ text-shadow: none !important;
147
+ background: rgba(0, 0, 0, 0.15);
148
+ padding: 4px 8px;
149
+ border-radius: 6px;
150
+ }
151
+ div[data-testid="stMetricValue"] {
152
+ color: #ffffff !important;
153
+ font-size: 1.8rem !important;
154
+ text-shadow: 0 0 3px rgba(0,0,0,0.3);
155
+ background: rgba(0,0,0,0.15);
156
+ border-radius: 6px;
157
+ padding: 6px 10px;
158
+ }
159
+ div[data-testid="stMetricValue"] {
160
+ color: #fefefe !important;
161
+ font-size: 1.4rem !important;
162
+ text-shadow: 1px 1px 6px rgba(0,0,0,0.5);
163
+ }
164
+ div[data-testid="stMetricLabel"] p {
165
+ color: #dce9ff !important;
166
+ font-weight: 700 !important;
167
+ letter-spacing: 0.3px;
168
+ }
169
+ div[data-testid="stMetricValue"],
170
+ div[data-testid="stMetricLabel"] p {
171
+ filter: drop-shadow(0 0 3px rgba(255,255,255,0.4));
172
+ }
173
+ /* ===== Custom feature cards (Tab 2) ===== */
174
+ .custom-card-transparent {
175
+ background: linear-gradient(145deg, rgba(255,255,255,0.12), rgba(0,0,0,0.25));
176
+ border: 1px solid rgba(255,255,255,0.25);
177
+ border-radius: 12px;
178
+ padding: 14px;
179
+ text-align: center;
180
+ transition: all 0.25s ease;
181
+ box-shadow: 0 2px 8px rgba(0,0,0,0.15);
182
+ width: 95%;
183
+ margin: 0 auto;
184
+ }
185
+ .custom-card-transparent:hover {
186
+ transform: translateY(-3px);
187
+ box-shadow: 0 4px 12px rgba(0,0,0,0.25);
188
+ filter: brightness(1.1);
189
+ }
190
+ .custom-card-transparent h2 {
191
+ color: #fefefe !important;
192
+ font-size: 1.6rem !important;
193
+ font-weight: 700 !important;
194
+ text-shadow: 0 0 4px rgba(255,255,255,0.25);
195
+ margin-top: 10px;
196
+ }
197
+ .feature-tag-final {
198
+ background-color: #1c3d70 !important;
199
+ padding: 5px 10px;
200
+ border-radius: 8px;
201
+ font-size: 0.9rem;
202
+ font-weight: 600;
203
+ color: #e3eeff !important;
204
+ text-shadow: 0 0 2px rgba(255,255,255,0.15);
205
+ display: inline-block;
206
+ margin-bottom: 3px;
207
+ }
208
+ /* ===== Restored missing pieces ===== */
209
+ div[data-testid="stExpander"] {
210
+ background-color: rgba(255, 255, 255, 0.85) !important;
211
+ border-radius: 12px !important;
212
+ border: 1px solid rgba(0, 90, 167, 0.25) !important;
213
+ box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1) !important;
214
+ margin-top: 2rem;
215
+ }
216
+ div.st-emotion-cache-1e5k5x7 {
217
+ background-color: rgba(230, 240, 255, 0.5) !important;
218
+ border-radius: 15px !important;
219
+ padding: 1rem 0.5rem !important;
220
+ border: 1px solid rgba(255, 255, 255, 0.3);
221
+ box-shadow: 0 4px 12px rgba(0,0,0,0.1);
222
+ margin: 1rem 0;
223
+ }
224
+ div.st-emotion-cache-1e5k5x7 div[data-testid="stMetricValue"] {
225
+ color: white !important;
226
+ text-shadow: 1px 1px 3px rgba(0,0,0,0.4);
227
+ }
228
+ div.st-emotion-cache-1e5k5x7 div[data-testid="stMetricLabel"] p {
229
+ color: #0A1931 !important;
230
+ font-weight: 600 !important;
231
+ }
232
+ button[data-baseweb="tab"][aria-selected="true"] {
233
+ border-bottom: 2px solid rgba(229,57,53,0.9) !important;
234
+ }
235
+ div[data-testid="stMetricLabel"] p:contains("Forecast for") {
236
+ color: #ffffff !important;
237
+ font-size: 2.2rem !important;
238
+ font-weight: 800 !important;
239
+ text-shadow: 1px 1px 3px rgba(0,0,0,0.3);
240
+ background: none !important;
241
+ border: none !important;
242
+ }
243
+ div[data-testid="stMetricValue"] {
244
+ color: #ffffff !important;
245
+ font-size: 2.2rem !important;
246
+ font-weight: 800 !important;
247
+ text-shadow: 2px 2px 5px rgba(0,0,0,0.4);
248
+ background: none !important;
249
+ border: none !important;
250
+ padding: 0 !important;
251
+ }
252
+ [data-testid="stMetricDelta"] {
253
+ font-size: 1.2rem !important;
254
+ font-weight: 700 !important;
255
+ color: #ffea7a !important;
256
+ text-shadow: 1px 1px 3px rgba(0,0,0,0.4);
257
+ }
258
+ div[data-testid="stMetricLabel"] p {
259
+ font-size: 1.5rem !important;
260
+ font-weight: 700 !important;
261
+ color: #06285a !important;
262
+ text-shadow: none !important;
263
+ background: none !important;
264
+ }
265
+ div[data-testid="stMetricValue"],
266
+ div[data-testid="stMetricLabel"] p {
267
+ filter: none !important;
268
+ }
269
+ /* ===== Custom Styling for Date INPUT FIELD ONLY ===== */
270
+ div[data-testid="stDateInput"] input {
271
+ background-color: #f0f2f6 !important;
272
+ color: #0A1931 !important;
273
+ border: 0.5px solid #cccccc !important;
274
+ border-radius: 4px;
275
+ padding: 8px 10px;
276
+ box-shadow: inset 0 1px 2px rgba(75, 98, 138);
277
+ transition: border-color 0.2s ease, box-shadow 0.2s ease;
278
+ }
279
+ div[data-testid="stDateInput"] button {
280
+ display: none !important;
281
+ }
282
+ div[data-testid="stDateInput"] input:hover,
283
+ div[data-testid="stDateInput"] input:focus {
284
+ border-color: #1547eb !important;
285
+ box-shadow: inset 0 1px 1px rgba(0,0,0,0.1), 0 0 0 2px rgba(21, 71, 235, 0.2);
286
+ }
287
+
288
+ </style>
289
+ """, unsafe_allow_html=True)
290
+
291
+ # --- 3. DATA & MODEL LOADING ---
292
+ @st.cache_data
293
+ def load_raw_data():
294
+ raw_df = pd.read_csv('data/Hanoi Daily 10 years.csv')
295
+ y_test = pd.read_csv('data/y_test.csv', index_col='datetime', parse_dates=True)
296
+ feature_importances = pd.read_csv('data/feature_importances.csv')
297
+ return raw_df, y_test, feature_importances
298
+
299
+ @st.cache_resource
300
+ def load_model_and_features():
301
+ model = joblib.load('artifacts/hanoi_temp_predictor.joblib')
302
+ selected_features = joblib.load('artifacts/selected_features.joblib')
303
+ return model, selected_features
304
+
305
+ @st.cache_data
306
+ def process_data(_raw_df):
307
+ return create_features(_raw_df)
308
+
309
+ # --- 4. MAIN APP LOGIC ---
310
+ load_css()
311
+ st.title("☀️ Group 5 Hanoi Weather Hub")
312
+ st.write("An interactive dashboard to forecast Hanoi's temperature for the next 5 days.")
313
+
314
+ raw_df, y_test, feature_importances = load_raw_data()
315
+ model, selected_features = load_model_and_features()
316
+
317
+ with st.spinner("Running feature engineering pipeline..."):
318
+ processed_df = process_data(raw_df)
319
+
320
+ col1, col2 = st.columns([1, 2])
321
+ with col1:
322
+ selected_date = st.date_input(
323
+ label="Select a date to forecast from:",
324
+ value=processed_df.index.max(),
325
+ min_value=processed_df.index.min(),
326
+ max_value=processed_df.index.max(),
327
+ format="YYYY-MM-DD"
328
+ )
329
+
330
+ tab1, tab2, tab3 = st.tabs(["📈 Interactive Forecast", "🧠 Forecast Deep Dive", "📊 Model Performance"])
331
+
332
+ # --- TAB 1 ---
333
+ with tab1:
334
+ selected_date_ts = pd.Timestamp(selected_date)
335
+ st.header(f"5-Day Forecast from {selected_date_ts.strftime('%Y-%m-%d')}")
336
+ input_data = processed_df.loc[[selected_date_ts]]
337
+ input_features = input_data[selected_features]
338
+ prediction = model.predict(input_features)[0]
339
+ actual_values = []
340
+ is_in_test_set = selected_date_ts in y_test.index
341
+ if is_in_test_set:
342
+ st.info("This is a backtest. 'Actual' values are shown for comparison.", icon="ℹ️")
343
+ actual_values = y_test.loc[selected_date_ts].values
344
+ else:
345
+ st.warning("This is a live forecast. 'Actual' values are not yet available.", icon="⚠️")
346
+ pred_cols = st.columns(5)
347
+ forecast_dates = pd.date_range(start=selected_date_ts, periods=6, freq='D')[1:]
348
+ for i, date in enumerate(forecast_dates):
349
+ delta_text = ""
350
+ if is_in_test_set and len(actual_values) > i:
351
+ delta_text = f"Actual: {actual_values[i]:.1f}°C"
352
+ pred_cols[i].metric(label=f"Forecast for {date.strftime('%b %d')}", value=f"{prediction[i]:.1f}°C", delta=delta_text, delta_color="off")
353
+ st.subheader("Visualizations")
354
+ st.markdown("#### Historical Context: Past 30 Days")
355
+ hist_data = processed_df.loc[selected_date_ts - pd.Timedelta(days=30):selected_date_ts, 'temp']
356
+ fig_hist = go.Figure()
357
+ fig_hist.add_trace(go.Scatter(x=hist_data.index, y=hist_data, mode='lines', name='Past 30 Days', line=dict(color='#636EFA')))
358
+ 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")
359
+ components.html(fig_hist.to_html(include_plotlyjs='cdn'), height=450)
360
+ if is_in_test_set:
361
+ st.markdown("#### Forecast vs. Actual Comparison")
362
+ fig_comp = go.Figure()
363
+ fig_comp.add_trace(go.Scatter(x=forecast_dates, y=prediction, mode='lines+markers', name='5-Day Forecast', line=dict(color=PLOT_COLORS['forecast'])))
364
+ if len(actual_values) > 0:
365
+ 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'])))
366
+ 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')
367
+ components.html(fig_comp.to_html(include_plotlyjs='cdn'), height=450)
368
+
369
+ # --- TAB 2 ---
370
+ with tab2:
371
+ # --- Section 1: Key Factors for the selected date ---
372
+ st.header("What were the most important factors for this forecast?")
373
+ st.write(f"For the forecast made on **{selected_date.strftime('%Y-%m-%d')}**, the model paid most attention to these factors:")
374
+
375
+ top_5_features = feature_importances.head(5)['Feature'].tolist()
376
+ key_factor_cols = st.columns(len(top_5_features))
377
+
378
+ for i, feature in enumerate(top_5_features):
379
+ value = processed_df.loc[pd.Timestamp(selected_date), feature]
380
+ with key_factor_cols[i]:
381
+ st.markdown(f"""
382
+ <div class="custom-card-transparent">
383
+ <span class="feature-tag-final">{feature}</span>
384
+ <h2>{value:.2f}</h2>
385
+ </div>
386
+ """, unsafe_allow_html=True)
387
+
388
+ # Add a visual separator (a bit of space)
389
+ st.markdown("<br>", unsafe_allow_html=True)
390
+
391
+ # --- Section 2: Overall Feature Importance Chart ---
392
+ st.subheader("Overall Feature Importance")
393
+ top_10_df = feature_importances.head(10)
394
+ fig_imp = go.Figure(go.Bar(
395
+ x=top_10_df['Importance_Mean'],
396
+ y=top_10_df['Feature'],
397
+ orientation='h',
398
+ marker_color='#005aa7'
399
+ ))
400
+
401
+ fig_imp.update_layout(
402
+ title={'text': '<b>Top 10 Most Important Features (Overall)</b>', 'x': 0.5},
403
+ xaxis_title='Permutation Importance Score',
404
+ yaxis={
405
+ 'title': '', # Y-axis title is removed as requested
406
+ 'autorange': "reversed",
407
+ },
408
+ margin=dict(l=150, r=20, t=50, b=70),
409
+ yaxis_ticklabelposition="outside top",
410
+ paper_bgcolor='#fafbfc', plot_bgcolor='#e5ecf6'
411
+ )
412
+ # Render the chart using the robust HTML component method
413
+ components.html(fig_imp.to_html(include_plotlyjs='cdn'), height=520)
414
+
415
+ # Add another visual separator
416
+ st.markdown("<br>", unsafe_allow_html=True)
417
+
418
+ # --- Section 3: Feature Glossary ---
419
+ st.header("Feature Glossary")
420
+ with st.expander("Click to learn about all 46 model features", expanded=False):
421
+ # Create a DataFrame from the dictionary for easy handling
422
+ glossary_df = pd.DataFrame(
423
+ FEATURE_DESCRIPTIONS.items(),
424
+ columns=['Feature', 'Description']
425
+ ).sort_values(by='Feature').reset_index(drop=True)
426
+
427
+ # Use Markdown to create a custom table with borders
428
+ st.markdown("""
429
+ <style>
430
+ .glossary-table {
431
+ width: 100%;
432
+ border-collapse: collapse;
433
+ }
434
+ .glossary-table th, .glossary-table td {
435
+ border: 1px solid #cccccc;
436
+ padding: 8px;
437
+ text-align: left;
438
+ }
439
+ .glossary-table th {
440
+ background-color: #f2f2f2;
441
+ font-weight: bold;
442
+ }
443
+ </style>
444
+ """, unsafe_allow_html=True)
445
+
446
+ # Build the HTML for the table
447
+ html_table = "<table class='glossary-table'><tr><th>Feature</th><th>Description</th></tr>"
448
+ for index, row in glossary_df.iterrows():
449
+ html_table += f"<tr><td><b>{row['Feature']}</b></td><td>{row['Description']}</td></tr>"
450
+ html_table += "</table>"
451
+
452
+ st.markdown(html_table, unsafe_allow_html=True)
453
 
454
+ # --- TAB 3 ---
455
+ with tab3:
456
+ st.header("Model Performance on the Entire Test Set")
457
+ X_test_filtered = processed_df.loc[y_test.index][selected_features]
458
+ y_pred_test = model.predict(X_test_filtered)
459
+ macro_r2, macro_rmse, macro_mae = r2_score(y_test, y_pred_test), np.sqrt(mean_squared_error(y_test, y_pred_test)), mean_absolute_error(y_test, y_pred_test)
460
+ m_cols = st.columns(3)
461
+ m_cols[0].metric("Average R2 Score", f"{macro_r2:.3f}")
462
+ m_cols[1].metric("Average RMSE", f"{macro_rmse:.3f}°C")
463
+ m_cols[2].metric("Average MAE", f"{macro_mae:.3f}°C")
464
+ st.subheader("Prediction vs. Actual Values")
465
+ y_test_flat, y_pred_flat = y_test.values.flatten(), y_pred_test.flatten()
466
+ fig_scatter = go.Figure()
467
+ 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'))
468
+ 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'))
469
+ fig_scatter.update_layout(title={'text': "<b>How well do predictions match actual values?</b>", 'x': 0.5}, xaxis_title="Predicted Temperature (°C)", yaxis_title="Predicted Temperature (°C)", paper_bgcolor='#fafbfc', plot_bgcolor='#e5ecf6')
470
+ components.html(fig_scatter.to_html(include_plotlyjs='cdn'), height=600)