4 "cell_type": "markdown",
5 "id": "83b774b3-ef55-480a-b999-506676e49145",
8 "# v2.1 run RNN with Spatial Training\n",
10 "This notebook is intended to set up a test where the RNN is run serial by location and compared to the spatial training scheme. Additionally, the ODE model with the augmented KF will be run as a comparison, but note that the RNN models will be predicting entirely without knowledge of the heldout locations, while the augmented KF will be run directly on the test locations.\n"
14 "cell_type": "markdown",
15 "id": "bbd84d61-a9cd-47b4-b538-4986fb10b98d",
18 "## Environment Setup"
23 "execution_count": null,
24 "id": "83cc1dc4-3dcb-4325-9263-58101a3dc378",
28 "import numpy as np\n",
29 "from utils import print_dict_summary, print_first, str2time, logging_setup\n",
32 "import os.path as osp\n",
33 "from moisture_rnn_pkl import pkl2train\n",
34 "from moisture_rnn import RNNParams, RNNData, RNN \n",
35 "from utils import hash2, read_yml, read_pkl, retrieve_url, Dict\n",
36 "from moisture_rnn import RNN\n",
37 "import reproducibility\n",
38 "from data_funcs import rmse, to_json, combine_nested, process_train_dict\n",
39 "from moisture_models import run_augmented_kf\n",
41 "import pandas as pd\n",
42 "import matplotlib.pyplot as plt\n",
49 "execution_count": null,
50 "id": "17db9b90-a931-4674-a447-5b8ffbcdc86a",
59 "execution_count": null,
60 "id": "35319c1c-7849-4b8c-8262-f5aa6656e0c7",
65 " url = \"https://demo.openwfm.org/web/data/fmda/dicts/fmda_nw_202401-05_f05.pkl\", \n",
66 " dest_path = \"data/fmda_nw_202401-05_f05.pkl\")"
71 "execution_count": null,
72 "id": "eabdbd9c-07d9-4bae-9851-cca79f321895",
76 "file_paths = ['data/fmda_nw_202401-05_f05.pkl']"
81 "execution_count": null,
82 "id": "dcca6185-e799-4dd1-8acb-87ad33c411d7",
86 "# read/write control\n",
87 "train_file='data/train.pkl'\n",
88 "train_create=True # if false, read\n",
95 "execution_count": null,
96 "id": "604388de-11ab-45c3-9f0d-80bdff0cca60",
100 "# Params used for data filtering\n",
101 "params_data = read_yml(\"params_data.yaml\") \n",
107 "execution_count": null,
108 "id": "211a1c2f-ba8d-40b8-b29c-daa38af97a26",
112 "# Params used for setting up RNN\n",
113 "params = read_yml(\"params.yaml\", subkey='rnn') \n",
119 "execution_count": null,
120 "id": "bc0a775b-b587-42ef-8576-e36dc0be3a75",
126 "if train_create:\n",
127 " logging.info('creating the training cases from files %s',file_paths)\n",
128 " # osp.join works on windows too, joins paths using \\ or /\n",
129 " train = process_train_dict(file_paths, params_data = params_data, verbose=True)\n",
131 " with open(train_file, 'wb') as file:\n",
132 " logging.info('Writing the rain cases into file %s',train_file)\n",
133 " pickle.dump(train, file)\n",
135 " logging.info('Reading the train cases from file %s',train_file)\n",
136 " train = read_pkl(train_file)"
141 "execution_count": null,
142 "id": "23cd60c0-9865-4314-9a96-948c3d400c08",
146 "from itertools import islice\n",
147 "train = {k: train[k] for k in islice(train, 200)}"
151 "cell_type": "markdown",
152 "id": "efc10cdc-f18b-4781-84da-b8e2eef39981",
155 "## Setup Validation Runs"
159 "cell_type": "markdown",
160 "id": "2d9cd5c5-87ed-41f9-b36c-e0c18d58c841",
163 "The following parameters will be used for both serial and spatial models."
168 "execution_count": null,
169 "id": "66f40c9f-c1c2-4b12-bf14-2ada8c26113d",
173 "params = RNNParams(params)\n",
174 "params.update({'epochs': 200, \n",
175 " 'learning_rate': 0.001,\n",
176 " 'activation': ['tanh', 'tanh'], # Activation for RNN Layers, Dense layers respectively.\n",
177 " 'recurrent_layers': 2, 'recurrent_units': 30, \n",
178 " 'dense_layers': 2, 'dense_units': 30,\n",
179 " 'early_stopping_patience': 30, # how many epochs of no validation accuracy gain to wait before stopping\n",
180 " 'batch_schedule_type': 'exp', # Hidden state batch reset schedule\n",
181 " 'bmin': 20, # Lower bound of hidden state batch reset, \n",
182 " 'bmax': params_data['hours'], # Upper bound of hidden state batch reset, using max hours\n",
183 " 'features_list': ['Ed', 'Ew', 'rain', 'elev', 'lon', 'lat', 'solar', 'wind']\n",
189 "execution_count": null,
190 "id": "36823193-b93c-421e-b699-8c1ae5719309",
194 "reproducibility.set_seed(123)"
198 "cell_type": "markdown",
199 "id": "a24d76fc-6c25-43e7-99df-3cd5dbf84fc3",
202 "## Spatial Data Training\n",
204 "This method combines the training timeseries data into a single 3-d array, with timeseries at the same location arranged appropriately in the right order for a given `batch_size` hyperparameter. The hidden state of the recurrent layers are set up reset when the location changes. "
209 "execution_count": null,
210 "id": "3b5371a9-c1e8-4df5-b360-210746f7cd52",
214 "# Start timer for code \n",
215 "start_time = time.time()"
220 "execution_count": null,
221 "id": "faf93470-b55f-4770-9fa9-3288a2f13fcc",
225 "# Combine Nested Dictionary into Spatial Data\n",
226 "train_sp = Dict(combine_nested(train))"
231 "execution_count": null,
232 "id": "c0c7f5fb-4c33-45f8-9a2e-38c9ab1cd4e3",
236 "rnn_dat_sp = RNNData(\n",
237 " train_sp, # input dictionary\n",
238 " scaler=\"standard\", # data scaling type\n",
239 " features_list = params['features_list'] # features for predicting outcome\n",
243 "rnn_dat_sp.train_test_split( \n",
244 " time_fracs = [.8, .1, .1], # Percent of total time steps used for train/val/test\n",
245 " space_fracs = [.8, .1, .1] # Percent of total timeseries used for train/val/test\n",
247 "rnn_dat_sp.scale_data()\n",
249 "rnn_dat_sp.batch_reshape(\n",
250 " timesteps = params['timesteps'], # Timesteps aka sequence length for RNN input data. \n",
251 " batch_size = params['batch_size'] # Number of samples of length timesteps for a single round of grad. descent\n",
257 "execution_count": null,
258 "id": "7431bc95-d384-40fd-a622-bbc0ee68e5cd",
262 "# Update Params specific to spatial training\n",
264 " 'loc_batch_reset': rnn_dat_sp.n_seqs # Used to reset hidden state when location changes for a given batch\n",
270 "execution_count": null,
271 "id": "4bc11474-fed8-47f2-b9cf-dfdda0d3d3b2",
275 "rnn_sp = RNN(params)\n",
276 "m_sp, errs = rnn_sp.run_model(rnn_dat_sp)"
281 "execution_count": null,
282 "id": "704ad662-d81a-488d-be3d-e90bf775a5b8",
291 "execution_count": null,
292 "id": "d53571e3-b6cf-49aa-9848-e3c77053283d",
297 "end_time = time.time()\n",
299 "# Calculate Code Runtime\n",
300 "elapsed_time_sp = end_time - start_time\n",
301 "print(f\"Spatial Training Elapsed time: {elapsed_time_sp:.4f} seconds\")"
305 "cell_type": "markdown",
306 "id": "7d8292a2-418c-48ed-aff7-ccbe98b046d3",
314 "execution_count": null,
315 "id": "cca12d8c-c0e1-4df4-b2ca-20440485f2f3",
319 "# Get timeseries IDs from previous RNNData object\n",
320 "test_cases = rnn_dat_sp.loc['test_locs']\n",
321 "print(len(test_cases))"
326 "execution_count": null,
327 "id": "997f2534-7e77-45b3-93bf-d988837dfc0b",
331 "test_ind = rnn_dat_sp.test_ind # Time index for test period start\n",
337 "execution_count": null,
338 "id": "1e4ffc68-c775-41c6-ac42-f49c76824b43",
345 "for case in test_cases:\n",
346 " print(\"~\"*50)\n",
348 " # Run Augmented KF\n",
349 " print('Running Augmented KF')\n",
350 " train[case]['h2'] = test_ind\n",
351 " train[case]['scale_fm'] = 1\n",
352 " m, Ec = run_augmented_kf(train[case])\n",
353 " y = train[case]['y'] \n",
354 " train[case]['m_kf'] = m\n",
355 " print(f\"KF RMSE: {rmse(m[test_ind:],y[test_ind:])}\")\n",
356 " outputs_kf[case] = {'case':case, 'errs': rmse(m[test_ind:],y[test_ind:])}"
361 "execution_count": null,
362 "id": "57b19ec5-23f6-44ec-9f71-16d4d69aec68",
366 "df_kf = pd.DataFrame.from_dict(outputs_kf).transpose()\n",
372 "execution_count": null,
373 "id": "25a9d2fe-83f7-4ef3-a04b-14c970b6e2ba",
381 "cell_type": "markdown",
382 "id": "f616bbf8-d89e-4c5b-9e47-59f02246b6f2",
385 "## Serial Training\n",
387 "This method initializes a RNN and uses successive `.fit` calls to train the model one location at a time. This is the naive approach to training a RNN on multiple timeseries, and is used as a baseline to see whether the spatial training scheme improves things."
392 "execution_count": null,
393 "id": "6fa20e9f-604a-4938-ab68-b71fbb7326df",
397 "# Start timer for code \n",
398 "start_time = time.time()"
403 "execution_count": null,
404 "id": "f033e78c-a506-4508-a23c-8e6574014872",
408 "# Update Params specific to Serial training\n",
410 " 'loc_batch_reset': None, # Used to reset hidden state when location changes for a given batch\n",
411 " 'epochs': 1 # less epochs since fit will be run multiple times over locations\n",
417 "execution_count": null,
418 "id": "ff1788ec-081b-403f-bcfa-b625f0e3dbe1",
422 "train_cases = rnn_dat_sp.loc['train_locs']\n",
423 "test_cases = rnn_dat_sp.loc['test_locs']"
428 "execution_count": null,
429 "id": "8a2af45e-e81b-421f-b940-e8779177dd5d",
433 "# Initialize Model with first train case\n",
434 "rnn_dat = RNNData(train[train_cases[0]], params['scaler'], params['features_list'])\n",
435 "rnn_dat.train_test_split(\n",
436 " time_fracs = [.8, .1, .1]\n",
438 "rnn_dat.scale_data()\n",
439 "rnn_dat.batch_reshape(timesteps = params['timesteps'], batch_size = params['batch_size'])"
444 "execution_count": null,
445 "id": "ac6fecc2-f614-4506-b5f9-05a6eca3b62e",
449 "reproducibility.set_seed()\n",
455 "execution_count": null,
456 "id": "79b5af30-7d52-410c-9595-e89e9756fd38",
463 "for case in train_cases:\n",
464 " print(\"~\"*50)\n",
465 " print(f\"Training with Case {case}\")\n",
466 " rnn_dat_temp = RNNData(train[case], params['scaler'], params['features_list'])\n",
467 " rnn_dat_temp.train_test_split(\n",
468 " time_fracs = [.8, .1, .1]\n",
470 " rnn_dat_temp.scale_data()\n",
471 " rnn_dat_temp.batch_reshape(timesteps = params['timesteps'], batch_size = params['batch_size'])\n",
472 " rnn.fit(rnn_dat_temp['X_train'], rnn_dat_temp['y_train'],\n",
473 " validation_data=(rnn_dat_temp['X_val'], rnn_dat_temp['y_val'])) "
478 "execution_count": null,
479 "id": "03d716b4-0ff5-4b80-a241-440543ba9b46",
486 "outputs_rnn_serial = {}\n",
487 "test_ind = rnn_dat.test_ind\n",
488 "for i, case in enumerate(test_cases):\n",
489 " print(\"~\"*50)\n",
490 " rnn_dat_temp = RNNData(train[case], params['scaler'], params['features_list'])\n",
491 " rnn_dat_temp.train_test_split(\n",
492 " time_fracs = [.8, .1, .1]\n",
494 " rnn_dat_temp.scale_data()\n",
495 " rnn_dat_temp.batch_reshape(timesteps = params['timesteps'], batch_size = params['batch_size']) \n",
496 " X_temp = rnn_dat_temp.scale_all_X()\n",
497 " m = rnn.predict(X_temp)\n",
498 " outputs_rnn_serial[case] = {'case':case, 'errs': rmse(m[test_ind:], rnn_dat.y_test)}"
503 "execution_count": null,
504 "id": "e5a80bae-fe1a-4ec9-b9ac-31d540eaba40",
508 "df_rnn_serial = pd.DataFrame.from_dict(outputs_rnn_serial).transpose()\n",
509 "df_rnn_serial.head()"
514 "execution_count": null,
515 "id": "0c5b866e-c2bf-4bc1-8f6f-3ba8a9448d07",
519 "df_rnn_serial.errs.mean()"
524 "execution_count": null,
525 "id": "f5a364cb-01bf-49ad-a704-5aa3c9564967",
530 "end_time = time.time()\n",
532 "# Calculate Code Runtime\n",
533 "elapsed_time_ser = end_time - start_time\n",
534 "print(f\"Serial Training Elapsed time: {elapsed_time_ser:.4f} seconds\")"
538 "cell_type": "markdown",
539 "id": "86795281-f8ea-4141-81ea-c53fae830e80",
547 "execution_count": null,
548 "id": "508a6392-49bc-4471-ad8e-814f60119283",
552 "print(f\"Total Test Cases: {len(test_cases)}\")\n",
553 "print(f\"Total Test Hours: {rnn_dat_temp.y_test.shape[0]}\")"
558 "execution_count": null,
559 "id": "73e8ca05-d17b-4e72-8def-fa77664e7bb0",
563 "print(f\"Spatial Training RMSE: {errs.mean()}\")\n",
564 "print(f\"Serial Training RMSE: {df_rnn_serial.errs.mean()}\")\n",
565 "print(f\"Augmented KF RMSE: {df_kf.errs.mean()}\")"
570 "execution_count": null,
571 "id": "a73d22ee-707b-44a3-80ab-ad6e671731cf",
578 "execution_count": null,
579 "id": "272bfb32-e8e2-49dd-8f90-4b5b09c3a2a2",
583 "print(f\"Spatial Training Elapsed time: {elapsed_time_sp:.4f} seconds\")\n",
584 "print(f\"Serial Training Elapsed time: {elapsed_time_ser:.4f} seconds\")"
589 "execution_count": null,
590 "id": "38ab08fb-ac97-45be-8907-6f9cd124243b",
598 "display_name": "Python 3 (ipykernel)",
599 "language": "python",
607 "file_extension": ".py",
608 "mimetype": "text/x-python",
610 "nbconvert_exporter": "python",
611 "pygments_lexer": "ipython3",