-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRandomForest.py
More file actions
173 lines (134 loc) · 5.95 KB
/
Copy pathRandomForest.py
File metadata and controls
173 lines (134 loc) · 5.95 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
import numpy as np
from sklearn.ensemble import RandomForestRegressor
from Dataset import TMP_VARS, get_station_features, get_station_target
# ── RF hyperparameters (Table 3, state-independent) ───────────────────────
RF_PARAMS = {
'TMP': {'n_estimators': 100, 'max_depth': 13},
'WIND': {'n_estimators': 50, 'max_depth': 10},
}
# ── subsample training data ───────────────────────────────────────────────────
def subsample_training_data(train_idx, static_ds, time_indicators,
era5_ds, madis_ds, variable,
subsample_frac=0.01, seed=42):
"""
Collect a random subsample of training data across all train stations.
Paper uses 1% of total training data for RF.
Parameters
----------
train_idx : np.ndarray of station indices
static_ds : xr.Dataset, shape (station_id,)
time_indicators: dict from compute_time_indicators()
era5_ds : xr.Dataset, already time-sliced
madis_ds : xr.Dataset, already time-sliced
variable : str
subsample_frac : float, fraction of timesteps to sample per station
seed : int
Returns
-------
X_sub : np.ndarray, shape (n_samples, n_features)
y_sub : np.ndarray, shape (n_samples,)
"""
rng = np.random.default_rng(seed)
n_time = len(time_indicators['times'])
n_sub = max(1, int(n_time * subsample_frac))
X_list, y_list = [], []
for count, i in enumerate(train_idx):
# random time indices for this station
time_idx = rng.choice(n_time, size=n_sub, replace=False)
time_idx.sort()
X_i = get_station_features(i, static_ds, time_indicators, variable)
y_i = get_station_target(i, era5_ds, madis_ds, variable)
X_list.append(X_i[time_idx])
y_list.append(y_i[time_idx])
if (count + 1) % 100 == 0:
print(f'Subsample {variable}: {count + 1}/{len(train_idx)} stations', flush=True)
X_sub = np.concatenate(X_list, axis=0) # (n_train_stations * n_sub, n_features)
y_sub = np.concatenate(y_list, axis=0) # (n_train_stations * n_sub,)
print(f'[{variable}] Subsample shape: X={X_sub.shape} y={y_sub.shape}', flush=True)
return X_sub, y_sub
# ── evaluate on a set of stations ────────────────────────────────────────────
def eval_stations_rf(idx, static_ds, time_indicators, era5_ds, madis_ds,
variable, model):
"""
Compute RMSE over stations in idx.
Parameters
----------
idx : np.ndarray of station indices
model : fitted RandomForestRegressor
Returns
-------
rmse : float
"""
sq_err = []
for i in idx:
X_i = get_station_features(i, static_ds, time_indicators, variable)
y_i = get_station_target(i, era5_ds, madis_ds, variable)
e_hat_i = model.predict(X_i)
residual = y_i - e_hat_i
sq_err.append((residual ** 2).mean())
return np.sqrt(np.mean(sq_err))
# ── train ─────────────────────────────────────────────────────────────────────
def train_rf(train_idx, val_idx, static_ds, time_indicators,
era5_ds, madis_ds, variable,
subsample_frac=0.01, seed=42):
"""
Train RandomForestRegressor on subsampled training data.
Uses paper hyperparameters from Table 3 (state-independent config).
Parameters
----------
train_idx : np.ndarray of station indices
val_idx : np.ndarray of station indices
static_ds : xr.Dataset, shape (station_id,)
time_indicators : dict from compute_time_indicators()
era5_ds : xr.Dataset, already time-sliced
madis_ds : xr.Dataset, already time-sliced
variable : str
subsample_frac : float, fraction of timesteps per station
seed : int
Returns
-------
model : fitted RandomForestRegressor
"""
params = RF_PARAMS['TMP'] if variable in TMP_VARS else RF_PARAMS['WIND']
# subsample training data
print(f'[{variable}] Subsampling training data...', flush=True)
X_sub, y_sub = subsample_training_data(
train_idx, static_ds, time_indicators,
era5_ds, madis_ds, variable,
subsample_frac=subsample_frac, seed=seed,
)
# train RF with paper hyperparameters
print(f'[{variable}] Training RF: {params}', flush=True)
model = RandomForestRegressor(
n_estimators=params['n_estimators'],
max_depth=params['max_depth'],
n_jobs=-1,
random_state=seed,
)
model.fit(X_sub, y_sub)
# evaluate on validation set
print(f'[{variable}] Evaluating on validation set...', flush=True)
val_rmse = eval_stations_rf(
val_idx, static_ds, time_indicators,
era5_ds, madis_ds, variable, model,
)
print(f'[{variable}] Val RMSE={val_rmse}', flush=True)
return model
# ── predict ───────────────────────────────────────────────────────────────────
def predict_rf(i, static_ds, time_indicators, era5_ds, variable, model):
"""
Compute bias-corrected ERA5 for a single station i.
Parameters
----------
i : int, station index
era5_ds : xr.Dataset, already time-sliced
model : fitted RandomForestRegressor
Returns
-------
f_hat : np.ndarray, shape (n_time,), float32
"""
X_i = get_station_features(i, static_ds, time_indicators, variable)
e_hat = model.predict(X_i)
f_i = era5_ds[variable].values[i].astype(np.float64)
f_hat = (f_i - e_hat).astype(np.float32)
return f_hat