OlamideKayode commited on
Commit
331907c
·
verified ·
1 Parent(s): de556bc

Upload app.py

Browse files
Files changed (1) hide show
  1. app.py +32 -10
app.py CHANGED
@@ -9,7 +9,6 @@ import streamlit as st
9
  from streamlit_autorefresh import st_autorefresh
10
  from sklearn.metrics import mean_absolute_error
11
  import plotly.express as px
12
- import plotly.graph_objects as go
13
 
14
  # Auto-refresh every 5 seconds
15
  st_autorefresh(interval=5000, key="refresh")
@@ -97,17 +96,33 @@ def engineer(df):
97
 
98
  return df
99
 
100
- # Forecast ahead logic
101
  def forecast_next(df, model, steps=5):
102
  forecasts = []
103
  df_copy = df.copy()
 
 
104
  for i in range(steps):
105
  df_copy = engineer(df_copy).dropna()
106
- input_row = df_copy.iloc[[-1]][[col for col in df_copy.columns if col in model.feature_names_in_]]
 
107
  y_pred = model.predict(input_row)[0]
108
- df_copy.loc[df_copy.index[-1], "power_consumption_kwh"] = y_pred
109
- df_copy = df_copy.append({**df_copy.iloc[-1], "power_consumption_kwh": y_pred, "timestamp": df_copy.iloc[-1].timestamp + 1800}, ignore_index=True)
110
- forecasts.append({"timestamp": df_copy.iloc[-1].timestamp, "forecast_kwh": y_pred})
 
 
 
 
 
 
 
 
 
 
 
 
 
111
  return pd.DataFrame(forecasts)
112
 
113
  # UI Layout
@@ -123,7 +138,14 @@ if not new_row.empty:
123
  st.session_state.history = pd.concat([st.session_state.history, new_row], ignore_index=True)
124
  df_feat = engineer(st.session_state.history).dropna()
125
  if not df_feat.empty:
126
- latest_input = df_feat.iloc[[-1]][[col for col in df_feat.columns if col in model.feature_names_in_]]
 
 
 
 
 
 
 
127
  prediction = model.predict(latest_input)[0]
128
  actual = new_row["power_consumption_kwh"].values[0]
129
  mae = mean_absolute_error([actual], [prediction])
@@ -150,15 +172,15 @@ if not new_row.empty:
150
  for region in ["east", "west", "north", "south"]:
151
  regional = df_feat[df_feat[f"region_{region}"] == 1]
152
  if not regional.empty:
153
- pred = model.predict(regional[[col for col in regional.columns if col in model.feature_names_in_]])
154
- st.write(f"**{region.title()} Region**: Avg Forecast: {np.mean(pred):.3f} kWh")
155
 
156
  st.subheader("🏠 Property Type Forecast")
157
  for region in ["east", "west", "north", "south"]:
158
  for ptype in ["commercial", "residential"]:
159
  filtered = df_feat[(df_feat[f"region_{region}"] == 1) & (df_feat[f"property_type_{ptype}"] == 1)]
160
  if not filtered.empty:
161
- preds = model.predict(filtered[[col for col in filtered.columns if col in model.feature_names_in_]])
162
  st.write(f"{region.title()} / {ptype.title()}: {np.mean(preds):.2f} kWh")
163
  else:
164
  st.success("✅ All data processed.")
 
9
  from streamlit_autorefresh import st_autorefresh
10
  from sklearn.metrics import mean_absolute_error
11
  import plotly.express as px
 
12
 
13
  # Auto-refresh every 5 seconds
14
  st_autorefresh(interval=5000, key="refresh")
 
96
 
97
  return df
98
 
99
+ # Forecast ahead logic (5 steps, 30min intervals)
100
  def forecast_next(df, model, steps=5):
101
  forecasts = []
102
  df_copy = df.copy()
103
+ expected_features = model.feature_names_in_.tolist()
104
+
105
  for i in range(steps):
106
  df_copy = engineer(df_copy).dropna()
107
+ # Ensure columns are aligned to model input
108
+ input_row = df_copy.iloc[[-1]][expected_features]
109
  y_pred = model.predict(input_row)[0]
110
+
111
+ # Update the last row's power consumption with prediction
112
+ df_copy.at[df_copy.index[-1], "power_consumption_kwh"] = y_pred
113
+
114
+ # Prepare the next timestamp: add 1800 seconds (30 mins)
115
+ next_timestamp = df_copy.iloc[-1]["timestamp"] + 1800
116
+
117
+ # Prepare new row: copy last row features but update timestamp and power consumption
118
+ new_row = df_copy.iloc[-1].copy()
119
+ new_row["power_consumption_kwh"] = y_pred
120
+ new_row["timestamp"] = next_timestamp
121
+
122
+ # Append new row safely
123
+ df_copy = pd.concat([df_copy, pd.DataFrame([new_row])], ignore_index=True)
124
+ forecasts.append({"timestamp": next_timestamp, "forecast_kwh": y_pred})
125
+
126
  return pd.DataFrame(forecasts)
127
 
128
  # UI Layout
 
138
  st.session_state.history = pd.concat([st.session_state.history, new_row], ignore_index=True)
139
  df_feat = engineer(st.session_state.history).dropna()
140
  if not df_feat.empty:
141
+ # Align features exactly to what model expects
142
+ expected_features = model.feature_names_in_.tolist()
143
+ for col in expected_features:
144
+ if col not in df_feat.columns:
145
+ df_feat[col] = 0
146
+
147
+ latest_input = df_feat[expected_features].iloc[[-1]]
148
+
149
  prediction = model.predict(latest_input)[0]
150
  actual = new_row["power_consumption_kwh"].values[0]
151
  mae = mean_absolute_error([actual], [prediction])
 
172
  for region in ["east", "west", "north", "south"]:
173
  regional = df_feat[df_feat[f"region_{region}"] == 1]
174
  if not regional.empty:
175
+ preds = model.predict(regional[expected_features])
176
+ st.write(f"**{region.title()} Region**: Avg Forecast: {np.mean(preds):.3f} kWh")
177
 
178
  st.subheader("🏠 Property Type Forecast")
179
  for region in ["east", "west", "north", "south"]:
180
  for ptype in ["commercial", "residential"]:
181
  filtered = df_feat[(df_feat[f"region_{region}"] == 1) & (df_feat[f"property_type_{ptype}"] == 1)]
182
  if not filtered.empty:
183
+ preds = model.predict(filtered[expected_features])
184
  st.write(f"{region.title()} / {ptype.title()}: {np.mean(preds):.2f} kWh")
185
  else:
186
  st.success("✅ All data processed.")