XGBoost Gap-Filling

Gap-fill time series using XGBoost with feature engineering.

XGBoost is a gradient boosting approach for gap-filling time series data. Effective for non-linear relationships, complex temporal interactions, and data with outliers. Often achieves higher accuracy than Random Forest. Demonstrates the complete workflow: feature engineering, model training, SHAP importance analysis, and gap-filling predictions.

XGBoost gap-filling for CO₂ flux (NEE)

This example demonstrates the full XGBoost gap-filling workflow: 1. Load example ecosystem flux data 2. Create engineered features (lag, rolling stats, STL, timestamps) 3. Train XGBoostTS model on complete observations 4. Evaluate feature importance using SHAP 5. Predict missing values (gap-fill)

Features used: Tair_f (temperature), VPD_f (vapor pressure deficit), Rg_f (radiation)

import matplotlib.pyplot as plt
import pandas as pd

import diive as dv

Load and prepare data

TARGET_COL = 'NEE_CUT_REF_orig'
subsetcols = [TARGET_COL, 'Tair_f', 'VPD_f', 'Rg_f']

df_orig = dv.load_exampledata_parquet()
df = df_orig.copy()
keep = (df.index.year >= 2020) & (df.index.year <= 2020)
df = df[keep].copy()
df = df[subsetcols].copy()

print(f"Data loaded: {len(df)} records from {df.index.min().date()} to {df.index.max().date()}")
print(f"Missing values in target: {df[TARGET_COL].isnull().sum()}")
  > Loaded .parquet file
/home/docs/checkouts/diive/checkouts/latest/diive/configs/exampledata/exampledat
a_PARQUET_CH-DAV_FP2022.5_2013-2022_ID20230206154316_30MIN.parquet (0.050
seconds).
Data loaded: 17568 records from 2020-01-01 to 2020-12-31
Missing values in target: 11630

Engineer features

Create an 8-stage feature engineering pipeline: lag features, rolling statistics, differencing, exponential moving averages, polynomial terms, STL decomposition, timestamp features, and continuous record number.

engineer = dv.gapfilling.FeatureEngineer(
    target_col=TARGET_COL,
    features_lag=[-2, -1],
    features_lag_stepsize=1,
    features_lag_exclude_cols=None,
    features_rolling=[2, 4, 12, 24, 48],
    features_rolling_exclude_cols=None,
    features_rolling_stats=['mean', 'median', 'min', 'max'],
    features_diff=[1, 2],
    features_diff_exclude_cols=None,
    features_ema=[6, 12, 24, 48],
    features_ema_exclude_cols=None,
    features_poly_degree=2,
    features_poly_exclude_cols=None,
    features_stl=True,
    features_stl_method='stl',
    features_stl_seasonal_period=None,
    features_stl_exclude_cols=None,
    features_stl_components=None,
    vectorize_timestamps=True,
    add_continuous_record_number=True,
    sanitize_timestamp=False
)
df_engineered = engineer.fit_transform(df)

print(f"\nEngineered features created: {df_engineered.shape[1]} columns")
Engineered features created: 130 columns

Train XGBoost model

Create an XGBoostTS model with the engineered features. The model will: 1. Automatically detect features to use 2. Reduce features using SHAP importance (keep only important ones) 3. Train on complete observations only

xgbts = dv.gapfilling.XGBoostTS(
    input_df=df_engineered,
    target_col=TARGET_COL,
    verbose=1,
    below_zero=None,  # How to treat negative predictions: None=keep, 'zero'=clip to 0
    # Use 'zero' or 'nan' for variables that cannot be negative (e.g. VPD, SW_IN, PPFD).
    # NEE can be negative (carbon uptake), so None is correct here.
    n_estimators=50,
    random_state=42,
    max_depth=6,
    learning_rate=0.1,
    early_stopping_rounds=10,
    n_jobs=-1,
    # Explain a 5000-row sample instead of every row. TreeSHAP costs time linear
    # in the number of rows and mean |SHAP| converges long before the full record,
    # so the ranking (and therefore the reduction below) is unchanged; the sample
    # is seeded, so the result stays reproducible.
    shap_max_rows=5000,
)

