Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

🖥️ Lecture slides: Session 10 (Fri Oct 23)

Learning outcomes. By the end of this notebook you can:

  1. find and repair unit, time-base, sentinel and gap problems in a multi-gauge discharge table, and write a description of the dataset that a script reads back;

  2. measure the diversity, class balance, noise level and intrinsic dimension of a labeled geoscience dataset;

  3. build a within-domain training and validation set and out-of-domain test sets along a statistical, a spatiotemporal and a physical axis, and explain why the scores differ;

  4. score a dataset on the class rubric (A1 to A4, B1 to B7, 0/1/2) with one line of evidence per criterion.

To run it. From the repository root, pixi run jupyter lab. Everything is generated in the notebook by the course package mlgeo_synth; no download is needed. Run the setup cell below once. Each Your turn cell is followed by a check that prints correct, a hint, or not answered yet. If your answer is not correct yet, the check puts the reference result in place so that the rest of the notebook runs; your own result is kept with the suffix _yours.

Source

1. Analysis-ready and AI-ready

Analysis-ready data let a scientist compute without redoing the provider’s work: the source is known, units and time base are consistent, gaps and flags are documented, and the files are in a standard format with a description a script can read.

AI-ready data also support training a model and testing whether it generalizes. That asks more questions: how many independent units the data cover, how the targets are distributed, how large the noise is, where the labels come from, how many features per sample, and whether the data can be split into a within-domain training set and an out-of-domain test set. Analysis-ready is necessary, not sufficient.

The class rubric has eleven criteria. Each is scored 0 (missing), 1 (present but incomplete) or 2 (another team can verify it).

CriterionWhat it asks
A1Provenancesource, version or retrieval date, license, citation; synthetic parts disclosed
A2Homogenizationconsistent units, reference frame, coordinates, time base and sampling; instrument or processing changes corrected or flagged
A3Quality and gapsquality flags, missing, sentinel and censored values, and their mechanism documented
A4Structure and metadatatidy tables or labeled arrays in a standard format, variables and units in a file a script can read
B1Diversityhow many independent units (stations, events, regions, years, instruments), not how many rows
B2Distributiondistribution of targets and inputs, imbalance and long tails, compared with the population the model will face
B3Noise characterizationinstrumental noise separated from natural variability; a noise level or signal-to-noise estimate
B4Augmentation potentialphysically valid transformations, and the ones that break the physics
B5Labelssource, quality, uncertainty, consistency; or the potential for self-supervised learning
B6Dimensionalitysamples vs features, input shape, variance captured by a few principal components
B7Partitioning potentialwithin-domain training and validation, out-of-domain test along a stated axis, leakage controlled

You will score the dataset of this notebook on this rubric at the end (section 5), and your project dataset with the same rubric.

2. The dataset: daily discharge at four gauges

A stream gauge records the water level (stage) every few minutes; the provider converts stage to discharge with a rating curve fitted to occasional direct measurements, and publishes the daily mean discharge in cubic meters per second (m³/s), or cubic feet per second (ft³/s) in the United States. A flood is a few days of discharge far above the seasonal flow.

The four gauges below are synthetic. Each stands for a runoff regime of Washington State:

  • G1 coastal rain: winter maximum; floods from atmospheric-river storms between October and March.

  • G2 snowmelt: low winter flow, a freshet from May to July; floods from rain on snow.

  • G3 mixed rain and snow: a winter and a spring maximum.

  • G4 semi-arid: a few m³/s; rare, short flash floods from convective storms.

Each series is a seasonal background, with wet and dry years, plus white measurement noise, plus floods injected as a Poisson process by mlgeo_synth.inject_rare_events with log-normal peak sizes, 2010 to 2024. The generator returns the label (flood, 1 on days inside a flood) and a flood number (event_id, -1 outside floods). The provider-style table has the problems of a real download: one gauge in ft³/s, ice-affected days written as -999, an outage with missing rows, and a sensor lost at a flood peak. The task we pose: detect flood days from the previous seven days of discharge.

                          regime  elevation_m  units
gauge_id                                            
G1                  coastal rain           60   m3/s
G2                      snowmelt         1100   m3/s
G3           mixed rain and snow          450  ft3/s
G4        semi-arid flash floods          300   m3/s
Loading...
<Figure size 1200x380 with 2 Axes>

G3 sits a factor of 35 above the others: the ratio between a cubic meter and a cubic foot. The map uses Natural Earth coastlines and borders (course copy in snapshots/); the gauge positions are chosen to match the regimes, not real gauges.

