Loading...
Loading...
Contributors:
Dataset URI:
10.5281/zenodo.23317498# Code and data for "A Benford's Law-Inspired Deep Learning Model for Streamflow Prediction" Jun Guo, Xinyu Chang, Yi Liu\*, Hui Qin, Shuang Zhu, Yunhui Bai, Shuhui Yang, Xiaojiong Xu School of Civil and Hydraulic Engineering, and Hubei Key Laboratory of Digital River Basin Science and Technology, Huazhong University of Science and Technology, Wuhan 430074, China. \*Corresponding author: Yi Liu (prof_liuyi@hust.edu.cn) This package holds what is needed to reproduce every number, table and figure in the paper (submitted to *Journal of Hydrology*) and its supplementary material: - the input data of the 463 CAMELS basins; - the training, evaluation, analysis and plotting code; - the trained models, the daily simulations of all models and the per-basin metrics. The study trains one regional LSTM on 463 CAMELS basins. Six loss configurations are compared. The proposed loss adds two terms to the usual data loss: - an FDC-matching term; - a differentiable leading-digit term. It pulls the soft leading-digit histogram of the simulated flow towards the histogram of the observed flow in the same 512-day block. --- ## 1. Contents ``` Benford_LSTM_streamflow/ ├── README.md this file (English) ├── README_zh.md Chinese version ├── LICENSE MIT (code) / CC BY 4.0 (data products and results) ├── CITATION.cff ├── requirements_train.txt environment for training / evaluation / analysis (GPU) ├── requirements_plot.txt environment for the figures (cartopy) ├── code/ │ ├── config.py paths, study periods, input variables, hyper-parameters, model identifiers │ ├── prepare_data.py rebuilds data/camels463_daily.npz from the original CAMELS files (optional) │ ├── train.py trains one model with one seed, writes weights, training log and daily simulation │ ├── metrics.py NSE, KGE, logNSE, FHV, FMS, FLV, FDC Log-MAE, recession Log-RMSE, BDI, flow span │ ├── evaluate.py per-basin metrics, screening, K-means regimes, Tables 2-4 (paired tests) │ ├── analysis.py remaining statistics of the paper and the supplement │ └── figures/ │ ├── plot_common.py shared plotting settings │ └── make_figures.py Figs. 1-8 and Fig. S1 ├── data/ │ ├── camels463_daily.npz daily forcings and streamflow, 463 basins, 1980-01-01 to 2014-12-31 (82 MB) │ ├── camels463_attributes.csv CAMELS static attributes of the 463 basins │ ├── basin_list_463.txt USGS gauge IDs (8 digits, leading zeros kept) │ └── basins_info.csv derived per-basin information (written by evaluate.py) ├── results/ │ ├── predictions/ 42 files <run>.npz, daily simulated streamflow (mm/d) (604 MB) │ ├── weights/ 42 files <run>.pt, trained network weights (PyTorch state_dict) (48 MB) │ ├── training_logs/ 42 files <run>.json, loss terms per epoch │ ├── metrics/metrics_long.csv per-basin metrics of every run and ensemble, test and validation periods │ ├── tables/ summary tables (Section 4 below) │ ├── evaluate_log.txt, analysis_log.txt └── figures/ Figs. 1-8 and S1 (PDF and 300-dpi PNG) ``` ## 2. Data ### 2.1 Source All inputs come from the CAMELS data set (Newman et al., 2015; Addor et al., 2017), distributed by NCAR at <https://ral.ucar.edu/solutions/products/camels>: - Daymet basin-mean forcings, `basin_mean_forcing/daymet`; - USGS daily streamflow, `usgs_streamflow`; - catchment attributes, `camels_attributes_v2.0`. The 463 basins are the subset of Shen et al. (2022). This package redistributes only a re-formatted subset of these files. Please cite the original CAMELS publications when you use them. ### 2.2 `data/camels463_daily.npz` Read the file with `numpy.load(..., allow_pickle=True)`: | key | shape | content | |---|---|---| | `X` | (463, 12784, 5) float32 | Daymet forcings `prcp` (mm/d), `srad` (W/m²), `tmax` (°C), `tmin` (°C), `vp` (Pa) | | `Q` | (463, 12784) float32 | observed streamflow, mm/d (converted from ft³/s with `area_gages2`); NaN = missing | | `S` | (463, 27) float32 | the 27 static attributes used as network input (Kratzert et al., 2019a); none is derived from streamflow | | `basins` | (463,) | gauge IDs (row order of `X`, `Q`, `S`, and of all prediction files) | | `dates` | (12784,) datetime64[D] | 1980-01-01 ... 2014-12-31 | | `static_names`, `dynamic_names` | | variable names | `prepare_data.py` rebuilds this file from the raw CAMELS text files: ``` python prepare_data.py --camels <path to basin_dataset_public_v1p2> ``` ### 2.3 `data/camels463_attributes.csv` This file holds 52 CAMELS attributes for the 463 basins (`gauge_id` plus topography, climate, hydrological signatures, soil, vegetation and geology). - The network uses only the 27 attributes listed in `config.STATIC`. - The streamflow signatures in the file serve only to group and describe basins. They include `baseflow_index`, which is one of the six K-means attributes in `config.CLUSTER_ATTRS`. ### 2.4 `data/basins_info.csv` This file is written by `evaluate.py`. Each row is one basin, with these columns: - the six clustering attributes, plus `aridity`, `zero_q_freq`, `frac_snow`, `gauge_lat` and `gauge_lon`; - `BDI_obs_train` / `BDI_obs_test`: Benford Deviation Index of the observed flow in the training / test period; - `span_decades`: flow span S = log10(Q5/Q95) in the training period; - `regime`: K-means class (`Flashy`, 177 basins; `Buffered`, 286 basins); - `NSE_benchmark_valid`: validation-period NSE of the 5-member benchmark ensemble; - `screen_valid`: True if `NSE_benchmark_valid` > 0.2. This gives the 450 basins used in the main analyses. ### 2.5 Study periods (water years, as in Kratzert et al., 2019a) | period | dates | use | |---|---|---| | training | 1999-10-01 to 2008-09-30 | network training | | test | 1989-10-01 to 1999-09-30 | all reported results unless stated otherwise | | validation | 1981-01-01 to 1989-09-30 | basin screening; check of the main comparisons in an independent period | ## 3. Models and runs All runs share the same data, network, optimiser, mini-batch order and seeds; only the loss differs. The setup is: - one LSTM layer with 256 units, dropout 0.4 and a 365-day input window; - 30 epochs of Adam, with the learning rate set to 1e-3, 5e-4 and 1e-4 from epochs 1, 11 and 21; - each mini-batch is 512 consecutive days of one basin; - the weight λ of the extra loss terms is 0 for the first 10 epochs, then rises linearly to λmax = 0.5 (Eq. 12). | run identifier | name in the paper | training loss | seeds | |---|---|---|---| | `benchmark` | Benchmark LSTM | Eq. (1): standardised MSE + 0.5·MSE of log10(Q+0.01) | 1-5 | | `proposed` | Proposed method (FDC-matching + leading-digit terms) | Eq. (11) = Eq. (1) + λ·(L_F + L_D) | 1-5 | | `digit` | Leading-digit term (ablation) | Eq. (1) + λ·L_D, Eq. (9) | 1-5 | | `fdc` | FDC-matching term (ablation) | Eq. (1) + λ·L_F, Eq. (10) | 1-5 | | `benford` | Benford loss (ablation) | Eq. (1) + λ·L_B, Eq. (8) | 1-5 | | `lstm_mse` | LSTM-MSE (ablation) | first term of Eq. (1) | 1-5 | | `proposed_lam0.1`, `proposed_lam1.0` | λmax = 0.1 and 1.0 (Section 3.6, Table 5) | Eq. (11) | 1-3 | | `benchmark_softplus`, `digit_softplus` | softplus output head (Section 4.3) | Eq. (1); Eq. (1) + λ·L_D | 1-3 | Every run produces three files named `<run>_seed<k>`, for example `proposed_seed3`: - `results/predictions/<run>_seed<k>.npz`: array `P` (463 × 12784), daily simulated flow in mm/d, same row and date order as `data/camels463_daily.npz`. The first 364 days have no full input window and are NaN. - `results/weights/<run>_seed<k>.pt`: weights; load them with `train.HydroLSTM(n_in=32, hidden=256, dropout=0.4)`. - `results/training_logs/<run>_seed<k>.json`: per-epoch mean of each loss term: - `total`, `mse`, `log`; - `reg`: the extra term, before weighting by λ; - `benf_kl`: diagnostic KL divergence to Benford; - `lam`, `sec`. Ensemble means average the daily simulations of all seeds. Two ensembles are only ever compared at the same size: - 5-seed models are compared with the 5-member benchmark; - 3-seed models are compared with the benchmark ensemble of seeds 1-3 (member `ens3` in `metrics_long.csv`). ## 4. What reproduces what | output | paper | |---|---| | `results/tables/model_summary.csv` | Table 2; medians quoted in Sections 3.1-3.3 | | `results/tables/paired_vs_benchmark.csv` | Table 3, rows "vs benchmark" of Table 4 (win rate, median improvement, bootstrap CI, Wilcoxon p, seed-paired t-test counts), regime results | | `results/tables/ablation_direct_comparisons.csv` | model-vs-model rows of Table 4 | | `results/tables/validation_consistency.csv` | validation-period check (Section 3.4) | | `results/tables/lambda_sensitivity.csv` | Table 5 | | `results/tables/softplus_head.csv` | output-head experiment (Section 4.3) | | `results/tables/lowflow_diagnostics.csv` | low-flow segment spread, collapse to zero (Sections 3.5, 4.2, 4.3) | | `results/tables/correlations.csv`, `winrate_by_span.csv` | Section 3.5, Figs. 6-7 | | `results/tables/digit_statistics.csv` | observed leading-digit statistics (Sections 2.3, 3.2) | | `results/tables/tableS1_wrapped_normal.csv` | Table S1 | | `results/tables/offset_sensitivity.csv` | Tables S2-S4 | | `figures/Fig01 ... Fig08`, `FigS1` | Figs. 1-8 and Fig. S1 | Metric columns in `metrics_long.csv` are listed below. Each row is one combination of basin × run × member (seed number, `ens` or `ens3`) × period (`test` / `valid`). - `NSE`, `KGE`, `logNSE`; - `FHV`, `FMS`, `FLV`: Yilmaz et al. (2008), in %. A positive FLV means the simulated low-flow segment of the FDC is flatter than the observed one; - `FDC_LogMAE`: mean absolute log10 error of the FDC for exceedance probability ≥ 0.75; - `Rec_LogRMSE`: log10 RMSE on recession days; - `BDI_sim`, `BDI_obs`: L1 distance of the leading-digit histogram to Benford's law. All log metrics use an offset of 0.01 mm/d; the supplement tests other offsets. ## 5. How to run The numbers in the paper were produced with two Python environments: - `requirements_train.txt`: Python 3.11, PyTorch 2.12 with CUDA 12.6. Used for training, `evaluate.py` and `analysis.py`. - `requirements_plot.txt`: Python 3.9, matplotlib 3.9 and cartopy 0.23. Used for the figures. Any recent versions should work. Run all scripts from the `code/` folder. ``` cd code # 1 (optional) rebuild the input file from raw CAMELS python prepare_data.py --camels <path to basin_dataset_public_v1p2> # 2 (optional) retrain; ~40 min per run on one RTX 4070 GPU; overwrites the files in results/ python train.py --model proposed --seed 1 python train.py --model proposed --seed 1 --lam 0.1 # -> proposed_lam0.1_seed1 python train.py --model digit --seed 1 --head softplus # -> digit_softplus_seed1 # all 42 runs: models benchmark, proposed, digit, fdc, benford, lstm_mse with seeds 1-5; # proposed --lam 0.1, proposed --lam 1.0, benchmark --head softplus, digit --head softplus with seeds 1-3 # 3 metrics, screening, regimes, Tables 2-4 (~1 min, CPU) python evaluate.py # 4 remaining statistics and supplementary tables (<1 min, CPU) python analysis.py # 5 figures (needs cartopy; first run downloads Natural Earth coastlines) cd figures python make_figures.py # all figures, or e.g. python make_figures.py fig5 fig8 ``` Steps 1-2 are optional, because the inputs and all 42 trained runs are included; steps 3-5 then reproduce every table and figure. Retraining with the same seed on the same hardware and software gives the same losses, because the training uses fixed seeds and a fixed mini-batch order. The LSTM runs in mixed precision with cuDNN autotuning, so other GPUs or library versions can give small run-to-run differences. These do not change the conclusions. ## 6. License - Code (`code/`): MIT License. - Data products and model results (`data/`, `results/`, `figures/`): CC BY 4.0. The CAMELS data subset is redistributed in re-formatted form for reproducibility only. Its original terms and citation requirements apply (see Section 2.1). ## 7. Citation If you use this package, please cite the paper (reference to be completed on publication) and this Zenodo record. Guo, J., Chang, X., Liu, Y., Qin, H., Zhu, S., Bai, Y., Yang, S., Xu, X. A Benford's Law-Inspired Deep Learning Model for Streamflow Prediction. *Journal of Hydrology* (under review). ## References - Addor, N., Newman, A. J., Mizukami, N., & Clark, M. P. (2017). The CAMELS data set: catchment attributes and meteorology for large-sample studies. *Hydrology and Earth System Sciences*, 21, 5293-5313. https://doi.org/10.5194/hess-21-5293-2017 - Kratzert, F., Klotz, D., Shalev, G., Klambauer, G., Hochreiter, S., & Nearing, G. (2019a). Towards learning universal, regional, and local hydrological behaviors via machine learning applied to large-sample datasets. *Hydrology and Earth System Sciences*, 23, 5089-5110. https://doi.org/10.5194/hess-23-5089-2019 - Newman, A. J., Clark, M. P., Sampson, K., Wood, A., Hay, L. E., Bock, A., et al. (2015). Development of a large-sample watershed-scale hydrometeorological data set for the contiguous USA. *Hydrology and Earth System Sciences*, 19, 209-223. https://doi.org/10.5194/hess-19-209-2015 - Shen, H., Tolson, B. A., & Mai, J. (2022). Time to update the split-sample approach in hydrological model calibration. *Water Resources Research*, 58, e2021WR031523. https://doi.org/10.1029/2021WR031523 - Yilmaz, K. K., Gupta, H. V., & Wagener, T. (2008). A process-based diagnostic approach to model evaluation: Application to the NWS distributed hydrologic model. *Water Resources Research*, 44, W09417. https://doi.org/10.1029/2007WR006716
Keyword(s):
MeSH Term(s):
Grants and Funding:
No Grants or Funding Data Available
Associated Publication(s):
No Associated Publication Data Available
Supplementary Data:
No Supplementary Data Available
Related Dataset(s):
No Related Dataset Data Available
The National Library of Medicine (NLM) provides information about biomedical datasets. Inclusion on an NLM Web page does not imply endorsement of, or agreement with, the contents by NLM or the National Institutes of Health. Learn more: NLM Web Policies (nih.gov)