# Feature reduction using SHAP importance
xgbts.reduce_features(shap_threshold_factor=0.5)
xgbts.report_feature_reduction()
  ! Some features are incomplete (<17568 values): .Tair_f_DIFF1 (17567),
.VPD_f_DIFF1 (17567), .Rg_f_DIFF1 (17567), .Tair_f_DIFF2 (17566), .VPD_f_DIFF2
(17566), .Rg_f_DIFF2 (17566)
  ! Not all target values can be predicted based on the full model.
────────────────────────────── Feature Reduction ───────────────────────────────

- Target variable: NEE_CUT_REF_orig
- Random variable .RANDOM used as benchmark for importance threshold.

SHAP IMPORTANCE (mean absolute SHAP values):

                   SHAP_IMPORTANCE   SHAP_SD
Rg_f                      2.275548  1.072434
.Tair_f_STL_TREND         0.554368  0.417541
.Tair_f_DIFF1             0.389679  0.294279
.DOY_COS                  0.241612  0.221256
.Rg_f_ROLLMIN4            0.232444  0.134985
...                            ...       ...
.Rg_f_ROLLMIN48           0.000000  0.000000
.VPD_f_POL2               0.000000  0.000000
.Rg_f_POL2                0.000000  0.000000
.YEAR                     0.000000  0.000000
.YEARWEEK                 0.000000  0.000000

[130 rows x 2 columns]