3. Analysis readiness (A1 to A4)

A1 Provenance

Every value here comes from mlgeo_synth with fixed seeds (11 to 14, one per gauge); the background equations and flood parameters are in the setup cell. The dataset is entirely synthetic, which must be stated in its description. For a real download, A1 asks for the provider (for example, USGS National Water Information System), the gauge numbers, the retrieval date, the data version (provisional or approved records), the license and the citation. We write these in the description in A4.

A2 Homogenization: units and time base

Your turn: convert to one unit and check the time base. Write q_m3s, the discharge of every row of raw in m³/s (multiply by 0.0283168 where the gauge reports ft³/s, using GAUGES['units']), and steps, the count of each interval in days between consecutive dates of the same gauge.

Hint: np.where(raw['gauge_id'].map(GAUGES['units']) == 'ft3/s', 0.0283168, 1.0); raw.groupby('gauge_id')['date'].diff().dt.days.value_counts().

[A2] not answered yet
[q_m3s, steps] using the reference result so the next cells run.

Worked solution below (click ⋯ to open).

Notebook Cell
date
1.0     21821
91.0        1
Name: count, dtype: int64
date
1.0     21821
91.0        1
Name: count, dtype: int64
(21916, 5)

One step of 91 days: G3 lost three months of rows in 2016. A gap encoded as absent rows is invisible to anyone who looks at the table without checking the time step. After reindex the outage is explicit NaN.

A3 Quality and gaps

Your turn: count sentinels and gaps. Write n_sentinel, the number of -999 values per gauge in daily['q_m3s']; q_clean, the same column with -999 replaced by NaN; and n_missing, the number of NaN per gauge in q_clean.

Hint: (daily['q_m3s'] == -999).groupby(daily['gauge_id']).sum(); Series.replace(-999, np.nan); isna().

[A3] not answered yet
[q_clean, n_sentinel, n_missing] using the reference result so the next cells run.

Worked solution below (click ⋯ to open).

Notebook Cell
          sentinel -999  missing after cleaning
gauge_id                                       
G1                    0                       0
G2                  144                     144
G3                    0                      90
G4                    0                       3
<Figure size 1100x300 with 1 Axes>

Three gap mechanisms, and they are not equivalent:

  • G2, ice (-999, 36 days in each of four winters): ice on the channel control makes the rating curve invalid. The flow is not zero and not unknown in the same way as an outage: it is low winter flow, censored by the method. Had we left -999 in place, the mean winter flow would be negative.

  • G3, outage (90 days in spring 2016): missing for reasons unrelated to the flow. Interpolating is defensible for a slowly varying series, not across a flood.

  • G4, sensor lost at the peak (3 days): missing because the flow was extreme. Every statistic of flood peaks at G4 is biased low, and a model never sees the largest flood. This is informative missingness, and it is common: gauges fail during the floods they were built for.

A4 Structure and metadata

The table daily is tidy: one row per gauge and day, one column per variable. The description of the dataset travels with it as a YAML file next to a Parquet copy of the table. Part of it is written below; you complete it.

Your turn: complete and read back the description. Add the entry for q_m3s (units and a short description) and a missing_values entry that states the encoding and the three gap mechanisms; write description to OUTDIR / 'description.yml' and read the file back into desc.

Hint: description['variables']['q_m3s'] = {...}; (OUTDIR / 'description.yml').write_text(yaml.safe_dump(description)); yaml.safe_load(...read_text()).

[A4] not answered yet
[desc] using the reference result so the next cells run.

Worked solution below (click ⋯ to open).

Notebook Cell
columns without units: none
synthetic disclosed: True | q_m3s: {'units': 'm3/s', 'description': 'daily mean river discharge'}
files: ['daily_discharge.parquet', 'description.yml']

4. AI readiness (B1 to B7)

B1 Diversity

Your turn: count units, not rows. Write n_rows, n_gauges, n_years (distinct calendar years) and n_floods (distinct floods over all gauges; a flood is a pair gauge, event_id).

Hint: len, nunique(), daily['date'].dt.year, and drop_duplicates() on ['gauge_id', 'event_id'].

[B1] not answered yet
[n_rows, n_gauges, n_years, n_floods] using the reference result so the next cells run.

Worked solution below (click ⋯ to open).

