Subelinha commited on
Commit
4267287
·
verified ·
1 Parent(s): 66c4e71

Update future_forecast.py

Browse files
Files changed (1) hide show
  1. future_forecast.py +1 -330
future_forecast.py CHANGED
@@ -97,333 +97,4 @@ def make_preprocessor() -> ColumnTransformer:
97
  )
98
 
99
 
100
- def make_pipeline(regressor: object) -> Pipeline:
101
- return Pipeline(
102
- [
103
- ("preprocess", make_preprocessor()),
104
- ("regressor", regressor),
105
- ]
106
- )
107
-
108
-
109
- def candidate_factories() -> dict[str, Callable[[], Pipeline]]:
110
- return {
111
- "Linear regression with lags": lambda: make_pipeline(LinearRegression()),
112
- "Ridge with lags (alpha=0.1)": lambda: make_pipeline(Ridge(alpha=0.1)),
113
- "Ridge with lags (alpha=1)": lambda: make_pipeline(Ridge(alpha=1.0)),
114
- "Ridge with lags (alpha=10)": lambda: make_pipeline(Ridge(alpha=10.0)),
115
- "Random forest with lags": lambda: make_pipeline(
116
- RandomForestRegressor(
117
- n_estimators=500,
118
- min_samples_leaf=2,
119
- max_features=0.8,
120
- random_state=RANDOM_STATE,
121
- n_jobs=-1,
122
- )
123
- ),
124
- }
125
-
126
-
127
- def regression_metrics(y_true: np.ndarray, y_pred: np.ndarray) -> dict[str, float]:
128
- return {
129
- "MAE": mean_absolute_error(y_true, y_pred),
130
- "RMSE": mean_squared_error(y_true, y_pred) ** 0.5,
131
- "R2": r2_score(y_true, y_pred),
132
- }
133
-
134
-
135
- def predict_named_model(
136
- name: str,
137
- training: pd.DataFrame,
138
- evaluation: pd.DataFrame,
139
- ) -> np.ndarray:
140
- if name == "Persistence (previous campaign)":
141
- return evaluation["production_lag_1"].to_numpy()
142
-
143
- model = candidate_factories()[name]()
144
- model.fit(training[FEATURES], training[TARGET])
145
- return model.predict(evaluation[FEATURES])
146
-
147
-
148
- def calculate_region_intervals(
149
- data: pd.DataFrame,
150
- selected_model: str,
151
- validation_years: list[int] = VALIDATION_YEARS,
152
- ) -> dict[str, float]:
153
- """Calculate the 90% interval specific to each region."""
154
- region_intervals = {}
155
-
156
- for region in data["region"].unique():
157
- errors = []
158
-
159
- for validation_year in validation_years:
160
- training = data[data["year_start"] < validation_year]
161
- validation = data[
162
- (data["year_start"] == validation_year) &
163
- (data["region"] == region)
164
- ]
165
-
166
- if len(training) < 2 or len(validation) == 0:
167
- continue
168
-
169
- # Use a simple model to estimate error by region
170
- if selected_model == "Persistence (previous campaign)":
171
- # For persistence, use the direct error
172
- val_data = validation.merge(
173
- training.groupby("region", observed=True)[TARGET]
174
- .tail(1)
175
- .rename("last_production"),
176
- on="region",
177
- how="left"
178
- )
179
- pred = val_data["last_production"].fillna(val_data[TARGET].mean()).to_numpy()
180
- else:
181
- model = candidate_factories()[selected_model]()
182
- model.fit(training[FEATURES], training[TARGET])
183
- pred = model.predict(validation[FEATURES])
184
-
185
- errors.extend(np.abs(validation[TARGET].values - pred))
186
-
187
- if errors:
188
- region_intervals[region] = np.quantile(errors, 0.90)
189
- else:
190
- # Fallback: use global error with a correction factor
191
- global_error = data["absolute_error"].quantile(0.90) if "absolute_error" in data.columns else 150000
192
- # Small regions have less data - reduce the interval
193
- region_data = data[data["region"] == region]
194
- if len(region_data) < 8:
195
- region_intervals[region] = global_error * 0.6
196
- else:
197
- region_intervals[region] = global_error
198
-
199
- return region_intervals
200
-
201
-
202
- def calculate_region_min_production(history: pd.DataFrame) -> dict[str, float]:
203
- """Calcula a produção mínima histórica por região."""
204
- min_production = {}
205
- for region in history["region"].unique():
206
- region_data = history[history["region"] == region][TARGET]
207
- if not region_data.empty:
208
- min_production[region] = float(region_data.min())
209
- else:
210
- min_production[region] = 0.0
211
- return min_production
212
-
213
-
214
- def evaluate_forecasters() -> EvaluationResult:
215
- data = build_supervised_data(load_history())
216
- names = ["Persistence (previous campaign)", *candidate_factories().keys()]
217
-
218
- metric_rows: list[dict[str, float | str | bool]] = []
219
- prediction_rows: list[pd.DataFrame] = []
220
- validation_predictions: dict[str, tuple[np.ndarray, np.ndarray]] = {}
221
-
222
- for name in names:
223
- observed_parts = []
224
- predicted_parts = []
225
-
226
- for validation_year in VALIDATION_YEARS:
227
- training = data[data["year_start"] < validation_year]
228
- validation = data[data["year_start"] == validation_year]
229
- prediction = predict_named_model(name, training, validation)
230
- observed_parts.append(validation[TARGET].to_numpy())
231
- predicted_parts.append(prediction)
232
-
233
- observed = np.concatenate(observed_parts)
234
- predicted = np.concatenate(predicted_parts)
235
- validation_predictions[name] = (observed, predicted)
236
-
237
- metric_rows.append(
238
- {
239
- "model": name,
240
- "split": "rolling_validation_2018_2022",
241
- **regression_metrics(observed, predicted),
242
- }
243
- )
244
-
245
- validation_metrics = pd.DataFrame(metric_rows).sort_values("MAE")
246
- selected_model = str(validation_metrics.iloc[0]["model"])
247
-
248
- final_training = data[data["year_start"] < min(TEST_YEARS)]
249
- test = data[data["year_start"].isin(TEST_YEARS)]
250
-
251
- # Calculate the absolute error for each forecast (used in the intervals)
252
- all_predictions = []
253
-
254
- for name in names:
255
- prediction = predict_named_model(name, final_training, test)
256
-
257
- metric_rows.append(
258
- {
259
- "model": name,
260
- "split": "test_2023_2025",
261
- **regression_metrics(test[TARGET].to_numpy(), prediction),
262
- }
263
- )
264
-
265
- detail = test[["region", "year_start", TARGET]].copy()
266
- detail["model"] = name
267
- detail["predicted_production_hl"] = prediction
268
- detail["absolute_error_hl"] = np.abs(detail[TARGET] - prediction)
269
- prediction_rows.append(detail)
270
- all_predictions.append(detail)
271
-
272
- # Combine all forecasts to have error data by region
273
- all_pred_df = pd.concat(all_predictions, ignore_index=True)
274
-
275
- # Calculate intervals by region using the selected model
276
- selected_predictions = all_pred_df[all_pred_df["model"] == selected_model]
277
- selected_predictions["absolute_error"] = selected_predictions["absolute_error_hl"]
278
- data_with_errors = data.merge(
279
- selected_predictions[["region", "year_start", "absolute_error"]],
280
- on=["region", "year_start"],
281
- how="left"
282
- )
283
-
284
- region_intervals = calculate_region_intervals(data_with_errors, selected_model)
285
- region_min_production = calculate_region_min_production(load_history())
286
-
287
- observed, predicted = validation_predictions[selected_model]
288
- interval_half_width = float(np.quantile(np.abs(observed - predicted), 0.90))
289
-
290
- metrics = pd.DataFrame(metric_rows)
291
- metrics["selected_on_validation"] = metrics["model"].eq(selected_model)
292
- predictions = pd.concat(prediction_rows, ignore_index=True)
293
-
294
- return EvaluationResult(
295
- metrics=metrics,
296
- predictions=predictions,
297
- selected_model=selected_model,
298
- interval_half_width=interval_half_width,
299
- region_intervals=region_intervals,
300
- region_min_production=region_min_production,
301
- )
302
-
303
-
304
- def make_future_features(
305
- history: pd.DataFrame,
306
- future_year: int = FUTURE_YEAR,
307
- area_overrides: dict[str, float] | None = None,
308
- ) -> pd.DataFrame:
309
- rows = []
310
- overrides = area_overrides or {}
311
-
312
- for region, region_history in history.groupby("region", observed=True):
313
- region_history = region_history.sort_values("year_start")
314
- recent = region_history.tail(3)
315
-
316
- if len(recent) < 2:
317
- continue
318
-
319
- latest_area_series = region_history["vineyard_area_ha"].dropna()
320
- if latest_area_series.empty:
321
- continue
322
-
323
- latest_area = float(latest_area_series.iloc[-1])
324
- lag_1 = float(recent[TARGET].iloc[-1])
325
- lag_2 = float(recent[TARGET].iloc[-2])
326
-
327
- rows.append(
328
- {
329
- "region": region,
330
- "year_start": future_year,
331
- "vineyard_area_ha": float(overrides.get(region, latest_area)),
332
- "production_lag_1": lag_1,
333
- "production_lag_2": lag_2,
334
- "production_mean_3": float(recent[TARGET].mean()),
335
- "production_trend_1": lag_1 - lag_2,
336
- }
337
- )
338
-
339
- return pd.DataFrame(rows).sort_values("region").reset_index(drop=True)
340
-
341
-
342
- def forecast_2026(
343
- evaluation: EvaluationResult | None = None,
344
- area_overrides: dict[str, float] | None = None,
345
- ) -> pd.DataFrame:
346
- evaluation = evaluation or evaluate_forecasters()
347
- history = load_history()
348
- supervised = build_supervised_data(history)
349
- future = make_future_features(history, area_overrides=area_overrides)
350
-
351
- if evaluation.selected_model == "Persistence (previous campaign)":
352
- prediction = future["production_lag_1"].to_numpy()
353
- else:
354
- model = candidate_factories()[evaluation.selected_model]()
355
- model.fit(supervised[FEATURES], supervised[TARGET])
356
- prediction = model.predict(future[FEATURES])
357
-
358
- result = future[["region", "year_start", "vineyard_area_ha"]].copy()
359
- result["selected_model"] = evaluation.selected_model
360
- result["predicted_production_hl"] = np.maximum(0, prediction).round().astype(int)
361
-
362
- # NEW: Calculate region-specific intervals with realistic limits
363
- lower_bounds = []
364
- upper_bounds = []
365
-
366
- for idx, row in result.iterrows():
367
- region = row["region"]
368
- pred = row["predicted_production_hl"]
369
-
370
- # Use region-specific interval or fallback to the global one
371
- half_width = evaluation.region_intervals.get(
372
- region,
373
- evaluation.interval_half_width
374
- )
375
-
376
- # Obtain the region's historical minimum production
377
- min_prod = evaluation.region_min_production.get(region, 0)
378
-
379
- # Calculate lower bound with three levels of protection:
380
- # 1. Cannot be negative (max with 0)
381
- # 2. Cannot be less than 30% of the region's historical minimum production
382
- # 3. If the forecast is too low, use a reasonable minumum value
383
- lower = max(0, pred - half_width)
384
-
385
- # Ensure a realistic minimum based on historical production
386
- if min_prod > 0:
387
- # Use 30% of the minimum production as an absolute limit
388
- absolute_min = min_prod * 0.3
389
- lower = max(lower, absolute_min)
390
- else:
391
- # Fallback: If there is no historical data, use 5% of the forecast
392
- lower = max(lower, pred * 0.05)
393
-
394
- # Limite superior
395
- upper = pred + half_width
396
-
397
- lower_bounds.append(int(round(lower)))
398
- upper_bounds.append(int(round(upper)))
399
-
400
- result["lower_90_hl"] = lower_bounds
401
- result["upper_90_hl"] = upper_bounds
402
-
403
- return result
404
-
405
-
406
- def save_outputs() -> tuple[EvaluationResult, pd.DataFrame]:
407
- evaluation = evaluate_forecasters()
408
- future = forecast_2026(evaluation=evaluation)
409
-
410
- TABLES_DIR.mkdir(parents=True, exist_ok=True)
411
- evaluation.metrics.to_csv(TABLES_DIR / "future_model_comparison.csv", index=False)
412
- evaluation.predictions.to_csv(TABLES_DIR / "future_model_test_predictions.csv", index=False)
413
- future.to_csv(TABLES_DIR / "forecast_2026_27.csv", index=False)
414
-
415
- return evaluation, future
416
-
417
-
418
- def main() -> None:
419
- evaluation, future = save_outputs()
420
- print("Selected on rolling validation:", evaluation.selected_model)
421
- print("Empirical 90% interval half-width:", f"{evaluation.interval_half_width:,.0f} hl")
422
- print("\nMetrics")
423
- print(evaluation.metrics.sort_values(["split", "MAE"]).to_string(index=False))
424
- print("\n2026/27 experimental forecasts")
425
- print(future.to_string(index=False))
426
-
427
-
428
- if __name__ == "__main__":
429
- main()
 
97
  )
98
 
99
 
100
+ def make_pipeline(regressor: object) -> Pipeline: