Random Forest Gap-Filling with Long-Term Year Pooling

Gap-fill time series using separate annual random forest models trained with neighboring years. This “long-term” approach adapts to seasonal patterns and yearly variability without assuming the data are stationary.

Demonstrates building separate models for each year, where each model is trained on data from the target year plus 2 neighboring years (e.g., 2020 model uses 2019, 2020, 2021 data).

Best for: Multi-year datasets where seasonal/yearly variation is significant.

Long-term random forest gap-filling approach

The LongTermGapFillingRandomForestTS class enables yearly models that adapt to seasonal and inter-annual variation. Each year gets its own trained model using a “neighboring years” pool strategy.

import matplotlib.pyplot as plt
import numpy as np

import diive as dv
from diive.gapfilling.longterm import LongTermGapFillingRandomForestTS

Load and prepare data

df = dv.load_exampledata_parquet()

# Use 3 years of data for speed (demonstrates long-term concept without full 10-year run)
df = df.loc[df.index.year.isin([2020, 2021, 2022])].copy()

# Select target and features
TARGET_COL = 'NEE_CUT_REF_orig'
feature_cols = [TARGET_COL, 'Tair_f', 'VPD_f', 'Rg_f']
df = df[feature_cols].copy()

# Quality control: remove low-quality NEE records
lowquality = df.index.get_level_values(0).to_frame()['QCF_NEE'] > 0 if 'QCF_NEE' in df.columns else False
if isinstance(lowquality, bool) and not lowquality:
    # Fallback: mark some records as missing manually if QCF not available
    pass