Notebook Cell
21916 rows, but 4 gauges x 15 years = 60 gauge-years and 185 floods
flood days: 943, i.e. 5.1 rows per flood

Twenty thousand rows are about two hundred independent floods at four gauges. Consecutive days are not independent samples, and a model that learns flood detection at four gauges has seen four basins, four rating curves, four climates. The number that limits what the model can learn is the number of floods and gauges.

B2 Distribution

Your turn: class balance and flood sizes. Write flood_frac, the fraction of flood days per gauge, and peaks, the largest discharge of each flood (a Series indexed by gauge and event_id).

Hint: groupby('gauge_id')['flood'].mean(); daily[daily['event_id'] >= 0].groupby(['gauge_id', 'event_id'])['q_m3s'].max().

[B2] not answered yet
[flood_frac, peaks] using the reference result so the next cells run.

Worked solution below (click ⋯ to open).

Notebook Cell
flood-day fraction per gauge: {'G1': 0.05, 'G2': 0.047, 'G3': 0.063, 'G4': 0.013}
<Figure size 700x300 with 1 Axes>

Between 1.3% and 6.3% of days are flood days: a model that always answers “no flood” is more than 90% accurate. We therefore score with average precision (AP), the area under the precision-recall curve, whose value for a random guess equals the flood fraction. The flood sizes are log-normal: the largest flood at each gauge is several times the median, and those are the floods that matter for hazard. The G4 maximum is truncated by the lost sensor (A3).

B3 Noise characterization

The discharge has three parts: the seasonal cycle and the wet and dry years (natural variability, the signal for a water-supply question), the floods (the signal here), and measurement noise (stage sensor, rating curve). Day-to-day differences on non-flood days remove most of the seasonal cycle and keep the noise; the median absolute difference ignores the occasional jump at the end of a flood.

Your turn: estimate the noise level and the signal-to-noise ratio. Write noise_sd, the measurement noise per gauge (1.4826 times the median absolute day-to-day difference on non-flood days, divided by √2), and snr, the median flood excess ev['excess'] per gauge divided by noise_sd.

Hint: daily[daily['flood'] == 0].groupby('gauge_id')['q_m3s'].diff(), then .abs().groupby(daily['gauge_id']).median().

[B3] not answered yet
[noise_sd, snr] using the reference result so the next cells run.

Worked solution below (click ⋯ to open).

Notebook Cell
    estimated noise (m³/s)  generator truth (m³/s)  SNR of the median flood
G1                    2.49                     2.5                     18.9
G2                    1.49                     1.5                     13.3
G3                    2.02                     2.0                     13.3
G4                    0.40                     0.4                     39.6

The estimate recovers the generator’s noise to within a few percent. With real data there is no truth column, and the estimate is the number that goes into the description. The median flood stands 13 to 40 times above the noise: small floods are separable from noise, and the difficulty is detecting a flood before it peaks, from the days before.

B4 Augmentation potential

Augmentation adds training samples by transforming existing ones. A transformation is valid if the result is a hydrograph the river could have produced: the same flood shifted by a few days, or the same flood with a new draw of measurement noise at the level measured in B3. Reversing time is not valid: floods rise in hours to days and recede over days to weeks, because the recession drains storage in the basin; a reversed hydrograph rises slowly and drops abruptly.

Your turn: one valid and one invalid augmentation. Write aug_noise, window plus Gaussian noise at the level noise_sd['G1'] drawn with rng_aug, and aug_flip, window reversed in time.

Hint: rng_aug.normal(0, noise_sd['G1'], len(window)); window[::-1].

[B4] not answered yet
[aug_noise, aug_flip] using the reference result so the next cells run.

Worked solution below (click ⋯ to open).

Notebook Cell
<Figure size 800x300 with 1 Axes>

Shifting a window in time is valid only if the label shifts with it, and a flood moved from November to August at G1 would put it in the dry season, outside the physics. Adding noise at G4 at the G1 level would produce negative discharge. Synthetic floods with known truth, like the ones in this notebook, are a third route, valid as long as their shape matches the basin (disclosed in A1).

B5 Labels

Our labels come from the generator: exact, and unavailable for a real river. Real flood labels come from a threshold (the National Weather Service flood stage, or a percentile of discharge), from a peak-over-threshold analysis, or from reports of damage. Two labelers rarely agree on when a flood ends.

Your turn: compare two labelers. Write label_thr, 1 where q_m3s exceeds the gauge’s 95th percentile q95, agree, the fraction of days where label_thr equals flood, and missed, the fraction of generator flood days that the threshold labels 0.