- These results are from feature reduction. Final model importances are
  recalculated during gap-filling.

  129 original input features: ['Tair_f', 'VPD_f', 'Rg_f', '.Tair_f-2',
'.Tair_f-1', '.VPD_f-2', '.VPD_f-1', '.Rg_f-2', '.Rg_f-1', '.Tair_f_MEAN2',
'.VPD_f_MEAN2', '.Rg_f_MEAN2', '.Tair_f_SD2', '.VPD_f_SD2', '.Rg_f_SD2',
'.Tair_f_MEAN4', '.VPD_f_MEAN4', '.Rg_f_MEAN4', '.Tair_f_SD4', '.VPD_f_SD4',
'.Rg_f_SD4', '.Tair_f_MEAN12', '.VPD_f_MEAN12', '.Rg_f_MEAN12', '.Tair_f_SD12',
'.VPD_f_SD12', '.Rg_f_SD12', '.Tair_f_MEAN24', '.VPD_f_MEAN24', '.Rg_f_MEAN24',
'.Tair_f_SD24', '.VPD_f_SD24', '.Rg_f_SD24', '.Tair_f_MEAN48', '.VPD_f_MEAN48',
'.Rg_f_MEAN48', '.Tair_f_SD48', '.VPD_f_SD48', '.Rg_f_SD48',
'.Tair_f_ROLLMEDIAN2', '.VPD_f_ROLLMEDIAN2', '.Rg_f_ROLLMEDIAN2',
'.Tair_f_ROLLMIN2', '.VPD_f_ROLLMIN2', '.Rg_f_ROLLMIN2', '.Tair_f_ROLLMAX2',
'.VPD_f_ROLLMAX2', '.Rg_f_ROLLMAX2', '.Tair_f_ROLLMEDIAN4',
'.VPD_f_ROLLMEDIAN4', '.Rg_f_ROLLMEDIAN4', '.Tair_f_ROLLMIN4',
'.VPD_f_ROLLMIN4', '.Rg_f_ROLLMIN4', '.Tair_f_ROLLMAX4', '.VPD_f_ROLLMAX4',
'.Rg_f_ROLLMAX4', '.Tair_f_ROLLMEDIAN12', '.VPD_f_ROLLMEDIAN12',
'.Rg_f_ROLLMEDIAN12', '.Tair_f_ROLLMIN12', '.VPD_f_ROLLMIN12',
'.Rg_f_ROLLMIN12', '.Tair_f_ROLLMAX12', '.VPD_f_ROLLMAX12', '.Rg_f_ROLLMAX12',
'.Tair_f_ROLLMEDIAN24', '.VPD_f_ROLLMEDIAN24', '.Rg_f_ROLLMEDIAN24',
'.Tair_f_ROLLMIN24', '.VPD_f_ROLLMIN24', '.Rg_f_ROLLMIN24', '.Tair_f_ROLLMAX24',
'.VPD_f_ROLLMAX24', '.Rg_f_ROLLMAX24', '.Tair_f_ROLLMEDIAN48',
'.VPD_f_ROLLMEDIAN48', '.Rg_f_ROLLMEDIAN48', '.Tair_f_ROLLMIN48',
'.VPD_f_ROLLMIN48', '.Rg_f_ROLLMIN48', '.Tair_f_ROLLMAX48', '.VPD_f_ROLLMAX48',
'.Rg_f_ROLLMAX48', '.Tair_f_DIFF1', '.VPD_f_DIFF1', '.Rg_f_DIFF1',
'.Tair_f_DIFF2', '.VPD_f_DIFF2', '.Rg_f_DIFF2', '.Tair_f_EMA6', '.VPD_f_EMA6',
'.Rg_f_EMA6', '.Tair_f_EMA12', '.VPD_f_EMA12', '.Rg_f_EMA12', '.Tair_f_EMA24',
'.VPD_f_EMA24', '.Rg_f_EMA24', '.Tair_f_EMA48', '.VPD_f_EMA48', '.Rg_f_EMA48',
'.Tair_f_POL2', '.VPD_f_POL2', '.Rg_f_POL2', '.Tair_f_STL_TREND',
'.Tair_f_STL_SEASONAL', '.Tair_f_STL_RESIDUAL', '.VPD_f_STL_TREND',
'.VPD_f_STL_SEASONAL', '.VPD_f_STL_RESIDUAL', '.Rg_f_STL_TREND',
'.Rg_f_STL_SEASONAL', '.Rg_f_STL_RESIDUAL', '.YEAR', '.SEASON_SIN',
'.SEASON_COS', '.MONTH_SIN', '.MONTH_COS', '.WEEK_SIN', '.WEEK_COS', '.DOY_SIN',
'.DOY_COS', '.HOUR_SIN', '.HOUR_COS', '.YEARMONTH', '.YEARDOY', '.YEARWEEK',
'.RECORDNUMBER']
  107 rejected features: ['Tair_f', 'VPD_f', '.Tair_f-2', '.Tair_f-1',
'.VPD_f-2', '.VPD_f-1', '.Rg_f-2', '.Tair_f_MEAN2', '.VPD_f_MEAN2',
'.Tair_f_SD2', '.VPD_f_SD2', '.Rg_f_SD2', '.Tair_f_MEAN4', '.VPD_f_MEAN4',
'.Rg_f_MEAN4', '.VPD_f_SD4', '.Rg_f_SD4', '.Tair_f_MEAN12', '.VPD_f_MEAN12',
'.Rg_f_MEAN12', '.Tair_f_SD12', '.Rg_f_SD12', '.Tair_f_MEAN24', '.VPD_f_MEAN24',
'.Rg_f_MEAN24', '.Tair_f_SD24', '.VPD_f_SD24', '.Rg_f_SD24', '.Tair_f_MEAN48',
'.VPD_f_MEAN48', '.Rg_f_MEAN48', '.Tair_f_SD48', '.VPD_f_SD48', '.Rg_f_SD48',
'.Tair_f_ROLLMEDIAN2', '.VPD_f_ROLLMEDIAN2', '.Rg_f_ROLLMEDIAN2',
'.Tair_f_ROLLMIN2', '.VPD_f_ROLLMIN2', '.Tair_f_ROLLMAX2', '.VPD_f_ROLLMAX2',
'.Rg_f_ROLLMAX2', '.Tair_f_ROLLMEDIAN4', '.VPD_f_ROLLMEDIAN4',
'.Rg_f_ROLLMEDIAN4', '.Tair_f_ROLLMIN4', '.VPD_f_ROLLMIN4', '.Tair_f_ROLLMAX4',
'.VPD_f_ROLLMAX4', '.Rg_f_ROLLMAX4', '.Tair_f_ROLLMEDIAN12',
'.VPD_f_ROLLMEDIAN12', '.Rg_f_ROLLMEDIAN12', '.Tair_f_ROLLMIN12',
'.VPD_f_ROLLMIN12', '.Rg_f_ROLLMIN12', '.Tair_f_ROLLMAX12', '.VPD_f_ROLLMAX12',
'.Rg_f_ROLLMAX12', '.VPD_f_ROLLMEDIAN24', '.Rg_f_ROLLMEDIAN24',
'.VPD_f_ROLLMIN24', '.Rg_f_ROLLMIN24', '.Tair_f_ROLLMAX24', '.VPD_f_ROLLMAX24',
'.Rg_f_ROLLMAX24', '.VPD_f_ROLLMEDIAN48', '.VPD_f_ROLLMIN48', '.Rg_f_ROLLMIN48',
'.Tair_f_ROLLMAX48', '.VPD_f_ROLLMAX48', '.Rg_f_ROLLMAX48', '.Rg_f_DIFF1',
'.Tair_f_DIFF2', '.VPD_f_DIFF2', '.Tair_f_EMA6', '.VPD_f_EMA6', '.Rg_f_EMA6',
'.Tair_f_EMA12', '.VPD_f_EMA12', '.Rg_f_EMA12', '.Tair_f_EMA24', '.VPD_f_EMA24',
'.Rg_f_EMA24', '.Tair_f_EMA48', '.VPD_f_EMA48', '.Rg_f_EMA48', '.Tair_f_POL2',
'.VPD_f_POL2', '.Rg_f_POL2', '.Tair_f_STL_SEASONAL', '.Tair_f_STL_RESIDUAL',
'.VPD_f_STL_TREND', '.VPD_f_STL_SEASONAL', '.VPD_f_STL_RESIDUAL',
'.Rg_f_STL_SEASONAL', '.Rg_f_STL_RESIDUAL', '.YEAR', '.SEASON_SIN',
'.SEASON_COS', '.MONTH_SIN', '.MONTH_COS', '.WEEK_SIN', '.WEEK_COS',
'.HOUR_COS', '.YEARMONTH', '.YEARWEEK']
  22 accepted features: ['Rg_f', '.Tair_f_STL_TREND', '.Tair_f_DIFF1',
'.DOY_COS', '.Rg_f_ROLLMIN4', '.Tair_f_ROLLMEDIAN48', '.Rg_f_ROLLMEDIAN48',
'.Tair_f_ROLLMIN48', '.Rg_f_ROLLMIN2', '.YEARDOY', '.DOY_SIN', '.RECORDNUMBER',
'.Tair_f_ROLLMEDIAN24', '.Rg_f_MEAN2', '.Rg_f-1', '.HOUR_SIN', '.Rg_f_DIFF2',
'.VPD_f_SD12', '.Tair_f_ROLLMIN24', '.Rg_f_STL_TREND', '.Tair_f_SD4',
'.VPD_f_DIFF1']

