4 "cell_type": "markdown",
5 "id": "83b774b3-ef55-480a-b999-506676e49145",
8 "# v2.1 run RNN strategy serial by Location\n",
10 "This version of the RNN runs the model on each location separately, one at a time. Two main runs:\n",
11 "1. Run separate model at each location - training and prediction at least location independently - training mode periods 0:train_ind (was 0:h2), then prediction in test_ind:end. Validation data, if any, are from train_ind:test_ind\n",
12 "2. Run same model with multiple fitting calls 0:train_ind at different locations, compare prediction accuracy in test_ind:end at for all location. \n"
17 "execution_count": null,
18 "id": "83cc1dc4-3dcb-4325-9263-58101a3dc378",
22 "import numpy as np\n",
23 "from utils import print_dict_summary, print_first, str2time, logging_setup\n",
26 "import os.path as osp\n",
27 "from moisture_rnn_pkl import pkl2train\n",
28 "from moisture_rnn import RNNParams, RNNData, RNN \n",
29 "from utils import hash2, read_yml, read_pkl, retrieve_url\n",
30 "from moisture_rnn import RNN\n",
31 "import reproducibility\n",
32 "from data_funcs import rmse, to_json\n",
33 "from moisture_models import run_augmented_kf\n",
35 "import pandas as pd\n",
36 "import matplotlib.pyplot as plt\n",
42 "execution_count": null,
43 "id": "17db9b90-a931-4674-a447-5b8ffbcdc86a",
52 "execution_count": null,
53 "id": "35319c1c-7849-4b8c-8262-f5aa6656e0c7",
58 " url = \"https://demo.openwfm.org/web/data/fmda/dicts/test_CA_202401.pkl\", \n",
59 " dest_path = \"data/fmda_nw_202401-05_f05.pkl\")"
64 "execution_count": null,
65 "id": "eabdbd9c-07d9-4bae-9851-cca79f321895",
69 "repro_file = \"data/reproducibility_dict_v2_TEST.pkl\"\n",
70 "file_names=['fmda_nw_202401-05_f05.pkl']\n",
72 "file_paths = [osp.join(file_dir,file_name) for file_name in file_names]"
77 "execution_count": null,
78 "id": "dcca6185-e799-4dd1-8acb-87ad33c411d7",
82 "# read/write control\n",
83 "train_file='data/train.pkl'\n",
84 "train_create=True # if false, read\n",
91 "execution_count": null,
92 "id": "bc0a775b-b587-42ef-8576-e36dc0be3a75",
98 "repro = read_pkl(repro_file)\n",
100 "if train_create:\n",
101 " logging.info('creating the training cases from files %s',file_paths)\n",
102 " # osp.join works on windows too, joins paths using \\ or /\n",
103 " train = pkl2train(file_paths)\n",
105 " with open(train_file, 'wb') as file:\n",
106 " logging.info('Writing the rain cases into file %s',train_file)\n",
107 " pickle.dump(train, file)\n",
109 " logging.info('Reading the train cases from file %s',train_file)\n",
110 " train = read_pkl(train_file)"
115 "execution_count": null,
116 "id": "211a1c2f-ba8d-40b8-b29c-daa38af97a26",
120 "params_all = read_yml(\"params.yaml\")\n",
121 "print(params_all.keys())"
126 "execution_count": null,
127 "id": "698df86b-8550-4135-81df-45dbf503dd4e",
131 "# from module_param_sets import param_sets"
136 "execution_count": null,
137 "id": "4b0c9a9b-dd02-4251-aa4a-2acc1101e153",
141 "param_sets_keys=['rnn']\n",
142 "cases=list(train.keys())[0:50]\n",
143 "# cases=list(train.keys())\n",
144 "# cases.remove('reproducibility')\n",
150 "execution_count": null,
151 "id": "dd22baf2-59d2-460e-8c47-b20116dd5982",
155 "logging.info('Running over parameter sets %s',param_sets_keys)\n",
156 "logging.info('Running over cases %s',cases)"
160 "cell_type": "markdown",
161 "id": "802f3eef-1702-4478-b6e3-2288a6edae24",
164 "## Run Reproducibility Case"
169 "execution_count": null,
170 "id": "69a3adb9-39fd-4c0c-9c9b-aaa2a9a3af40",
174 "params = repro['repro_info']['params']\n",
175 "print(type(params))\n",
178 "# Set up input data\n",
179 "rnn_dat = RNNData(repro, scaler = params['scaler'], features_list = params['features_list'])\n",
180 "rnn_dat.train_test_split(\n",
181 " time_fracs = params['time_fracs']\n",
183 "rnn_dat.scale_data()\n",
184 "rnn_dat.batch_reshape(timesteps = params['timesteps'], batch_size = params['batch_size'])"
189 "execution_count": null,
190 "id": "855703c4-d7a9-4579-bca7-7c737a81d0de",
194 "reproducibility.set_seed(123)\n",
195 "rnn = RNN(params)\n",
196 "m, errs = rnn.run_model(rnn_dat, reproducibility_run=True)"
200 "cell_type": "markdown",
201 "id": "49e31fdd-4c14-4a81-9e2b-4c6ba94d1f83",
204 "## Separate Models by Location"
209 "execution_count": null,
210 "id": "e11e7c83-183f-48ba-abd8-a6aedff66090",
214 "# Set up output dictionaries\n",
221 "execution_count": null,
222 "id": "dc5b47bd-4fbc-44b8-b2dd-d118e068b450",
229 "for k in param_sets_keys:\n",
230 " params = RNNParams(params_all[k])\n",
231 " print(\"~\"*80)\n",
232 " print(\"Running with params:\")\n",
234 " # Increase Val Frac so no errors, TODO fix validation\n",
235 " params.update({\n",
236 " 'train_frac': .9,\n",
237 " 'val_frac': .05,\n",
238 " 'activation': ['relu', 'relu'],\n",
240 " 'dense_units': 10,\n",
241 " 'rnn_layers': 2 \n",
243 " for case in cases:\n",
244 " print(\"~\"*50)\n",
245 " logging.info('Processing case %s',case)\n",
246 " print_dict_summary(train[case])\n",
247 " # Format data & Run Model\n",
248 " # rnn_dat = create_rnn_data2(train[case], params)\n",
249 " rnn_dat = RNNData(train[case], scaler = params['scaler'], features_list = params['features_list'])\n",
250 " rnn_dat.train_test_split(\n",
251 " time_fracs = [.9, .05, .05]\n",
253 " rnn_dat.scale_data()\n",
254 " rnn_dat.batch_reshape(timesteps = params['timesteps'], batch_size = params['batch_size'])\n",
255 " params.update({'bmax': rnn_dat.hours})\n",
256 " reproducibility.set_seed()\n",
257 " rnn = RNN(params)\n",
258 " m, errs = rnn.run_model(rnn_dat, plot_period=\"predict\")\n",
259 " # Add model output to case\n",
260 " train[case]['m_rnn']=m\n",
261 " # Get RMSE Prediction Error\n",
262 " print(f\"RMSE: {errs}\")\n",
263 " outputs_rnn[case] = {'case':case, 'errs': errs.copy()}\n",
265 " # Run Augmented KF\n",
266 " print('Running Augmented KF')\n",
267 " train[case]['h2'] = rnn_dat.test_ind\n",
268 " train[case]['scale_fm'] = 1\n",
269 " m, Ec = run_augmented_kf(train[case])\n",
270 " y = rnn_dat['y'] \n",
271 " train[case]['m_kf'] = m\n",
272 " print(f\"KF RMSE: {rmse(m[rnn_dat.test_ind:],y[rnn_dat.test_ind:])}\")\n",
273 " outputs_kf[case] = {'case':case, 'errs': rmse(m[rnn_dat.test_ind:],y[rnn_dat.test_ind:])}\n",
275 " # Save Outputs \n",
276 " to_json(outputs_rnn, \"rnn_errs.json\")\n",
277 " to_json(outputs_kf, \"kf_errs.json\")"
282 "execution_count": null,
283 "id": "15384e4d-b8ec-4700-bdc2-83b0433d11c9",
287 "logging.info('fmda_rnn_serial.ipynb done')"
292 "execution_count": null,
293 "id": "d0e78fb3-b501-49d6-81a9-1a13da0134a0",
297 "import importlib\n",
298 "import moisture_rnn\n",
299 "importlib.reload(moisture_rnn)\n",
300 "from moisture_rnn import RNN"
305 "execution_count": null,
306 "id": "37053436-8dfe-4c40-8614-811817e83782",
310 "for k in outputs_rnn:\n",
311 " print(\"~\"*50)\n",
312 " print(outputs_rnn[k]['case'])\n",
313 " print(outputs_rnn[k]['errs']['prediction'])"
318 "execution_count": null,
319 "id": "9154d5f7-015f-4ef7-af45-020410a1ea65",
323 "for k in outputs_kf:\n",
324 " print(\"~\"*50)\n",
325 " print(outputs_kf[k]['case'])\n",
326 " print(outputs_kf[k]['errs'])"
331 "execution_count": null,
332 "id": "dfd90d87-fe08-48b5-8cc4-31bd19c5c20a",
338 "cell_type": "markdown",
339 "id": "f3c1c299-1655-4c64-a458-c7723db6ea6d",
342 "### TODO: FIX SCALING in Scheme below\n",
344 "Scaling is done separately in each now."
348 "cell_type": "markdown",
349 "id": "0c0c3470-30f5-4915-98a7-dcdf5760d482",
352 "## Training at Multiple Locations\n",
359 "execution_count": null,
360 "id": "dd1aca73-7279-473e-b2a3-95aa1db7b1a8",
364 "params = RNNParams(params_all['rnn'])\n",
366 " 'epochs': 1, # less epochs since it is per location\n",
367 " 'activation': ['relu', 'relu'],\n",
368 " 'train_frac': .9,\n",
369 " 'val_frac': .05, \n",
370 " 'dense_units': 10,\n",
371 " 'rnn_layers': 2\n",
374 "# rnn_dat = create_rnn_data2(train[cases[0]], params)\n",
375 "rnn_dat = RNNData(train[cases[0]], params['scaler'], params['features_list'])\n",
376 "rnn_dat.train_test_split(\n",
377 " time_fracs = [.9, .05, .05]\n",
379 "rnn_dat.scale_data()\n",
380 "rnn_dat.batch_reshape(timesteps = params['timesteps'], batch_size = params['batch_size'])"
385 "execution_count": null,
386 "id": "65b2f9a3-a8f2-4ac1-8e4d-ba38a86eaf40",
390 "reproducibility.set_seed()\n",
396 "execution_count": null,
397 "id": "47a85ef2-8145-4de8-9f2e-86622306ffd8",
404 "print(\"Running with params:\")\n",
407 "for case in cases[0:10]:\n",
408 " print(\"~\"*50)\n",
409 " logging.info('Processing case %s',case)\n",
410 " print_dict_summary(train[case])\n",
411 " rnn_dat_temp = RNNData(train[case], params['scaler'], params['features_list'])\n",
412 " rnn_dat_temp.train_test_split(\n",
413 " time_fracs = [.9, .05, .05]\n",
415 " rnn_dat_temp.scale_data()\n",
416 " rnn_dat_temp.batch_reshape(timesteps = params['timesteps'], batch_size = params['batch_size'])\n",
417 " rnn.fit(rnn_dat_temp['X_train'], rnn_dat_temp['y_train'],\n",
418 " validation_data=(rnn_dat_temp['X_val'], rnn_dat_temp['y_val']))\n",
419 " # run_rnn_pkl(train[case],param_sets[i])"
423 "cell_type": "markdown",
424 "id": "a0421b8d-49aa-4409-8cbf-7732f1137838",
432 "execution_count": null,
433 "id": "63d7854a-94f7-425c-9561-4fe518e044bb",
439 "# Predict Cases Used in Training\n",
441 "inds = np.arange(0,10)\n",
442 "train_keys = list(train.keys())\n",
444 " print(\"~\"*50)\n",
445 " case = train_keys[i]\n",
446 " print(f\"Predicting case {case}\")\n",
447 " # rnn_dat = create_rnn_data2(train[case], params)\n",
448 " rnn_dat_temp = RNNData(train[case], params['scaler'], params['features_list'])\n",
449 " rnn_dat_temp.train_test_split(\n",
450 " time_fracs = [.9, .05, .05]\n",
452 " rnn_dat_temp.scale_data()\n",
453 " rnn_dat_temp.batch_reshape(timesteps = params['timesteps'], batch_size = params['batch_size'])\n",
454 " X_temp = rnn_dat_temp.scale_all_X()\n",
455 " m = rnn.predict(X_temp)\n",
456 " test_ind = rnn_dat['test_ind']\n",
457 " rmses.append(rmse(m[test_ind:], rnn_dat['y_test'].flatten()))"
462 "execution_count": null,
463 "id": "2a5423e0-778b-4f69-9ed0-f0082a1fefe5",
472 "execution_count": null,
473 "id": "45c9caae-7ced-4f21-aa05-c9b125e8fdcb",
477 "pd.DataFrame({'Case': list(train.keys())[0:10], 'RMSE': rmses}).style.hide(axis=\"index\")"
482 "execution_count": null,
483 "id": "f710f482-b600-4ea5-9a8a-823a13b4ec7a",
489 "# Predict New Locations\n",
491 "for i, case in enumerate(list(train.keys())[10:100]):\n",
492 " print(\"~\"*50)\n",
493 " print(f\"Predicting case {case}\")\n",
494 " rnn_dat_temp = RNNData(train[case], params['scaler'], params['features_list'])\n",
495 " rnn_dat_temp.train_test_split(\n",
496 " time_fracs = [.9, .05, .05]\n",
498 " rnn_dat_temp.scale_data()\n",
499 " rnn_dat_temp.batch_reshape(timesteps = params['timesteps'], batch_size = params['batch_size'])\n",
500 " X = rnn_dat_temp.scale_all_X()\n",
501 " m = rnn.predict(X)\n",
502 " train[case]['m'] = m\n",
503 " test_ind = rnn_dat['test_ind']\n",
504 " rmses.append(rmse(m[test_ind:], rnn_dat.y_test.flatten()))\n",
506 "df = pd.DataFrame({'Case': list(train.keys())[10:100], 'RMSE': rmses})"
511 "execution_count": null,
512 "id": "d793ac87-d94b-4b16-a271-46cdc259b4fe",
516 "df[0:5].style.hide(axis=\"index\")"
521 "execution_count": null,
522 "id": "b99606d1-bd46-4041-8303-1bcbb196f6f4",
531 "execution_count": null,
532 "id": "52ec264d-d4b7-444c-b623-002d6383da30",
541 "execution_count": null,
542 "id": "998922cd-46bb-4063-8284-0497e19c39b0",
551 "execution_count": null,
552 "id": "889f3bbb-9fb2-4621-9e93-1d0bc0f83e01",
559 "execution_count": null,
560 "id": "fe407f61-15f2-4086-a386-7d7a5bb90d26",
567 "execution_count": null,
568 "id": "2fdb63b3-68b8-4877-a7a2-f63257cb29d5",
575 "execution_count": null,
576 "id": "5c7563c5-a880-45c7-8381-8ce4e1a44216",
583 "execution_count": null,
584 "id": "ad5dae6c-1269-4674-a49e-2efe8b956911",
592 "display_name": "Python 3 (ipykernel)",
593 "language": "python",
601 "file_extension": ".py",
602 "mimetype": "text/x-python",
604 "nbconvert_exporter": "python",
605 "pygments_lexer": "ipython3",