Hint: (daily['q_m3s'] > daily['q95']).astype(int); .mean(); ((label_thr == 0) & (daily['flood'] == 1)).sum().

[B5] not answered yet
[label_thr, agree, missed] using the reference result so the next cells run.

Worked solution below (click ⋯ to open).

Notebook Cell
agreement 0.947; the threshold misses 54% of the generator's flood days
threshold      0    1
generator            
0          20319  654
1            512  431

The agreement looks high only because most days are dry days on which both labelers say 0. The threshold misses the small floods during the high season and the recession tails, and flags high seasonal flow (G2 freshet) that is not a flood. Labels with this kind of disagreement are common; the description should state which definition was used. For self-supervised learning the situation is favorable: decades of unlabeled daily discharge at thousands of gauges exist, with strong structure (seasonality, recessions) that a model can learn before it sees any label.

B6 Dimensionality

The input of the flood detector is a window of seven daily discharges plus the day of year (as sine and cosine): nine features per sample.

(21615, 9)

Your turn: variance explained by principal components. Write cum_var, the cumulative fraction of variance explained by the principal components of the standardized feature table X.

Hint: PCA().fit(StandardScaler().fit_transform(X)), then np.cumsum(pca.explained_variance_ratio_).

[B6] not answered yet
[cum_var] using the reference result so the next cells run.

Worked solution below (click ⋯ to open).

Notebook Cell
cumulative variance explained: [0.736 0.848 0.945 0.966 0.978 0.986 0.991 0.996 1.   ]

About 20,000 samples for 9 features is a comfortable ratio for a random forest. The first principal component alone explains about three quarters of the variance: seven consecutive days of discharge are nearly copies of each other, and the intrinsic dimension of the window is closer to three (level, day of year as two components) than to nine. That redundancy is also why neighboring days are near-copies of each other, the problem of B7.

B7 Partitioning: within domain and out of domain

Training and validation sets come from the same domain; validation tests interpolation and is used to choose settings. The test set comes from outside the training domain along a stated axis, and tests generalization. We define the domain as gauges G1 to G3, years 2010 to 2021. Validation is 20% of the gauge-months of that domain, held out as whole months so that consecutive days do not straddle the split. Everything else is out of domain: the years 2022 to 2024 (time) and gauge G4 (space). One model, a random forest classifier, for all the tests.

train 10301, validation 2605, last years 3246, gauge G4 5463 samples

Statistical axis: distance to the training set

A sample is out of domain statistically if it lies far from every training sample in feature space. We measure the distance to the nearest training sample after standardizing the features with the training mean and standard deviation (standardizing with all the data would leak the test distribution into the scale). A sample is “outside” if its distance exceeds the 95th percentile of the distances between each training sample and its nearest other training sample.

Your turn: distances to the training set. Fit scaler on X_train only; write d_train, the distance from each training sample to its nearest other training sample, d_eval, the distance from each row of X_eval to its nearest training sample, d_cut, the 95th percentile of d_train, and outside, True where d_eval exceeds d_cut.

Hint: NearestNeighbors(n_neighbors=2).fit(Z_train); nn.kneighbors(Z_train)[0][:, 1]; nn.kneighbors(Z_eval, n_neighbors=1)[0][:, 0]; np.percentile.

[B7.stat] not answered yet
[d_train, d_eval, d_cut, outside] using the reference result so the next cells run.

Worked solution below (click ⋯ to open).

Notebook Cell
21% of evaluation samples are outside; mean squared error: validation 0.0324, outside 0.1109
flood days: 2.1% of samples inside, 9.0% outside
share outside: validation 6%, last years 8%, gauge G4 36%
<Figure size 700x300 with 1 Axes>

The error grows with distance from the training set. The far samples are the rare states of the river: flood days, which the training set covers thinly, and G4, a third of whose days are outside. Few validation samples are outside, as expected for a within-domain set. The distance needs no label, so it can be computed for any new sample before the model is trusted with it.

Spatiotemporal axis: held-out years and a held-out gauge

Your turn: score each partition. Write ap_val, ap_late and ap_gauge, the average precision of p_eval against y_eval on the validation samples, the last years, and gauge G4.

Hint: average_precision_score(y_eval[is_val], p_eval[is_val]), and the same with is_late and is_g4.

[B7.space] not answered yet
[ap_val, ap_late, ap_gauge] using the reference result so the next cells run.