Train and evaluate model

xgbts.trainmodel(showplot_scores=False, showplot_importance=False)
xgbts.report_traintest()
─────────────────────── MODEL TRAINING & TESTING RESULTS ───────────────────────

## DATA
  > target: NEE_CUT_REF_orig
  > features: 22 ['Rg_f', '.Tair_f_STL_TREND', '.Tair_f_DIFF1', '.DOY_COS',
'.Rg_f_ROLLMIN4', '.Tair_f_ROLLMEDIAN48', '.Rg_f_ROLLMEDIAN48',
'.Tair_f_ROLLMIN48', '.Rg_f_ROLLMIN2', '.YEARDOY', '.DOY_SIN', '.RECORDNUMBER',
'.Tair_f_ROLLMEDIAN24', '.Rg_f_MEAN2', '.Rg_f-1', '.HOUR_SIN', '.Rg_f_DIFF2',
'.VPD_f_SD12', '.Tair_f_ROLLMIN24', '.Rg_f_STL_TREND', '.Tair_f_SD4',
'.VPD_f_DIFF1']
  > 17568 records (with missing)
  > 5938 available records for target and all features (no missing values)
  > training on 4453 records (75.0%) between 2020-01-01 01:45:00 and 2020-12-31
21:45:00
  > testing on 1485 unseen records (25.0%) of NEE_CUT_REF_orig between
