Update rnn_workshop.ipynb
[notebooks.git] / fmda / fmda_rnn_serial.ipynb
blob9d84b694509c04e4e4dd2e4aff6c679aaf6a4b91
2  "cells": [
3   {
4    "cell_type": "markdown",
5    "id": "83b774b3-ef55-480a-b999-506676e49145",
6    "metadata": {},
7    "source": [
8     "# v2.1 run RNN strategy serial by Location\n",
9     "\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"
13    ]
14   },
15   {
16    "cell_type": "code",
17    "execution_count": null,
18    "id": "83cc1dc4-3dcb-4325-9263-58101a3dc378",
19    "metadata": {},
20    "outputs": [],
21    "source": [
22     "import numpy as np\n",
23     "from utils import print_dict_summary, print_first, str2time, logging_setup\n",
24     "import pickle\n",
25     "import logging\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",
34     "import copy\n",
35     "import pandas as pd\n",
36     "import matplotlib.pyplot as plt\n",
37     "import yaml"
38    ]
39   },
40   {
41    "cell_type": "code",
42    "execution_count": null,
43    "id": "17db9b90-a931-4674-a447-5b8ffbcdc86a",
44    "metadata": {},
45    "outputs": [],
46    "source": [
47     "logging_setup()"
48    ]
49   },
50   {
51    "cell_type": "code",
52    "execution_count": null,
53    "id": "35319c1c-7849-4b8c-8262-f5aa6656e0c7",
54    "metadata": {},
55    "outputs": [],
56    "source": [
57     "retrieve_url(\n",
58     "    url = \"https://demo.openwfm.org/web/data/fmda/dicts/test_CA_202401.pkl\", \n",
59     "    dest_path = \"fmda_nw_202401-05_f05.pkl\")"
60    ]
61   },
62   {
63    "cell_type": "code",
64    "execution_count": null,
65    "id": "eabdbd9c-07d9-4bae-9851-cca79f321895",
66    "metadata": {},
67    "outputs": [],
68    "source": [
69     "repro_file = \"data/reproducibility_dict_v2_TEST.pkl\"\n",
70     "file_names=['fmda_nw_202401-05_f05.pkl']\n",
71     "file_dir='data'\n",
72     "file_paths = [osp.join(file_dir,file_name) for file_name in file_names]"
73    ]
74   },
75   {
76    "cell_type": "code",
77    "execution_count": null,
78    "id": "dcca6185-e799-4dd1-8acb-87ad33c411d7",
79    "metadata": {},
80    "outputs": [],
81    "source": [
82     "# read/write control\n",
83     "train_file='train.pkl'\n",
84     "train_create=False   # if false, read\n",
85     "train_write=False\n",
86     "train_read=True"
87    ]
88   },
89   {
90    "cell_type": "code",
91    "execution_count": null,
92    "id": "bc0a775b-b587-42ef-8576-e36dc0be3a75",
93    "metadata": {
94     "scrolled": true
95    },
96    "outputs": [],
97    "source": [
98     "repro = read_pkl(repro_file)\n",
99     "\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",
104     "if train_write:\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",
108     "if train_read:\n",
109     "    logging.info('Reading the train cases from file %s',train_file)\n",
110     "    train = read_pkl(train_file)"
111    ]
112   },
113   {
114    "cell_type": "code",
115    "execution_count": null,
116    "id": "211a1c2f-ba8d-40b8-b29c-daa38af97a26",
117    "metadata": {},
118    "outputs": [],
119    "source": [
120     "params_all = read_yml(\"params.yaml\")\n",
121     "print(params_all.keys())"
122    ]
123   },
124   {
125    "cell_type": "code",
126    "execution_count": null,
127    "id": "698df86b-8550-4135-81df-45dbf503dd4e",
128    "metadata": {},
129    "outputs": [],
130    "source": [
131     "# from module_param_sets import param_sets"
132    ]
133   },
134   {
135    "cell_type": "code",
136    "execution_count": null,
137    "id": "4b0c9a9b-dd02-4251-aa4a-2acc1101e153",
138    "metadata": {},
139    "outputs": [],
140    "source": [
141     "param_sets_keys=['rnn']\n",
142     "cases=list(train.keys())[0:10]\n",
143     "# cases=list(train.keys())\n",
144     "# cases.remove('reproducibility')\n",
145     "cases"
146    ]
147   },
148   {
149    "cell_type": "code",
150    "execution_count": null,
151    "id": "dd22baf2-59d2-460e-8c47-b20116dd5982",
152    "metadata": {},
153    "outputs": [],
154    "source": [
155     "logging.info('Running over parameter sets %s',param_sets_keys)\n",
156     "logging.info('Running over cases %s',cases)"
157    ]
158   },
159   {
160    "cell_type": "markdown",
161    "id": "802f3eef-1702-4478-b6e3-2288a6edae24",
162    "metadata": {},
163    "source": [
164     "## Run Reproducibility Case"
165    ]
166   },
167   {
168    "cell_type": "code",
169    "execution_count": null,
170    "id": "69a3adb9-39fd-4c0c-9c9b-aaa2a9a3af40",
171    "metadata": {},
172    "outputs": [],
173    "source": [
174     "params = repro['repro_info']['params']\n",
175     "print(type(params))\n",
176     "print(params)\n",
177     "\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",
182     ")\n",
183     "rnn_dat.scale_data()\n",
184     "rnn_dat.batch_reshape(timesteps = params['timesteps'], batch_size = params['batch_size'])"
185    ]
186   },
187   {
188    "cell_type": "code",
189    "execution_count": null,
190    "id": "855703c4-d7a9-4579-bca7-7c737a81d0de",
191    "metadata": {},
192    "outputs": [],
193    "source": [
194     "reproducibility.set_seed(123)\n",
195     "rnn = RNN(params)\n",
196     "m, errs = rnn.run_model(rnn_dat, reproducibility_run=True)"
197    ]
198   },
199   {
200    "cell_type": "markdown",
201    "id": "49e31fdd-4c14-4a81-9e2b-4c6ba94d1f83",
202    "metadata": {},
203    "source": [
204     "## Separate Models by Location"
205    ]
206   },
207   {
208    "cell_type": "code",
209    "execution_count": null,
210    "id": "e11e7c83-183f-48ba-abd8-a6aedff66090",
211    "metadata": {},
212    "outputs": [],
213    "source": [
214     "# Set up output dictionaries\n",
215     "outputs_kf = {}\n",
216     "outputs_rnn = {}"
217    ]
218   },
219   {
220    "cell_type": "code",
221    "execution_count": null,
222    "id": "dc5b47bd-4fbc-44b8-b2dd-d118e068b450",
223    "metadata": {
224     "scrolled": true
225    },
226    "outputs": [],
227    "source": [
228     "\n",
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",
233     "    print(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",
239     "        'epochs': 10,\n",
240     "        'dense_units': 10,\n",
241     "        'rnn_layers': 2       \n",
242     "    })\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",
252     "        )\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)\n",
259     "        # Add model output to case\n",
260     "        train[case]['m']=m\n",
261     "        # Get RMSE Prediction Error\n",
262     "        print(f\"RMSE: {errs}\")\n",
263     "        outputs_rnn[case] = {'case':case, 'errs': errs.copy()}\n",
264     "        \n",
265     "        # Run Augmented KF\n",
266     "        print('Running Augmented KF')\n",
267     "        train[case]['h2'] = train[case]['hours'] // 2\n",
268     "        train[case]['scale_fm'] = 1\n",
269     "        m, Ec = run_augmented_kf(train[case])\n",
270     "        m = m*rnn_dat['scale_fm']\n",
271     "        y = rnn_dat['y']*rnn_dat['scale_fm']          \n",
272     "        train[case]['m'] = m\n",
273     "        print(f\"KF RMSE: {rmse(m,y)}\")\n",
274     "        outputs_kf[case] = {'case':case, 'errs': rmse(m,y)}\n",
275     "\n",
276     "        # Save Outputs \n",
277     "        to_json(outputs_rnn, \"rnn_errs.json\")\n",
278     "        to_json(outputs_kf, \"kf_errs.json\")"
279    ]
280   },
281   {
282    "cell_type": "code",
283    "execution_count": null,
284    "id": "15384e4d-b8ec-4700-bdc2-83b0433d11c9",
285    "metadata": {},
286    "outputs": [],
287    "source": [
288     "logging.info('fmda_rnn_serial.ipynb done')"
289    ]
290   },
291   {
292    "cell_type": "code",
293    "execution_count": null,
294    "id": "d0e78fb3-b501-49d6-81a9-1a13da0134a0",
295    "metadata": {},
296    "outputs": [],
297    "source": [
298     "import importlib\n",
299     "import moisture_rnn\n",
300     "importlib.reload(moisture_rnn)\n",
301     "from moisture_rnn import RNN"
302    ]
303   },
304   {
305    "cell_type": "code",
306    "execution_count": null,
307    "id": "37053436-8dfe-4c40-8614-811817e83782",
308    "metadata": {},
309    "outputs": [],
310    "source": [
311     "for k in outputs_rnn:\n",
312     "    print(\"~\"*50)\n",
313     "    print(outputs_rnn[k]['case'])\n",
314     "    print(outputs_rnn[k]['errs']['prediction'])"
315    ]
316   },
317   {
318    "cell_type": "code",
319    "execution_count": null,
320    "id": "9154d5f7-015f-4ef7-af45-020410a1ea65",
321    "metadata": {},
322    "outputs": [],
323    "source": [
324     "for k in outputs_kf:\n",
325     "    print(\"~\"*50)\n",
326     "    print(outputs_kf[k]['case'])\n",
327     "    print(outputs_kf[k]['errs'])"
328    ]
329   },
330   {
331    "cell_type": "markdown",
332    "id": "f3c1c299-1655-4c64-a458-c7723db6ea6d",
333    "metadata": {},
334    "source": [
335     "### TODO: FIX SCALING in Scheme below\n",
336     "\n",
337     "Scaling is done separately in each now."
338    ]
339   },
340   {
341    "cell_type": "markdown",
342    "id": "0c0c3470-30f5-4915-98a7-dcdf5760d482",
343    "metadata": {},
344    "source": [
345     "## Training at Multiple Locations\n",
346     "\n",
347     "Still sequential"
348    ]
349   },
350   {
351    "cell_type": "code",
352    "execution_count": null,
353    "id": "dd1aca73-7279-473e-b2a3-95aa1db7b1a8",
354    "metadata": {},
355    "outputs": [],
356    "source": [
357     "params = RNNParams(params_all['rnn'])\n",
358     "params.update({\n",
359     "    'epochs': 1, # less epochs since it is per location\n",
360     "    'activation': ['relu', 'relu'],\n",
361     "    'train_frac': .9,\n",
362     "    'val_frac': .05,    \n",
363     "    'dense_units': 10,\n",
364     "    'rnn_layers': 2\n",
365     "})\n",
366     "\n",
367     "# rnn_dat = create_rnn_data2(train[cases[0]], params)\n",
368     "rnn_dat = RNNData(train[cases[0]], params['scaler'], params['features_list'])\n",
369     "rnn_dat.train_test_split(\n",
370     "    time_fracs = [.9, .05, .05]\n",
371     ")\n",
372     "rnn_dat.scale_data()\n",
373     "rnn_dat.batch_reshape(timesteps = params['timesteps'], batch_size = params['batch_size'])"
374    ]
375   },
376   {
377    "cell_type": "code",
378    "execution_count": null,
379    "id": "65b2f9a3-a8f2-4ac1-8e4d-ba38a86eaf40",
380    "metadata": {},
381    "outputs": [],
382    "source": [
383     "reproducibility.set_seed()\n",
384     "rnn = RNN(params)"
385    ]
386   },
387   {
388    "cell_type": "code",
389    "execution_count": null,
390    "id": "47a85ef2-8145-4de8-9f2e-86622306ffd8",
391    "metadata": {
392     "scrolled": true
393    },
394    "outputs": [],
395    "source": [
396     "print(\"~\"*80)\n",
397     "print(\"Running with params:\")\n",
398     "print(params)\n",
399     "\n",
400     "for case in cases[0:10]:\n",
401     "    print(\"~\"*50)\n",
402     "    logging.info('Processing case %s',case)\n",
403     "    print_dict_summary(train[case])\n",
404     "    rnn_dat_temp = RNNData(train[case], params['scaler'], params['features_list'])\n",
405     "    rnn_dat_temp.train_test_split(\n",
406     "        time_fracs = [.9, .05, .05]\n",
407     "    )\n",
408     "    rnn_dat_temp.scale_data()\n",
409     "    rnn_dat_temp.batch_reshape(timesteps = params['timesteps'], batch_size = params['batch_size'])\n",
410     "    rnn.fit(rnn_dat_temp['X_train'], rnn_dat_temp['y_train'],\n",
411     "           validation_data=(rnn_dat_temp['X_val'], rnn_dat_temp['y_val']))\n",
412     "    # run_rnn_pkl(train[case],param_sets[i])"
413    ]
414   },
415   {
416    "cell_type": "markdown",
417    "id": "a0421b8d-49aa-4409-8cbf-7732f1137838",
418    "metadata": {},
419    "source": [
420     "### Predict "
421    ]
422   },
423   {
424    "cell_type": "code",
425    "execution_count": null,
426    "id": "63d7854a-94f7-425c-9561-4fe518e044bb",
427    "metadata": {
428     "scrolled": true
429    },
430    "outputs": [],
431    "source": [
432     "# Predict Cases Used in Training\n",
433     "rmses = []\n",
434     "inds = np.arange(0,10)\n",
435     "train_keys = list(train.keys())\n",
436     "for i in inds:\n",
437     "    print(\"~\"*50)\n",
438     "    case = train_keys[i]\n",
439     "    print(f\"Predicting case {case}\")\n",
440     "    # rnn_dat = create_rnn_data2(train[case], params)\n",
441     "    rnn_dat_temp = RNNData(train[case], params['scaler'], params['features_list'])\n",
442     "    rnn_dat_temp.train_test_split(\n",
443     "        time_fracs = [.9, .05, .05]\n",
444     "    )\n",
445     "    rnn_dat_temp.scale_data()\n",
446     "    rnn_dat_temp.batch_reshape(timesteps = params['timesteps'], batch_size = params['batch_size'])\n",
447     "    X_temp = rnn_dat_temp.scale_all_X()\n",
448     "    m = rnn.predict(X_temp)\n",
449     "    test_ind = rnn_dat['test_ind']\n",
450     "    rmses.append(rmse(m[test_ind:], rnn_dat['y_test'].flatten()))"
451    ]
452   },
453   {
454    "cell_type": "code",
455    "execution_count": null,
456    "id": "2a5423e0-778b-4f69-9ed0-f0082a1fefe5",
457    "metadata": {},
458    "outputs": [],
459    "source": [
460     "rmses"
461    ]
462   },
463   {
464    "cell_type": "code",
465    "execution_count": null,
466    "id": "45c9caae-7ced-4f21-aa05-c9b125e8fdcb",
467    "metadata": {},
468    "outputs": [],
469    "source": [
470     "pd.DataFrame({'Case': list(train.keys())[0:10], 'RMSE': rmses}).style.hide(axis=\"index\")"
471    ]
472   },
473   {
474    "cell_type": "code",
475    "execution_count": null,
476    "id": "f710f482-b600-4ea5-9a8a-823a13b4ec7a",
477    "metadata": {
478     "scrolled": true
479    },
480    "outputs": [],
481    "source": [
482     "# Predict New Locations\n",
483     "rmses = []\n",
484     "for i, case in enumerate(list(train.keys())[10:100]):\n",
485     "    print(\"~\"*50)\n",
486     "    print(f\"Predicting case {case}\")\n",
487     "    rnn_dat_temp = RNNData(train[case], params['scaler'], params['features_list'])\n",
488     "    rnn_dat_temp.train_test_split(\n",
489     "        time_fracs = [.9, .05, .05]\n",
490     "    )\n",
491     "    rnn_dat_temp.scale_data()\n",
492     "    rnn_dat_temp.batch_reshape(timesteps = params['timesteps'], batch_size = params['batch_size'])\n",
493     "    X = rnn_dat_temp.scale_all_X()\n",
494     "    m = rnn.predict(X)\n",
495     "    train[case]['m'] = m\n",
496     "    test_ind = rnn_dat['test_ind']\n",
497     "    rmses.append(rmse(m[test_ind:], rnn_dat.y_test.flatten()))\n",
498     "\n",
499     "df = pd.DataFrame({'Case': list(train.keys())[10:100], 'RMSE': rmses})"
500    ]
501   },
502   {
503    "cell_type": "code",
504    "execution_count": null,
505    "id": "d793ac87-d94b-4b16-a271-46cdc259b4fe",
506    "metadata": {},
507    "outputs": [],
508    "source": [
509     "df[0:5].style.hide(axis=\"index\")"
510    ]
511   },
512   {
513    "cell_type": "code",
514    "execution_count": null,
515    "id": "b99606d1-bd46-4041-8303-1bcbb196f6f4",
516    "metadata": {},
517    "outputs": [],
518    "source": [
519     "df"
520    ]
521   },
522   {
523    "cell_type": "code",
524    "execution_count": null,
525    "id": "52ec264d-d4b7-444c-b623-002d6383da30",
526    "metadata": {},
527    "outputs": [],
528    "source": [
529     "df.RMSE.mean()"
530    ]
531   },
532   {
533    "cell_type": "code",
534    "execution_count": null,
535    "id": "998922cd-46bb-4063-8284-0497e19c39b0",
536    "metadata": {},
537    "outputs": [],
538    "source": [
539     "plt.hist(df.RMSE)"
540    ]
541   },
542   {
543    "cell_type": "code",
544    "execution_count": null,
545    "id": "889f3bbb-9fb2-4621-9e93-1d0bc0f83e01",
546    "metadata": {},
547    "outputs": [],
548    "source": []
549   },
550   {
551    "cell_type": "code",
552    "execution_count": null,
553    "id": "fe407f61-15f2-4086-a386-7d7a5bb90d26",
554    "metadata": {},
555    "outputs": [],
556    "source": []
557   },
558   {
559    "cell_type": "code",
560    "execution_count": null,
561    "id": "2fdb63b3-68b8-4877-a7a2-f63257cb29d5",
562    "metadata": {},
563    "outputs": [],
564    "source": []
565   },
566   {
567    "cell_type": "code",
568    "execution_count": null,
569    "id": "5c7563c5-a880-45c7-8381-8ce4e1a44216",
570    "metadata": {},
571    "outputs": [],
572    "source": []
573   },
574   {
575    "cell_type": "code",
576    "execution_count": null,
577    "id": "ad5dae6c-1269-4674-a49e-2efe8b956911",
578    "metadata": {},
579    "outputs": [],
580    "source": []
581   }
582  ],
583  "metadata": {
584   "kernelspec": {
585    "display_name": "Python 3 (ipykernel)",
586    "language": "python",
587    "name": "python3"
588   },
589   "language_info": {
590    "codemirror_mode": {
591     "name": "ipython",
592     "version": 3
593    },
594    "file_extension": ".py",
595    "mimetype": "text/x-python",
596    "name": "python",
597    "nbconvert_exporter": "python",
598    "pygments_lexer": "ipython3",
599    "version": "3.12.5"
600   }
601  },
602  "nbformat": 4,
603  "nbformat_minor": 5