Note
Go to the end to download the full example code.
FEATURE ENGINEERING: 8-STAGE PIPELINE¶
Use FeatureEngineer to create ML-ready features: temporal encoding, lag, rolling stats, differencing, EMA, polynomial terms, STL decomposition, and record numbering.
Part of the diive library: https://github.com/holukas/diive
Load example data¶
import diive as dv
df_orig = dv.load_exampledata_parquet()
# Use 2020 data only for faster processing
keep = (df_orig.index.year == 2020)
df_data = df_orig[keep][['Tair_f', 'VPD_f', 'Rg_f']].copy()
df_data.columns = ['temperature', 'vapor_pressure_deficit', 'radiation']
print("Example data:")
print(f" Records: {len(df_data)}")
print(f" Period: {df_data.index.min().date()} to {df_data.index.max().date()}")
print(f" Columns: {list(df_data.columns)}")
> 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).
Example data:
Records: 17568
Period: 2020-01-01 to 2020-12-31
Columns: ['temperature', 'vapor_pressure_deficit', 'radiation']
Full 8-stage pipeline¶
Create ML-ready features in one pass. The stage numbers follow the
FeatureEngineer docstring. STL (stage 6) and the record number (stage 8,
add_continuous_record_number) stay off here.
from diive.core.ml.feature_engineer import FeatureEngineer
engineer = FeatureEngineer(
target_col='temperature',
# Stage 7: Timestamp features
vectorize_timestamps=True,
# Stage 1: Lag features
features_lag=[-2, -1],
# Stage 2: Rolling stats
features_rolling=[12, 24], # 6-hour, 12-hour windows
features_rolling_stats=['mean', 'std', 'min', 'max'],
# Stage 3: Differencing
features_diff=[1],
# Stage 4: EMA
features_ema=[6, 12],
# Stage 5: Polynomial
features_poly_degree=2,
# Stage 6: STL decomposition (optional)
features_stl=False,
)
df_full = engineer.fit_transform(df_data)
print(f"\nFeature engineering complete:")
print(f" Input: 3 columns (temperature, vapor_pressure_deficit, radiation)")
print(f" Output: {df_full.shape[1]} columns")
print(f" Features created: {df_full.shape[1] - 3}")
# Show first few rows
print(f"\nFirst 3 rows (sample columns):")
cols_to_show = ['temperature', 'vapor_pressure_deficit', 'radiation',
'.vapor_pressure_deficit-1', '.radiation_MEAN12', '.temperature_EMA6']
cols_available = [c for c in cols_to_show if c in df_full.columns]
print(df_full.iloc[:3][cols_available])
Feature engineering complete:
Input: 3 columns (temperature, vapor_pressure_deficit, radiation)
Output: 49 columns
Features created: 46
First 3 rows (sample columns):
temperature ... .radiation_MEAN12
TIMESTAMP_MIDDLE ...
2020-01-01 00:15:00 -0.610 ... 0.0
2020-01-01 00:45:00 -0.403 ... 0.0
2020-01-01 01:15:00 -0.517 ... 0.0
[3 rows x 5 columns]
All generated features¶
List all engineered features (columns in df_full not in df_data).
generated_features = [c for c in df_full.columns if c not in df_data.columns]
print("\n" + "=" * 70)
print(f"Generated Features ({len(generated_features)})")
print("=" * 70)
for i, feat in enumerate(sorted(generated_features), 1):
print(f"{i:2d}. {feat}")
======================================================================
Generated Features (46)
======================================================================
1. .DOY_COS
2. .DOY_SIN
3. .HOUR_COS
4. .HOUR_SIN
5. .MONTH_COS
6. .MONTH_SIN
7. .SEASON_COS
8. .SEASON_SIN
9. .WEEK_COS
10. .WEEK_SIN
11. .YEAR
12. .YEARDOY
13. .YEARMONTH
14. .YEARWEEK
15. .radiation-1
16. .radiation-2
17. .radiation_DIFF1
18. .radiation_EMA12
19. .radiation_EMA6
20. .radiation_MEAN12
21. .radiation_MEAN24
22. .radiation_POL2
23. .radiation_ROLLMAX12
24. .radiation_ROLLMAX24
25. .radiation_ROLLMIN12
26. .radiation_ROLLMIN24
27. .radiation_ROLLSD12
28. .radiation_ROLLSD24
29. .radiation_SD12
30. .radiation_SD24
31. .vapor_pressure_deficit-1
32. .vapor_pressure_deficit-2
33. .vapor_pressure_deficit_DIFF1
34. .vapor_pressure_deficit_EMA12
35. .vapor_pressure_deficit_EMA6
36. .vapor_pressure_deficit_MEAN12
37. .vapor_pressure_deficit_MEAN24
38. .vapor_pressure_deficit_POL2
39. .vapor_pressure_deficit_ROLLMAX12
40. .vapor_pressure_deficit_ROLLMAX24
41. .vapor_pressure_deficit_ROLLMIN12
42. .vapor_pressure_deficit_ROLLMIN24
43. .vapor_pressure_deficit_ROLLSD12
44. .vapor_pressure_deficit_ROLLSD24
45. .vapor_pressure_deficit_SD12
46. .vapor_pressure_deficit_SD24
Feature importance¶
Correlation with target shows which features matter most.
print("\n" + "=" * 60)
print("Feature importance (correlation with temperature)")
print("=" * 60)
correlations = df_full.corr()['temperature'].abs().sort_values(ascending=False)
for i, (feat, corr) in enumerate(correlations.head(12).items(), 1):
if feat != 'temperature':
print(f"{i:2}. {feat:<30} r = {corr:.3f}")
============================================================
Feature importance (correlation with temperature)
============================================================
2. .DOY_COS r = 0.706
3. .WEEK_COS r = 0.695
4. .vapor_pressure_deficit_ROLLMAX12 r = 0.685
5. .SEASON_COS r = 0.678
6. .vapor_pressure_deficit_ROLLMAX24 r = 0.672
7. .vapor_pressure_deficit_EMA6 r = 0.660
8. .vapor_pressure_deficit_SD24 r = 0.660
9. .vapor_pressure_deficit_ROLLSD24 r = 0.660
10. .vapor_pressure_deficit_EMA12 r = 0.656
11. vapor_pressure_deficit r = 0.653
12. .vapor_pressure_deficit-1 r = 0.652
Total running time of the script: (0 minutes 0.220 seconds)