Worked solution below (click ⋯ to open).

Notebook Cell
AP random split 0.736 | validation 0.739 | last years 0.703 | gauge G4 0.200

The random split and the validation score about the same, and both look good. The random split, though, has G4 days in its training set, so its score is a statement about gauges the model has already seen. The held-out years score close to validation, because 2022 to 2024 at G1 to G3 come from the same climate and rating curves. The held-out gauge scores far lower: G4 floods of 10 to 20 m³/s look like ordinary winter flow at G1. A random split would have hidden that a flood detector built this way does not transfer to a new basin.

Cross-validation at G1 alone (5 folds each): shuffled KFold scatters the days of each flood over training and test folds, TimeSeriesSplit trains on the past only, GroupKFold keeps each flood, and each 30-day block of dry days, in one fold.

KFold, shuffled      AP = 0.730 ± 0.032
TimeSeriesSplit      AP = 0.642 ± 0.105
GroupKFold by flood  AP = 0.707 ± 0.045

Shuffled KFold scores a little above GroupKFold. The gap is small on this dataset: measurement noise keeps neighboring days from being copies of each other, and a flood is detected from its rise over the last two or three days. It grows with smooth inputs (30-day means, snowpack, soil moisture), whose neighboring values are nearly identical. TimeSeriesSplit scores lowest, partly because its first folds train on three years only.

Leakage by preprocessing. Every statistic computed from the data (a mean, a standard deviation, a PCA basis, a percentile, an imputation value) becomes part of the model. Computed on all the data before splitting, it carries information from the test set into training. Two cases: a scaler, and oversampling the rare class.

scaler fit on all data       AP last years = 0.528
scaler fit on training only  AP last years = 0.528
oversampling before the split: AP = 1.000 (copies of the same flood day on both sides)

The scaler barely changes the score here: a long, stationary record and two numbers per feature. The gap grows with short records, drifting test periods and richer preprocessing (PCA, imputation, feature selection). Oversampling before the split produces a near-perfect score that measures nothing. Rule: split first, then fit every preprocessing step, and resample, on the training set only.

Physical axis: floods larger than any in training

Hazard models are judged on the largest floods, which are by definition the rarest in any record. We pose a regression: estimate the flood peak above the pre-flood discharge (excess) from what is known in the first two days (q0, rise1, rise2), the season and the gauge’s mean flow. We train on floods whose excess is below the 80th percentile of all floods, and test on the larger ones.

145 floods below the threshold, 37 above

Your turn: train on small floods, test on large ones. Write small, True for floods with excess <= thr; fit peak_model on the small floods; write pred_large, its estimate for the large floods, and ratio_large, the median of estimated over observed excess for the large floods.

Hint: peak_model.fit(ev.loc[small, EV_FEATS], ev.loc[small, 'excess']); np.median(pred_large / ev.loc[~small, 'excess']).

[B7.phys] not answered yet
[pred_large, ratio_large] using the reference result so the next cells run.

Worked solution below (click ⋯ to open).

Notebook Cell
median estimated/observed: small floods 1.00, large floods 0.69 (linear model 0.99)
<Figure size 500x450 with 1 Axes>

The forest cannot return a value larger than the training targets it averages, so every large flood is capped near the largest training flood and underestimated. A linear model extrapolates, and does well here only because the synthetic flood shape is linear in amplitude by construction. Real rivers change physics as floods grow: water leaves the channel onto the floodplain, and the rating curve itself is extrapolated above the largest measured flow. The physical axis tests whether the model has learned something that holds outside the range of sizes it was shown.

Loading...

Report the out-of-domain scores with their axis. The validation score tells you the model learned the training domain; only the test scores tell you where it can be used.

5. Score this dataset on the rubric

Give each criterion 0, 1 or 2 and one line of evidence from this notebook. Be strict: 2 means another team could verify it from the files in data/ai_ready_demo/ and this notebook.

[rubric] 0 of 11 criteria scored with evidence; a criterion needs a score 0, 1 or 2 and one line of evidence

One instructor scoring below (click ⋯ to open). Discuss where yours differs.

Notebook Cell
[rubric] 11 of 11 criteria scored with evidence
total: 18 of 22

6. Your project dataset

Apply the same rubric to your project dataset: one score and one line of evidence per criterion, and the files or notebook cells that support each 2. For B7, name the axis of your test set and the independent unit you split by. The rubric is part of the project milestone; see the chapter assignment and the final project description.