deepof_model_evaluation.ipynb 16.7 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "%load_ext autoreload\n",
    "%autoreload 2"
   ]
  },
13
14
15
16
17
18
19
20
21
22
  {
   "cell_type": "code",
   "execution_count": 67,
   "metadata": {},
   "outputs": [],
   "source": [
    "import warnings\n",
    "warnings.filterwarnings(\"ignore\")"
   ]
  },
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# deepOF model evaluation"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Given a dataset and a trained model, this notebook allows the user to \n",
    "\n",
    "* Load and inspect the different models (encoder, decoder, grouper, gmvaep)\n",
    "* Visualize reconstruction quality for a given model\n",
    "* Visualize a static latent space\n",
    "* Visualize trajectories on the latent space for a given video\n",
    "* sample from the latent space distributions and generate video clips showcasing generated data"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "os.chdir(os.path.dirname(\"../\"))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {},
   "outputs": [],
   "source": [
    "import deepof.data\n",
    "import deepof.utils\n",
    "import numpy as np\n",
    "import pandas as pd\n",
    "import tensorflow as tf\n",
    "from sklearn.preprocessing import StandardScaler\n",
    "\n",
    "from ipywidgets import interact\n",
    "from IPython import display\n",
    "from matplotlib.animation import FuncAnimation\n",
    "import matplotlib.pyplot as plt\n",
    "import seaborn as sns\n",
    "\n",
    "from ipywidgets import interact"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 1. Define and run project"
   ]
  },
  {
   "cell_type": "code",
84
   "execution_count": 75,
85
86
87
88
   "metadata": {},
   "outputs": [],
   "source": [
    "path = os.path.join(\"..\", \"..\", \"Desktop\", \"deepoftesttemp\")\n",
89
90
91
    "trained_network = os.path.join(\"..\", \"..\", \"Desktop\")\n",
    "exclude_bodyparts = [\"Tail_1\", \"Tail_2\", \"Tail_tip\", \"Tail_base\"]\n",
    "window_size = 24"
92
93
94
95
   ]
  },
  {
   "cell_type": "code",
96
   "execution_count": 54,
97
98
99
100
101
102
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
103
104
      "CPU times: user 280 ms, sys: 22.3 ms, total: 303 ms\n",
      "Wall time: 250 ms\n"
105
106
107
108
109
110
111
112
     ]
    }
   ],
   "source": [
    "%%time\n",
    "proj = deepof.data.project(\n",
    "    path=path,\n",
    "    smooth_alpha=0.99,\n",
113
    "    exclude_bodyparts=exclude_bodyparts,\n",
114
115
116
117
118
119
    "    arena_dims=[380],\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
120
   "execution_count": 55,
121
122
123
124
125
126
127
128
129
130
131
132
133
134
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Loading trajectories...\n",
      "Smoothing trajectories...\n",
      "Interpolating outliers...\n",
      "Iterative imputation of ocluded bodyparts...\n",
      "Computing distances...\n",
      "Computing angles...\n",
      "Done!\n",
      "deepof analysis of 2 videos\n",
135
136
      "CPU times: user 2.63 s, sys: 85.8 ms, total: 2.71 s\n",
      "Wall time: 634 ms\n"
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
     ]
    }
   ],
   "source": [
    "%%time\n",
    "proj = proj.run(verbose=True)\n",
    "print(proj)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 2. Load pretrained deepof model"
   ]
  },
  {
   "cell_type": "code",
155
   "execution_count": 56,
156
157
158
159
   "metadata": {},
   "outputs": [],
   "source": [
    "coords = proj.get_coords(center=\"Center\", align=\"Spine_1\", align_inplace=True)\n",
160
    "preprocessed_data,_,_,_ = coords.preprocess(test_videos=0, window_step=5, window_size=window_size)"
161
162
163
164
   ]
  },
  {
   "cell_type": "code",
165
   "execution_count": 57,
166
167
168
169
170
171
172
173
174
175
176
177
178
   "metadata": {},
   "outputs": [],
   "source": [
    "# Set model parameters\n",
    "encoding=6\n",
    "loss=\"ELBO\"\n",
    "k=25\n",
    "pheno=0\n",
    "predictor=0"
   ]
  },
  {
   "cell_type": "code",
179
   "execution_count": 58,
180
   "metadata": {},
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
   "outputs": [
    {
     "ename": "ValueError",
     "evalue": "You are trying to load a weight file containing 15 layers into a model with 14 layers.",
     "output_type": "error",
     "traceback": [
      "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[0;31mValueError\u001b[0m                                Traceback (most recent call last)",
      "\u001b[0;32m<ipython-input-58-ea431bf97d05>\u001b[0m in \u001b[0;36m<module>\u001b[0;34m\u001b[0m\n\u001b[1;32m     10\u001b[0m gmvaep.load_weights(\n\u001b[1;32m     11\u001b[0m     os.path.join(\n\u001b[0;32m---> 12\u001b[0;31m         \u001b[0mtrained_network\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;34m[\u001b[0m\u001b[0mi\u001b[0m \u001b[0;32mfor\u001b[0m \u001b[0mi\u001b[0m \u001b[0;32min\u001b[0m \u001b[0mos\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mlistdir\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mtrained_network\u001b[0m\u001b[0;34m)\u001b[0m \u001b[0;32mif\u001b[0m \u001b[0mi\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mendswith\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m\"h5\"\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m]\u001b[0m\u001b[0;34m[\u001b[0m\u001b[0;36m0\u001b[0m\u001b[0;34m]\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m     13\u001b[0m     )\n\u001b[1;32m     14\u001b[0m )\n",
      "\u001b[0;32m~/opt/anaconda3/envs/Machine_Learning/lib/python3.6/site-packages/tensorflow/python/keras/engine/training.py\u001b[0m in \u001b[0;36mload_weights\u001b[0;34m(self, filepath, by_name, skip_mismatch, options)\u001b[0m\n\u001b[1;32m   2232\u001b[0m             f, self.layers, skip_mismatch=skip_mismatch)\n\u001b[1;32m   2233\u001b[0m       \u001b[0;32melse\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m-> 2234\u001b[0;31m         \u001b[0mhdf5_format\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mload_weights_from_hdf5_group\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mf\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mself\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mlayers\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m   2235\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m   2236\u001b[0m   \u001b[0;32mdef\u001b[0m \u001b[0m_updated_config\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mself\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n",
      "\u001b[0;32m~/opt/anaconda3/envs/Machine_Learning/lib/python3.6/site-packages/tensorflow/python/keras/saving/hdf5_format.py\u001b[0m in \u001b[0;36mload_weights_from_hdf5_group\u001b[0;34m(f, layers)\u001b[0m\n\u001b[1;32m    686\u001b[0m                      \u001b[0;34m'containing '\u001b[0m \u001b[0;34m+\u001b[0m \u001b[0mstr\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mlen\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mlayer_names\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m)\u001b[0m \u001b[0;34m+\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m    687\u001b[0m                      \u001b[0;34m' layers into a model with '\u001b[0m \u001b[0;34m+\u001b[0m \u001b[0mstr\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mlen\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mfiltered_layers\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m)\u001b[0m \u001b[0;34m+\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m--> 688\u001b[0;31m                      ' layers.')\n\u001b[0m\u001b[1;32m    689\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m    690\u001b[0m   \u001b[0;31m# We batch weight value assignments in a single backend call\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n",
      "\u001b[0;31mValueError\u001b[0m: You are trying to load a weight file containing 15 layers into a model with 14 layers."
     ]
    }
   ],
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
   "source": [
    "encoder, decoder, grouper, gmvaep = deepof.models.SEQ_2_SEQ_GMVAE(\n",
    "    loss=loss,\n",
    "    number_of_components=k,\n",
    "    compile_model=True,\n",
    "    encoding=encoding,\n",
    "    predictor=predictor,\n",
    "    phenotype_prediction=pheno,\n",
    ").build(preprocessed_data.shape)[:4]\n",
    "\n",
    "gmvaep.load_weights(\n",
    "    os.path.join(\n",
    "        trained_network, [i for i in os.listdir(trained_network) if i.endswith(\"h5\")][0]\n",
    "    )\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
215
   "execution_count": 59,
216
217
218
219
220
221
222
223
224
225
226
227
228
229
   "metadata": {
    "scrolled": true
   },
   "outputs": [],
   "source": [
    "# Uncomment to see model summaries\n",
    "# encoder.summary()\n",
    "# decoder.summary()\n",
    "# grouper.summary()\n",
    "# gmvaep.summary()"
   ]
  },
  {
   "cell_type": "code",
230
   "execution_count": 60,
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
   "metadata": {},
   "outputs": [],
   "source": [
    "# Uncomment to plot model structure\n",
    "def plot_model(model, name):\n",
    "    tf.keras.utils.plot_model(\n",
    "        model,\n",
    "        to_file=os.path.join(\n",
    "            path,\n",
    "            \"deepof_{}_{}.png\".format(name, datetime.now().strftime(\"%Y%m%d-%H%M%S\")),\n",
    "        ),\n",
    "        show_shapes=True,\n",
    "        show_dtype=False,\n",
    "        show_layer_names=True,\n",
    "        rankdir=\"TB\",\n",
    "        expand_nested=True,\n",
    "        dpi=200,\n",
    "    )\n",
    "\n",
    "\n",
    "# plot_model(encoder, \"encoder\")\n",
    "# plot_model(decoder, \"decoder\")\n",
    "# plot_model(grouper, \"grouper\")\n",
    "# plot_model(gmvaep, \"gmvaep\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 4. Pass data through all models"
   ]
  },
  {
   "cell_type": "code",
266
   "execution_count": 61,
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
   "metadata": {},
   "outputs": [],
   "source": [
    "encodings = encoder.predict(preprocessed_data)\n",
    "groupings = grouper.predict(preprocessed_data)\n",
    "reconstrs = gmvaep.predict(preprocessed_data)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 5. Evaluate reconstruction (to be incorporated into deepof.evaluate)"
   ]
  },
  {
   "cell_type": "code",
284
   "execution_count": 62,
285
286
287
288
289
290
291
292
293
   "metadata": {},
   "outputs": [],
   "source": [
    "# Fit a scaler to the data, to back-transform reconstructions later\n",
    "scaler = StandardScaler().fit(preprocessed_data[:, 0, :])"
   ]
  },
  {
   "cell_type": "code",
294
   "execution_count": 63,
295
296
297
298
   "metadata": {},
   "outputs": [],
   "source": [
    "# Rescale reconstructions\n",
299
    "rescaled_reconstructions = scaler.inverse_transform(\n",
300
301
302
303
304
305
306
    "    reconstrs.reshape(reconstrs.shape[0] * reconstrs.shape[1], reconstrs.shape[2])\n",
    ")\n",
    "rescaled_reconstructions = rescaled_reconstructions.reshape(reconstrs.shape)"
   ]
  },
  {
   "cell_type": "code",
307
   "execution_count": 98,
308
309
310
   "metadata": {},
   "outputs": [],
   "source": [
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
    "# Auxiliary animation functions\n",
    "\n",
    "\n",
    "def plot_mouse_graph(instant_x, instant_y, instant_rec_x, instant_rec_y, ax, edges):\n",
    "    \"\"\"Generates a graph plot of the mouse\"\"\"\n",
    "    plots = []\n",
    "    rec_plots = []\n",
    "    for edge in edges:\n",
    "        (temp_plot,) = ax.plot(\n",
    "            [float(instant_x[edge[0]]), float(instant_x[edge[1]])],\n",
    "            [float(instant_y[edge[0]]), float(instant_y[edge[1]])],\n",
    "            color=\"#006699\",\n",
    "        )\n",
    "        (temp_rec_plot,) = ax.plot(\n",
    "            [float(instant_rec_x[edge[0]]), float(instant_rec_x[edge[1]])],\n",
    "            [float(instant_rec_y[edge[0]]), float(instant_rec_y[edge[1]])],\n",
    "            color=\"#006699\",\n",
    "        )\n",
    "        plots.append(temp_plot)\n",
    "        rec_plots.append(temp_rec_plot)\n",
    "    return plots\n",
    "\n",
    "\n",
    "def update_mouse_graph(x, y, plots, edges):\n",
    "    \"\"\"Updates the graph plot to enable animation\"\"\"\n",
    "\n",
    "    for plot, edge in zip(plots, edges):\n",
    "        plot.set_data(\n",
    "            [float(x[edge[0]]), float(x[edge[1]])],\n",
    "            [float(y[edge[0]]), float(y[edge[1]])],\n",
    "        )"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 100,
   "metadata": {
    "scrolled": false
   },
   "outputs": [
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "db7a005dac9b4673bc2c91dac50c7db0",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "interactive(children=(FloatSlider(value=7500.0, description='time_slider', max=15000.0, step=500.0), IntSlider…"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "# Display a video with the original data superimposed with the reconstructions\n",
    "\n",
    "random_exp = np.random.choice(list(coords.keys()), 1)[0]\n",
    "\n",
    "\n",
    "@interact(time_slider=(0.0, 15000, 500), length_slider=(0, 1000, 100))\n",
    "def animate_mice_across_time(time_slider, length_slider):\n",
    "\n",
    "    fig, ax = plt.subplots(1, 1, figsize=(10, 10))\n",
    "\n",
    "    edges = deepof.utils.connect_mouse_topview()\n",
    "\n",
    "    for bpart in exclude_bodyparts:\n",
    "        edges.remove_node(bpart)\n",
    "\n",
    "    for limb in [\"Left_fhip\", \"Right_fhip\", \"Left_bhip\", \"Right_bhip\"]:\n",
    "        edges.remove_edge(\"Center\", limb)\n",
    "\n",
    "    edges = edges.edges()\n",
    "\n",
    "    data = coords[random_exp].loc[time_slider : time_slider + length_slider - 1, :]\n",
    "    data_rec = gmvaep.predict(\n",
    "        coords.filter_videos([random_exp]).preprocess(\n",
    "            test_videos=0, window_step=5, window_size=window_size\n",
    "        )[0]\n",
    "    )\n",
    "    data_rec = pd.DataFrame(scaler.inverse_transform(data_rec[:, 24 // 2, :]))\n",
    "    data_rec.columns = data.columns\n",
    "\n",
    "    data[\"Center\", \"x\"] = 0\n",
    "    data[\"Center\", \"y\"] = 0\n",
    "    data_rec[\"Center\", \"x\"] = 0\n",
    "    data_rec[\"Center\", \"y\"] = 0\n",
    "\n",
    "    init_x = data.xs(\"x\", level=1, axis=1, drop_level=False).iloc[0, :]\n",
    "    init_y = data.xs(\"y\", level=1, axis=1, drop_level=False).iloc[0, :]\n",
    "    init_rec_x = data_rec.xs(\"x\", level=1, axis=1, drop_level=False).iloc[0, :]\n",
    "    init_rec_y = data_rec.xs(\"y\", level=1, axis=1, drop_level=False).iloc[0, :]\n",
    "\n",
    "    plots = plot_mouse_graph(init_x, init_y, init_rec_x, init_rec_y, ax, edges)\n",
    "    scatter = ax.scatter(x=np.array(init_x), y=np.array(init_y), color=\"#006699\",)\n",
    "    rec_scatter = ax.scatter(\n",
    "        x=np.array(init_rec_x), y=np.array(init_rec_y), color=\"#006699\",\n",
    "    )\n",
    "\n",
    "    # Update data in main plot\n",
    "    def animation_frame(i):\n",
    "        # Update scatter plot\n",
    "        x = data.xs(\"x\", level=1, axis=1, drop_level=False).iloc[i, :]\n",
    "        y = data.xs(\"y\", level=1, axis=1, drop_level=False).iloc[i, :]\n",
    "        rec_x = data_rec.xs(\"x\", level=1, axis=1, drop_level=False).iloc[i, :]\n",
    "        rec_y = data_rec.xs(\"y\", level=1, axis=1, drop_level=False).iloc[i, :]\n",
    "        \n",
    "        scatter.set_offsets(np.c_[np.array(x), np.array(y)])\n",
    "        scatter.set_offsets(np.c_[np.array(rec_x), np.array(rec_y)])\n",
    "        update_mouse_graph(x, y, plots, edges)\n",
    "\n",
    "        return scatter\n",
    "\n",
    "    animation = FuncAnimation(\n",
    "        fig, func=animation_frame, frames=length_slider, interval=100,\n",
    "    )\n",
    "\n",
    "    ax.set_title(\"Positions across time for centered data\")\n",
    "    ax.set_ylim(-100, 60)\n",
    "    ax.set_xlim(-60, 60)\n",
    "    ax.set_xlabel(\"x\")\n",
    "    ax.set_ylabel(\"y\")\n",
    "\n",
    "    video = animation.to_html5_video()\n",
    "    html = display.HTML(video)\n",
    "    display.display(html)\n",
    "    plt.close()"
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 6. Evaluate latent space (to be incorporated into deepof.evaluate)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
456
457
458
459
460
461
462
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.10"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}