2020-01-01 15:45:00 and 2020-12-31 14:45:00

## MODEL
  > estimator:  XGBRegressor(base_score=None, booster=None, callbacks=None,
             colsample_bylevel=None, colsample_bynode=None,
             colsample_bytree=None, device=None, early_stopping_rounds=10,
             enable_categorical=True, eval_metric=None, feature_types=None,
             feature_weights=None, gamma=None, grow_policy=None,
             importance_type=None, interaction_constraints=None,
             learning_rate=0.1, max_bin=None, max_cat_threshold=None,
             max_cat_to_onehot=None, max_delta_step=None, max_depth=6,
             max_leaves=None, min_child_weight=None, missing=nan,
             monotone_constraints=None, multi_strategy=None, n_estimators=50,
             n_jobs=-1, num_parallel_tree=None, ...)
  > parameters:  {'objective': 'reg:squarederror', 'base_score': None,
'booster': None, 'callbacks': None, 'colsample_bylevel': None,
'colsample_bynode': None, 'colsample_bytree': None, 'device': None,
'early_stopping_rounds': 10, 'enable_categorical': True, 'eval_metric': None,
'feature_types': None, 'feature_weights': None, 'gamma': None, 'grow_policy':
None, 'importance_type': None, 'interaction_constraints': None, 'learning_rate':
0.1, 'max_bin': None, 'max_cat_threshold': None, 'max_cat_to_onehot': None,
'max_delta_step': None, 'max_depth': 6, 'max_leaves': None, 'min_child_weight':
None, 'missing': nan, 'monotone_constraints': None, 'multi_strategy': None,
'n_estimators': 50, 'n_jobs': -1, 'num_parallel_tree': None, 'random_state': 42,
'reg_alpha': None, 'reg_lambda': None, 'sampling_method': None,
'scale_pos_weight': None, 'subsample': None, 'tree_method': None,
'validate_parameters': None, 'verbosity': None}
  > number of features:  22
  > feature names:  ['Rg_f', '.Tair_f_STL_TREND', '.Tair_f_DIFF1', '.DOY_COS',
'.Rg_f_ROLLMIN4', '.Tair_f_ROLLMEDIAN48', '.Rg_f_ROLLMEDIAN48',
'.Tair_f_ROLLMIN48', '.Rg_f_ROLLMIN2', '.YEARDOY', '.DOY_SIN', '.RECORDNUMBER',
'.Tair_f_ROLLMEDIAN24', '.Rg_f_MEAN2', '.Rg_f-1', '.HOUR_SIN', '.Rg_f_DIFF2',
'.VPD_f_SD12', '.Tair_f_ROLLMIN24', '.Rg_f_STL_TREND', '.Tair_f_SD4',
'.VPD_f_DIFF1']

## FEATURE IMPORTANCES
  > calculated from unseen test data (1485 records)
  > shows mean absolute SHAP values

                      SHAP_IMPORTANCE   SHAP_SD
