Update other ML models, handle params better
[notebooks.git] / fmda / fmda_rnn_serial.ipynb
blob2cb928b05f2cb79f4e34253a0f2ae019f5ffa672
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 = \"data/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='data/train.pkl'\n",
84     "train_create=True   # if false, read\n",
85     "train_write=True\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:50]\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, 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",
264     "        \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",
274     "\n",
275     "        # Save Outputs \n",
276     "        to_json(outputs_rnn, \"rnn_errs.json\")\n",
277     "        to_json(outputs_kf, \"kf_errs.json\")"
278    ]
279   },
280   {
281    "cell_type": "code",
282    "execution_count": null,
283    "id": "15384e4d-b8ec-4700-bdc2-83b0433d11c9",
284    "metadata": {},
285    "outputs": [],
286    "source": [
287     "logging.info('fmda_rnn_serial.ipynb done')"
288    ]
289   },
290   {
291    "cell_type": "code",
292    "execution_count": null,
293    "id": "d0e78fb3-b501-49d6-81a9-1a13da0134a0",
294    "metadata": {},
295    "outputs": [],
296    "source": [
297     "import importlib\n",
298     "import moisture_rnn\n",
299     "importlib.reload(moisture_rnn)\n",
300     "from moisture_rnn import RNN"
301    ]
302   },
303   {
304    "cell_type": "code",
305    "execution_count": null,
306    "id": "37053436-8dfe-4c40-8614-811817e83782",
307    "metadata": {},
308    "outputs": [],
309    "source": [
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'])"
314    ]
315   },
316   {
317    "cell_type": "code",
318    "execution_count": null,
319    "id": "9154d5f7-015f-4ef7-af45-020410a1ea65",
320    "metadata": {},
321    "outputs": [],
322    "source": [
323     "for k in outputs_kf:\n",
324     "    print(\"~\"*50)\n",
325     "    print(outputs_kf[k]['case'])\n",
326     "    print(outputs_kf[k]['errs'])"
327    ]
328   },
329   {
330    "cell_type": "code",
331    "execution_count": null,
332    "id": "dfd90d87-fe08-48b5-8cc4-31bd19c5c20a",
333    "metadata": {},
334    "outputs": [],
335    "source": []
336   },
337   {
338    "cell_type": "markdown",
339    "id": "f3c1c299-1655-4c64-a458-c7723db6ea6d",
340    "metadata": {},
341    "source": [
342     "### TODO: FIX SCALING in Scheme below\n",
343     "\n",
344     "Scaling is done separately in each now."
345    ]
346   },
347   {
348    "cell_type": "markdown",
349    "id": "0c0c3470-30f5-4915-98a7-dcdf5760d482",
350    "metadata": {},
351    "source": [
352     "## Training at Multiple Locations\n",
353     "\n",
354     "Still sequential"
355    ]
356   },
357   {
358    "cell_type": "code",
359    "execution_count": null,
360    "id": "dd1aca73-7279-473e-b2a3-95aa1db7b1a8",
361    "metadata": {},
362    "outputs": [],
363    "source": [
364     "params = RNNParams(params_all['rnn'])\n",
365     "params.update({\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",
372     "})\n",
373     "\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",
378     ")\n",
379     "rnn_dat.scale_data()\n",
380     "rnn_dat.batch_reshape(timesteps = params['timesteps'], batch_size = params['batch_size'])"
381    ]
382   },
383   {
384    "cell_type": "code",
385    "execution_count": null,
386    "id": "65b2f9a3-a8f2-4ac1-8e4d-ba38a86eaf40",
387    "metadata": {},
388    "outputs": [],
389    "source": [
390     "reproducibility.set_seed()\n",
391     "rnn = RNN(params)"
392    ]
393   },
394   {
395    "cell_type": "code",
396    "execution_count": null,
397    "id": "47a85ef2-8145-4de8-9f2e-86622306ffd8",
398    "metadata": {
399     "scrolled": true
400    },
401    "outputs": [],
402    "source": [
403     "print(\"~\"*80)\n",
404     "print(\"Running with params:\")\n",
405     "print(params)\n",
406     "\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",
414     "    )\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])"
420    ]
421   },
422   {
423    "cell_type": "markdown",
424    "id": "a0421b8d-49aa-4409-8cbf-7732f1137838",
425    "metadata": {},
426    "source": [
427     "### Predict "
428    ]
429   },
430   {
431    "cell_type": "code",
432    "execution_count": null,
433    "id": "63d7854a-94f7-425c-9561-4fe518e044bb",
434    "metadata": {
435     "scrolled": true
436    },
437    "outputs": [],
438    "source": [
439     "# Predict Cases Used in Training\n",
440     "rmses = []\n",
441     "inds = np.arange(0,10)\n",
442     "train_keys = list(train.keys())\n",
443     "for i in inds:\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",
451     "    )\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()))"
458    ]
459   },
460   {
461    "cell_type": "code",
462    "execution_count": null,
463    "id": "2a5423e0-778b-4f69-9ed0-f0082a1fefe5",
464    "metadata": {},
465    "outputs": [],
466    "source": [
467     "rmses"
468    ]
469   },
470   {
471    "cell_type": "code",
472    "execution_count": null,
473    "id": "45c9caae-7ced-4f21-aa05-c9b125e8fdcb",
474    "metadata": {},
475    "outputs": [],
476    "source": [
477     "pd.DataFrame({'Case': list(train.keys())[0:10], 'RMSE': rmses}).style.hide(axis=\"index\")"
478    ]
479   },
480   {
481    "cell_type": "code",
482    "execution_count": null,
483    "id": "f710f482-b600-4ea5-9a8a-823a13b4ec7a",
484    "metadata": {
485     "scrolled": true
486    },
487    "outputs": [],
488    "source": [
489     "# Predict New Locations\n",
490     "rmses = []\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",
497     "    )\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",
505     "\n",
506     "df = pd.DataFrame({'Case': list(train.keys())[10:100], 'RMSE': rmses})"
507    ]
508   },
509   {
510    "cell_type": "code",
511    "execution_count": null,
512    "id": "d793ac87-d94b-4b16-a271-46cdc259b4fe",
513    "metadata": {},
514    "outputs": [],
515    "source": [
516     "df[0:5].style.hide(axis=\"index\")"
517    ]
518   },
519   {
520    "cell_type": "code",
521    "execution_count": null,
522    "id": "b99606d1-bd46-4041-8303-1bcbb196f6f4",
523    "metadata": {},
524    "outputs": [],
525    "source": [
526     "df"
527    ]
528   },
529   {
530    "cell_type": "code",
531    "execution_count": null,
532    "id": "52ec264d-d4b7-444c-b623-002d6383da30",
533    "metadata": {},
534    "outputs": [],
535    "source": [
536     "df.RMSE.mean()"
537    ]
538   },
539   {
540    "cell_type": "code",
541    "execution_count": null,
542    "id": "998922cd-46bb-4063-8284-0497e19c39b0",
543    "metadata": {},
544    "outputs": [],
545    "source": [
546     "plt.hist(df.RMSE)"
547    ]
548   },
549   {
550    "cell_type": "code",
551    "execution_count": null,
552    "id": "889f3bbb-9fb2-4621-9e93-1d0bc0f83e01",
553    "metadata": {},
554    "outputs": [],
555    "source": []
556   },
557   {
558    "cell_type": "code",
559    "execution_count": null,
560    "id": "fe407f61-15f2-4086-a386-7d7a5bb90d26",
561    "metadata": {},
562    "outputs": [],
563    "source": []
564   },
565   {
566    "cell_type": "code",
567    "execution_count": null,
568    "id": "2fdb63b3-68b8-4877-a7a2-f63257cb29d5",
569    "metadata": {},
570    "outputs": [],
571    "source": []
572   },
573   {
574    "cell_type": "code",
575    "execution_count": null,
576    "id": "5c7563c5-a880-45c7-8381-8ce4e1a44216",
577    "metadata": {},
578    "outputs": [],
579    "source": []
580   },
581   {
582    "cell_type": "code",
583    "execution_count": null,
584    "id": "ad5dae6c-1269-4674-a49e-2efe8b956911",
585    "metadata": {},
586    "outputs": [],
587    "source": []
588   }
589  ],
590  "metadata": {
591   "kernelspec": {
592    "display_name": "Python 3 (ipykernel)",
593    "language": "python",
594    "name": "python3"
595   },
596   "language_info": {
597    "codemirror_mode": {
598     "name": "ipython",
599     "version": 3
600    },
601    "file_extension": ".py",
602    "mimetype": "text/x-python",
603    "name": "python",
604    "nbconvert_exporter": "python",
605    "pygments_lexer": "ipython3",
606    "version": "3.12.5"
607   }
608  },
609  "nbformat": 4,
610  "nbformat_minor": 5