print(f"Data: {len(df)} records from {df.index.min().date()} to {df.index.max().date()}")
print(f"Missing values: {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: 52608 records from 2020-01-01 to 2022-12-31
Missing values: 34754

Feature engineering for all records

Before model training, create engineered features (lags, timestamps, trends). This preparation applies to all years equally.

engineer = dv.gapfilling.FeatureEngineer(
    target_col=TARGET_COL,
    verbose=2,
    features_lag=[-1, -1],  # 1-step lag on all features except target
    add_continuous_record_number=True,  # Capture long-term drift
    sanitize_timestamp=False  # Example data is already clean; skip 10-step validation
)
df_engineered = engineer.fit_transform(df)

print(f"Engineered features shape: {df_engineered.shape}")
  > Added new column .RECORDNUMBER with record numbers from 1 to 52608.
Engineered features shape: (52608, 8)

Initialize long-term model with yearly pools

Create one random forest model per year. Each model is trained on: - The target year’s data - Plus 2 neighboring years (year-1 and year+1)

This neighboring-years strategy allows each year’s model to capture that year’s seasonal patterns while benefiting from adjacent years’ data.

gf = LongTermGapFillingRandomForestTS(
    input_df=df_engineered,
    target_col=TARGET_COL,
    verbose=2,
    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=3,  # Reduced from standard 300 for speed (demo only)
    random_state=42,
    n_jobs=-1,
    # Ordinary flux-RF leaf sizes, and the reason this example runs in seconds.
    # Left at the sklearn defaults (leaf=1, no depth limit) three trees grow one
    # leaf per record on the three-year pool, and TreeSHAP's cost scales with
    # leaves x depth^2 -- that alone made this the slowest example in the suite.
    min_samples_split=10,
    min_samples_leaf=5,
    # SHAP explains a seeded 5000-row sample per year. Its cost is linear in rows
    # and mean |SHAP| converges early, so the per-year ranking below is unchanged.
    shap_max_rows=5000,
)

# Create yearpools: each year gets its target year +/- 1 neighbors
gf.create_yearpools()

# Initialize models for each year using their respective data pools
gf.initialize_yearly_models()
  > Initializing model for 2020 ...

────── GAP-FILLING START — NEE_CUT_REF_orig · RF (RandomForestRegressor) ───────
  > Initializing model for 2021 ...

────── GAP-FILLING START — NEE_CUT_REF_orig · RF (RandomForestRegressor) ───────
  > Initializing model for 2022 ...

────── GAP-FILLING START — NEE_CUT_REF_orig · RF (RandomForestRegressor) ───────

Feature reduction across all years (optional)

Identifies features that are important across all years. Fits one model per year using SHAP, prunes weak features, then re-initialises the year pools. Skipped here for speed (only 3 features + n_estimators=3 leaves nothing to prune). Enable in production when working with many engineered features.

gf.reduce_features_across_years() print(f”Features retained across all years: {gf.features_reduced_across_years}”)

Fill gaps with year-specific models

Apply each year’s trained model to fill missing values in that year.

gf.fillgaps()

print(f"Gap-filling complete. Gapfilled series: {gf.gapfilled_.name}")
  > Training model for 2020 ...

─────────────── MODEL TRAINING & TESTING — NEE_CUT_REF_orig · RF ───────────────
  > 7 feature(s), 17,854 complete record(s) of 52,608 (2020-01-01 00:15:00 to
2022-12-31 23:45:00)
  > Train/test split: 13,390 train / 4,464 test (25% held out)
  > Test set is a RANDOM subset of the complete records, not a temporal block.
This reproduces the gap-filling task: gaps lie between observed records and are
filled from the drivers at the same timestamp.
                Configuration
┏━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━┓
┃ setting           ┃                 value ┃
┡━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━┩
│ regressor         │ RandomForestRegressor │
│ target            │      NEE_CUT_REF_orig │
│ test_size         │                  0.25 │
│ below_zero        │                  None │
│ n_estimators      │                     3 │
│ random_state      │                    42 │
│ n_jobs            │                    -1 │
│ min_samples_split │                    10 │
│ min_samples_leaf  │                     5 │
└───────────────────┴───────────────────────┘
                   Held-out test scores
┏━━━━━━━━┳━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓
┃ metric ┃  value ┃ description                           ┃
┡━━━━━━━━╇━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┩
│ R2     │ 0.5971 │ coeff. of determination (1 = perfect) │
│ RMSE   │  3.652 │ root mean squared error               │
│ MAE    │  2.602 │ mean absolute error                   │
│ MedAE  │  1.861 │ median absolute error                 │
│ MAPE   │  2.033 │ mean absolute % error                 │
│ MAXE   │  24.16 │ max error                             │
│ MSE    │  13.34 │ mean squared error                    │
└────────┴────────┴───────────────────────────────────────┘
  Top feature importances (held-out test)
┏━━━┳━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━┳━━━━━━━━┓
┃ # ┃ feature       ┃ mean |SHAP| ┃     SD ┃
┡━━━╇━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━╇━━━━━━━━┩
│ 1 │ Rg_f          │      3.2494 │ 1.9515 │
│ 2 │ Tair_f        │      1.3856 │ 1.0268 │
│ 3 │ .VPD_f-1      │      0.8586 │ 0.6355 │
│ 4 │ .RECORDNUMBER │      0.4624 │ 0.5234 │
│ 5 │ .Tair_f-1     │      0.3799 │ 0.3779 │
│ 6 │ .Rg_f-1       │      0.2598 │ 0.2265 │
│ 7 │ VPD_f         │      0.2270 │ 0.2195 │
└───┴───────────────┴─────────────┴────────┘
  v Training complete.
  > Gap-filling 2020 ...

───────────────────── GAP-FILLING — NEE_CUT_REF_orig · RF ──────────────────────
  > Predicted 52608 records where all features available.
  > Filling 34754 missing records in NEE_CUT_REF_orig_gfRF ...
  > Fallback: filling 0 remaining gaps in NEE_CUT_REF_orig_gfRF ...
  > Observed: 17,854  |  gaps filled: 34,754 (34,754 full model, 0 fallback)
  > Coverage now 100.0%  (52,608 of 52,608 records)
   In-sample scores (all data, incl. training — optimistic)
┏━━━━━━━━┳━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓
┃ metric ┃     value ┃ description                           ┃
┡━━━━━━━━╇━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┩
│ R2     │     0.745 │ coeff. of determination (1 = perfect) │
│ RMSE   │     2.849 │ root mean squared error               │
│ MAE    │     1.948 │ mean absolute error                   │
│ MedAE  │     1.309 │ median absolute error                 │
│ MAPE   │ 5.733e+11 │ mean absolute % error                 │
│ MAXE   │     24.16 │ max error                             │
│ MSE    │     8.116 │ mean squared error                    │
└────────┴───────────┴───────────────────────────────────────┘
   Feature importances (final gap-filling
                   model)
┏━━━┳━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━┳━━━━━━━━┓
┃ # ┃ feature       ┃ mean |SHAP| ┃     SD ┃
┡━━━╇━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━╇━━━━━━━━┩
│ 1 │ Rg_f          │      3.2535 │ 1.9513 │
│ 2 │ Tair_f        │      1.3963 │ 1.0391 │
│ 3 │ .VPD_f-1      │      0.8566 │ 0.6364 │
│ 4 │ .RECORDNUMBER │      0.4666 │ 0.5316 │
│ 5 │ .Tair_f-1     │      0.3818 │ 0.3771 │
│ 6 │ .Rg_f-1       │      0.2603 │ 0.2264 │
│ 7 │ VPD_f         │      0.2258 │ 0.2190 │
└───┴───────────────┴─────────────┴────────┘
  > Training model for 2021 ...

─────────────── MODEL TRAINING & TESTING — NEE_CUT_REF_orig · RF ───────────────
  > 7 feature(s), 17,854 complete record(s) of 52,608 (2020-01-01 00:15:00 to
2022-12-31 23:45:00)
  > Train/test split: 13,390 train / 4,464 test (25% held out)
  > Test set is a RANDOM subset of the complete records, not a temporal block.
This reproduces the gap-filling task: gaps lie between observed records and are
filled from the drivers at the same timestamp.
                Configuration
┏━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━┓
┃ setting           ┃                 value ┃
┡━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━┩
│ regressor         │ RandomForestRegressor │
│ target            │      NEE_CUT_REF_orig │
│ test_size         │                  0.25 │
│ below_zero        │                  None │
│ n_estimators      │                     3 │
│ random_state      │                    42 │
│ n_jobs            │                    -1 │
│ min_samples_split │                    10 │
│ min_samples_leaf  │                     5 │
└───────────────────┴───────────────────────┘
                   Held-out test scores
┏━━━━━━━━┳━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓
┃ metric ┃  value ┃ description                           ┃
┡━━━━━━━━╇━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┩
│ R2     │ 0.5971 │ coeff. of determination (1 = perfect) │
│ RMSE   │  3.652 │ root mean squared error               │
│ MAE    │  2.602 │ mean absolute error                   │
│ MedAE  │  1.861 │ median absolute error                 │
│ MAPE   │  2.033 │ mean absolute % error                 │
│ MAXE   │  24.16 │ max error                             │
│ MSE    │  13.34 │ mean squared error                    │
└────────┴────────┴───────────────────────────────────────┘
  Top feature importances (held-out test)
┏━━━┳━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━┳━━━━━━━━┓
┃ # ┃ feature       ┃ mean |SHAP| ┃     SD ┃
┡━━━╇━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━╇━━━━━━━━┩
│ 1 │ Rg_f          │      3.2494 │ 1.9515 │
│ 2 │ Tair_f        │      1.3856 │ 1.0268 │
│ 3 │ .VPD_f-1      │      0.8586 │ 0.6355 │
│ 4 │ .RECORDNUMBER │      0.4624 │ 0.5234 │
│ 5 │ .Tair_f-1     │      0.3799 │ 0.3779 │
│ 6 │ .Rg_f-1       │      0.2598 │ 0.2265 │
│ 7 │ VPD_f         │      0.2270 │ 0.2195 │
└───┴───────────────┴─────────────┴────────┘
  v Training complete.
  > Gap-filling 2021 ...

───────────────────── GAP-FILLING — NEE_CUT_REF_orig · RF ──────────────────────
  > Predicted 52608 records where all features available.
  > Filling 34754 missing records in NEE_CUT_REF_orig_gfRF ...
  > Fallback: filling 0 remaining gaps in NEE_CUT_REF_orig_gfRF ...
  > Observed: 17,854  |  gaps filled: 34,754 (34,754 full model, 0 fallback)
  > Coverage now 100.0%  (52,608 of 52,608 records)
   In-sample scores (all data, incl. training — optimistic)
┏━━━━━━━━┳━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓
┃ metric ┃     value ┃ description                           ┃
┡━━━━━━━━╇━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┩
│ R2     │     0.745 │ coeff. of determination (1 = perfect) │
│ RMSE   │     2.849 │ root mean squared error               │
│ MAE    │     1.948 │ mean absolute error                   │
│ MedAE  │     1.309 │ median absolute error                 │
│ MAPE   │ 5.733e+11 │ mean absolute % error                 │
│ MAXE   │     24.16 │ max error                             │
│ MSE    │     8.116 │ mean squared error                    │
└────────┴───────────┴───────────────────────────────────────┘
   Feature importances (final gap-filling
                   model)
┏━━━┳━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━┳━━━━━━━━┓
┃ # ┃ feature       ┃ mean |SHAP| ┃     SD ┃
┡━━━╇━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━╇━━━━━━━━┩
│ 1 │ Rg_f          │      3.2535 │ 1.9513 │
│ 2 │ Tair_f        │      1.3963 │ 1.0391 │
│ 3 │ .VPD_f-1      │      0.8566 │ 0.6364 │
│ 4 │ .RECORDNUMBER │      0.4666 │ 0.5316 │
│ 5 │ .Tair_f-1     │      0.3818 │ 0.3771 │
│ 6 │ .Rg_f-1       │      0.2603 │ 0.2264 │
│ 7 │ VPD_f         │      0.2258 │ 0.2190 │
└───┴───────────────┴─────────────┴────────┘
  > Training model for 2022 ...

─────────────── MODEL TRAINING & TESTING — NEE_CUT_REF_orig · RF ───────────────
  > 7 feature(s), 17,854 complete record(s) of 52,608 (2020-01-01 00:15:00 to
2022-12-31 23:45:00)
  > Train/test split: 13,390 train / 4,464 test (25% held out)
  > Test set is a RANDOM subset of the complete records, not a temporal block.
This reproduces the gap-filling task: gaps lie between observed records and are
filled from the drivers at the same timestamp.
                Configuration
┏━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━┓
┃ setting           ┃                 value ┃
┡━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━┩
│ regressor         │ RandomForestRegressor │
│ target            │      NEE_CUT_REF_orig │
│ test_size         │                  0.25 │
│ below_zero        │                  None │
│ n_estimators      │                     3 │
│ random_state      │                    42 │
│ n_jobs            │                    -1 │
│ min_samples_split │                    10 │
│ min_samples_leaf  │                     5 │
└───────────────────┴───────────────────────┘
                   Held-out test scores
┏━━━━━━━━┳━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓
┃ metric ┃  value ┃ description                           ┃
┡━━━━━━━━╇━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┩
│ R2     │ 0.5971 │ coeff. of determination (1 = perfect) │
│ RMSE   │  3.652 │ root mean squared error               │
│ MAE    │  2.602 │ mean absolute error                   │
│ MedAE  │  1.861 │ median absolute error                 │
│ MAPE   │  2.033 │ mean absolute % error                 │
│ MAXE   │  24.16 │ max error                             │
│ MSE    │  13.34 │ mean squared error                    │
└────────┴────────┴───────────────────────────────────────┘
  Top feature importances (held-out test)
┏━━━┳━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━┳━━━━━━━━┓
┃ # ┃ feature       ┃ mean |SHAP| ┃     SD ┃
┡━━━╇━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━╇━━━━━━━━┩
│ 1 │ Rg_f          │      3.2494 │ 1.9515 │
│ 2 │ Tair_f        │      1.3856 │ 1.0268 │
│ 3 │ .VPD_f-1      │      0.8586 │ 0.6355 │
│ 4 │ .RECORDNUMBER │      0.4624 │ 0.5234 │
│ 5 │ .Tair_f-1     │      0.3799 │ 0.3779 │
│ 6 │ .Rg_f-1       │      0.2598 │ 0.2265 │
│ 7 │ VPD_f         │      0.2270 │ 0.2195 │
└───┴───────────────┴─────────────┴────────┘
  v Training complete.
  > Gap-filling 2022 ...

───────────────────── GAP-FILLING — NEE_CUT_REF_orig · RF ──────────────────────
  > Predicted 52608 records where all features available.
  > Filling 34754 missing records in NEE_CUT_REF_orig_gfRF ...
  > Fallback: filling 0 remaining gaps in NEE_CUT_REF_orig_gfRF ...
  > Observed: 17,854  |  gaps filled: 34,754 (34,754 full model, 0 fallback)
  > Coverage now 100.0%  (52,608 of 52,608 records)
   In-sample scores (all data, incl. training — optimistic)
┏━━━━━━━━┳━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓
┃ metric ┃     value ┃ description                           ┃
┡━━━━━━━━╇━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┩
│ R2     │     0.745 │ coeff. of determination (1 = perfect) │
│ RMSE   │     2.849 │ root mean squared error               │
│ MAE    │     1.948 │ mean absolute error                   │
│ MedAE  │     1.309 │ median absolute error                 │
│ MAPE   │ 5.733e+11 │ mean absolute % error                 │
│ MAXE   │     24.16 │ max error                             │
│ MSE    │     8.116 │ mean squared error                    │
└────────┴───────────┴───────────────────────────────────────┘
   Feature importances (final gap-filling
                   model)
┏━━━┳━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━┳━━━━━━━━┓
┃ # ┃ feature       ┃ mean |SHAP| ┃     SD ┃
┡━━━╇━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━╇━━━━━━━━┩
│ 1 │ Rg_f          │      3.2535 │ 1.9513 │
│ 2 │ Tair_f        │      1.3963 │ 1.0391 │
│ 3 │ .VPD_f-1      │      0.8566 │ 0.6364 │
│ 4 │ .RECORDNUMBER │      0.4666 │ 0.5316 │
│ 5 │ .Tair_f-1     │      0.3818 │ 0.3771 │
│ 6 │ .Rg_f-1       │      0.2603 │ 0.2264 │
│ 7 │ VPD_f         │      0.2258 │ 0.2190 │
└───┴───────────────┴─────────────┴────────┘
Gap-filling complete. Gapfilled series: NEE_CUT_REF_orig_gfRF

Examine per-year performance

Each year has its own R^2, MAE, and other metrics showing how well that year’s model performs.

from statistics import mean

mae_list = []
r2_list = []

print("\nPER-YEAR MODEL PERFORMANCE:")
print(f"{'Year':<6} {'R²':<10} {'MAE':<10}")
print("-" * 26)

for year in sorted(gf.scores_.keys()):
    scores = gf.scores_[year]
    mae_list.append(scores['mae'])
    r2_list.append(scores['r2'])
    print(f"{year:<6} {scores['r2']:<10.4f} {scores['mae']:<10.4f}")

print("-" * 26)
print(f"{'MEAN':<6} {mean(r2_list):<10.4f} {mean(mae_list):<10.4f}")
PER-YEAR MODEL PERFORMANCE:
Year   R²         MAE
--------------------------
2020   0.7450     1.9481
2021   0.7450     1.9481
2022   0.7450     1.9481
--------------------------
MEAN   0.7450     1.9481

Feature importance across years

The feature importance varies by year, showing how seasonal factors shift. For example, radiation (Rg_f) is always top predictor, but its relative importance and the rank of other features change across months/years.

TOP 5 FEATURES BY YEAR:
YEAR               2020      2021      2022
FEATURE
Rg_f           3.253472  3.253472  3.253472
Tair_f         1.396305  1.396305  1.396305
.VPD_f-1       0.856649  0.856649  0.856649
.RECORDNUMBER  0.466607  0.466607  0.466607
.Tair_f-1      0.381849  0.381849  0.381849

Visualization: before and after gap-filling

fig, axs = plt.subplots(ncols=2, figsize=(18, 9))
dv.plotting.HeatmapDateTime(series=df[TARGET_COL]).plot(ax=axs[0])
dv.plotting.HeatmapDateTime(series=gf.gapfilling_df_[gf.gapfilled_.name]).plot(ax=axs[1])

axs[0].set_title("Observed NEE (with gaps)", fontsize=14, fontweight='bold')
axs[1].set_title("Gap-Filled NEE (yearly RF models)", fontsize=14, fontweight='bold')
axs[0].tick_params(labelleft=False)
axs[1].tick_params(labelleft=False)

fig.show()

print("[OK] Long-term random forest gap-filling complete.")
Observed NEE (with gaps), Gap-Filled NEE (yearly RF models)
[OK] Long-term random forest gap-filling complete.

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

Gallery generated by Sphinx-Gallery