Rg_f                         2.404260  1.138467
.YEARDOY                     0.460475  0.529246
.Tair_f_STL_TREND            0.454874  0.388111
.Tair_f_DIFF1                0.421940  0.340101
.Tair_f_ROLLMEDIAN24         0.317238  0.252634
.Rg_f_ROLLMIN4               0.296521  0.166480
.DOY_COS                     0.287963  0.272812
.Tair_f_ROLLMEDIAN48         0.252048  0.178337
.Tair_f_ROLLMIN48            0.240785  0.195242
.Rg_f-1                      0.227097  0.146555
.HOUR_SIN                    0.222315  0.191032
.Rg_f_ROLLMIN2               0.222030  0.164180
.Rg_f_ROLLMEDIAN48           0.203643  0.152944
.Rg_f_STL_TREND              0.172638  0.161426
.Rg_f_DIFF2                  0.152970  0.150166
.DOY_SIN                     0.149979  0.195491
.RECORDNUMBER                0.129617  0.096081
.Tair_f_SD4                  0.121728  0.152243
.VPD_f_DIFF1                 0.114144  0.133360
.Tair_f_ROLLMIN24            0.102341  0.159085
.VPD_f_SD12                  0.098247  0.104407
.Rg_f_MEAN2                  0.052107  0.044297

## MODEL SCORES (test set, 1485 records)
  > MAE:   2.042805118278113 (mean absolute error)
  > MedAE: 1.4428951711654663 (median absolute error)
  > MSE:   8.408511763834012 (mean squared error)
  > RMSE:  2.8997433962049146 (root mean squared error)
  > MAXE:  17.465603900909425 (max error)
  > MAPE:  1.461 (mean absolute percentage error)
  > R2:    0.7223619690087635

Gap-fill missing data

Use the trained model to predict missing flux values.

xgbts.fillgaps(showplot_scores=False, showplot_importance=False)
xgbts.report_gapfilling()
───────────────────────────── GAP-FILLING RESULTS ──────────────────────────────

Scores and importances from predicted (11628) vs observed (5938) targets.

## TARGET
- period:  2020-01-01 00:15:00 to 2020-12-31 23:45:00
- potential values: 17568
- observed (NEE_CUT_REF_orig):  missing 11630
- gap-filled (NEE_CUT_REF_orig_gfXG):  17568 values, missing 0
- flag FLAG_NEE_CUT_REF_orig_gfXG_ISFILLED:  0=observed (5938)  1=gap-filled
(11628)  2=fallback (2)

## FEATURE IMPORTANCES  (22 features, SHAP TreeExplainer)

                      SHAP_IMPORTANCE   SHAP_SD
Rg_f                         2.420126  1.152078
.Tair_f_STL_TREND            0.457886  0.397184
.YEARDOY                     0.448863  0.512212
.Tair_f_DIFF1                0.432817  0.355230
.Tair_f_ROLLMEDIAN24         0.328608  0.270301
.Rg_f_ROLLMIN4               0.303051  0.175152
.DOY_COS                     0.288481  0.278259
.Tair_f_ROLLMEDIAN48         0.254651  0.178175
.Tair_f_ROLLMIN48            0.244640  0.191751
.Rg_f-1                      0.228322  0.151832
.HOUR_SIN                    0.223527  0.189089
.Rg_f_ROLLMIN2               0.221230  0.170028
.Rg_f_ROLLMEDIAN48           0.205620  0.155330
.Rg_f_STL_TREND              0.173498  0.168203
.Rg_f_DIFF2                  0.157908  0.156205
.DOY_SIN                     0.147268  0.187315
.RECORDNUMBER                0.132365  0.099266
.Tair_f_SD4                  0.126138  0.154398
.VPD_f_DIFF1                 0.111938  0.138369
.Tair_f_ROLLMIN24            0.109772  0.175952
.VPD_f_SD12                  0.101784  0.107549
.Rg_f_MEAN2                  0.053120  0.045187

## MODEL  (test size 25.0%)
- estimator:  XGBRegressor(base_score=None, booster=None, callbacks=None,
             colsample_bylevel=None, colsample_bynode=None,
             colsample_bytree=None, device=None, early_stopping_rounds=10,
             enable_categorical=True, eval_metric=None, feature_types=None,
             feature_weights=None, gamma=None, grow_policy=None,
             importance_type=None, interaction_constraints=None,
             learning_rate=0.1, max_bin=None, max_cat_threshold=None,
             max_cat_to_onehot=None, max_delta_step=None, max_depth=6,
             max_leaves=None, min_child_weight=None, missing=nan,
             monotone_constraints=None, multi_strategy=None, n_estimators=50,
             n_jobs=-1, num_parallel_tree=None, ...)
- parameters:  {'objective': 'reg:squarederror', 'base_score': None, 'booster':
None, 'callbacks': None, 'colsample_bylevel': None, 'colsample_bynode': None,
'colsample_bytree': None, 'device': None, 'early_stopping_rounds': 10,
'enable_categorical': True, 'eval_metric': None, 'feature_types': None,
'feature_weights': None, 'gamma': None, 'grow_policy': None, 'importance_type':
None, 'interaction_constraints': None, 'learning_rate': 0.1, 'max_bin': None,
'max_cat_threshold': None, 'max_cat_to_onehot': None, 'max_delta_step': None,
'max_depth': 6, 'max_leaves': None, 'min_child_weight': None, 'missing': nan,
'monotone_constraints': None, 'multi_strategy': None, 'n_estimators': 50,
'n_jobs': -1, 'num_parallel_tree': None, 'random_state': 42, 'reg_alpha': None,
'reg_lambda': None, 'sampling_method': None, 'scale_pos_weight': None,
'subsample': None, 'tree_method': None, 'validate_parameters': None,
'verbosity': None}

## MODEL SCORES (in-sample: predicted on ALL data incl. training rows;
optimistically biased)
- MAE:   1.717422883485355 (mean absolute error)
- MedAE: 1.1929901065826414 (median absolute error)
- MSE:   5.916437469425551 (mean squared error)
- RMSE:  2.432372806422887 (root mean squared error)
- MAXE:  17.465603900909425 (max error)
- MAPE:  326359446908.043 (mean absolute percentage error)
- R2:    0.811720370060427

## MODEL SCORES (out-of-sample: held-out test set, 25.0%; generalization
estimate)
- MAE:   2.042805118278113 (mean absolute error)
- MedAE: 1.4428951711654663 (median absolute error)
- MSE:   8.408511763834012 (mean squared error)
- RMSE:  2.8997433962049146 (root mean squared error)
- MAXE:  17.465603900909425 (max error)
- MAPE:  1.461 (mean absolute percentage error)
- R2:    0.7223619690087635

Visualize results

Compare observed data (with gaps) against XGBoost gap-filled predictions using side-by-side heatmaps.

observed = df[TARGET_COL]
gapfilled = xgbts.get_gapfilled_target()

fig, axes = plt.subplots(1, 2, figsize=(16, 5),
                         gridspec_kw={'wspace': 0.15},
                         constrained_layout=True)

dv.plotting.HeatmapDateTime(series=observed).plot(ax=axes[0])
axes[0].set_title('Observed\n(with gaps)', fontsize=11, fontweight='bold')

dv.plotting.HeatmapDateTime(series=gapfilled).plot(ax=axes[1])
axes[1].set_title('XGBoost\nGap-Filled', fontsize=11, fontweight='bold')

fig.suptitle('XGBoost Gap-Filling Comparison', fontsize=13, fontweight='bold', y=1.00)
plt.show()
XGBoost Gap-Filling Comparison, Observed (with gaps), XGBoost Gap-Filled

Cumulative carbon flux

Convert fluxes to carbon units and plot cumulative sums to evaluate overall agreement between observed and gap-filled data.

df_cumulative = pd.DataFrame({
    'Observed': observed,
    'Gap-filled': gapfilled
})
# Convert from umol CO2 m-2 s-1 to g C m-2 30min-1
df_cumulative = df_cumulative.multiply(0.02161926)
series_units = r'($\mathrm{gC\ m^{-2}}$)'

dv.plotting.Cumulative(
    df=df_cumulative,
    units=series_units,
    start_year=2020,
    end_year=2020
).plot()

print("[OK] XGBoost gap-filling complete.")
Cumulatives (2020-01-01 00:15:00-2020-12-31 23:45:00)
[OK] XGBoost gap-filling complete.

Total running time of the script: (0 minutes 11.784 seconds)

Gallery generated by Sphinx-Gallery