deepof_model_evaluation.ipynb 26.2 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
  {
   "cell_type": "code",
15
   "execution_count": 2,
16
17
18
19
   "metadata": {},
   "outputs": [],
   "source": [
    "import warnings\n",
20
    "\n",
21
22
23
    "warnings.filterwarnings(\"ignore\")"
   ]
  },
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
  {
   "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",
46
   "execution_count": 3,
47
48
49
50
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
51
    "\n",
52
53
54
55
56
    "os.chdir(os.path.dirname(\"../\"))"
   ]
  },
  {
   "cell_type": "code",
57
   "execution_count": 4,
58
59
60
61
62
63
64
65
   "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",
66
    "from collections import Counter\n",
67
68
    "from sklearn.preprocessing import StandardScaler\n",
    "\n",
69
70
71
72
73
    "from sklearn.manifold import TSNE\n",
    "from sklearn.decomposition import PCA\n",
    "from sklearn.discriminant_analysis import LinearDiscriminantAnalysis\n",
    "import umap\n",
    "\n",
74
    "from ipywidgets import interactive, interact, HBox, Layout, VBox\n",
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
    "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",
92
   "execution_count": 5,
93
94
95
96
   "metadata": {},
   "outputs": [],
   "source": [
    "path = os.path.join(\"..\", \"..\", \"Desktop\", \"deepoftesttemp\")\n",
97
98
    "trained_network = os.path.join(\"..\", \"..\", \"Desktop\")\n",
    "exclude_bodyparts = [\"Tail_1\", \"Tail_2\", \"Tail_tip\", \"Tail_base\"]\n",
99
    "window_size = 11"
100
101
102
103
   ]
  },
  {
   "cell_type": "code",
104
   "execution_count": 6,
105
106
107
108
109
110
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
111
112
      "CPU times: user 429 ms, sys: 37.5 ms, total: 466 ms\n",
      "Wall time: 375 ms\n"
113
114
115
116
117
118
     ]
    }
   ],
   "source": [
    "%%time\n",
    "proj = deepof.data.project(\n",
119
    "    path=path, smooth_alpha=0.99, exclude_bodyparts=exclude_bodyparts, arena_dims=[380],\n",
120
121
122
123
124
    ")"
   ]
  },
  {
   "cell_type": "code",
125
   "execution_count": 7,
126
127
128
129
130
131
132
133
134
135
136
137
138
139
   "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",
140
141
      "CPU times: user 3 s, sys: 161 ms, total: 3.16 s\n",
      "Wall time: 951 ms\n"
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
     ]
    }
   ],
   "source": [
    "%%time\n",
    "proj = proj.run(verbose=True)\n",
    "print(proj)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 2. Load pretrained deepof model"
   ]
  },
  {
   "cell_type": "code",
160
   "execution_count": 8,
161
162
163
   "metadata": {},
   "outputs": [],
   "source": [
164
165
166
167
168
169
    "# Set model parameters\n",
    "encoding = 6\n",
    "loss = \"ELBO\"\n",
    "k = 25\n",
    "pheno = 0\n",
    "predictor = 0"
170
171
172
173
   ]
  },
  {
   "cell_type": "code",
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
   "execution_count": 9,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "['GMVAE_loss=ELBO_encoding=6_k=25_latreg=none_20210312-084005_final_weights.h5',\n",
       " 'GMVAE_loss=ELBO_encoding=6_k=25_latreg=variance_20210312-090508_final_weights.h5',\n",
       " 'GMVAE_loss=ELBO_encoding=6_k=25_latreg=categorical+variance_20210312-085926_final_weights.h5',\n",
       " 'GMVAE_loss=ELBO_encoding=6_k=25_latreg=categorical_20210312-093339_final_weights.h5']"
      ]
     },
     "execution_count": 9,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "[i for i in os.listdir(trained_network) if i.endswith(\"h5\")]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
198
199
200
   "metadata": {},
   "outputs": [],
   "source": [
201
202
203
204
    "coords = proj.get_coords(center=\"Center\", align=\"Spine_1\", align_inplace=True)\n",
    "coords = coords.preprocess(test_videos=0, window_step=1, window_size=11, shuffle=True)[\n",
    "    0\n",
    "]"
205
206
207
208
   ]
  },
  {
   "cell_type": "code",
209
   "execution_count": 11,
210
   "metadata": {},
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
   "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-11-ced14f806c60>\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."
     ]
    }
   ],
226
227
228
229
230
231
232
233
   "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",
234
    ").build(coords.shape)[:4]\n",
235
236
237
238
239
240
241
242
243
244
    "\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",
245
   "execution_count": null,
246
247
248
249
250
251
252
253
254
255
256
257
258
259
   "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",
260
   "execution_count": null,
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
   "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": [
291
    "### 4. Evaluate reconstruction (to be incorporated into deepof.evaluate)"
292
293
294
295
   ]
  },
  {
   "cell_type": "code",
296
   "execution_count": null,
297
298
299
   "metadata": {},
   "outputs": [],
   "source": [
300
301
302
303
304
305
306
307
308
309
310
311
    "# 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",
312
    "            linewidth=2.0,\n",
313
314
315
316
    "        )\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",
317
318
    "            color=\"red\",\n",
    "            linewidth=2.0,\n",
319
320
321
    "        )\n",
    "        plots.append(temp_plot)\n",
    "        rec_plots.append(temp_rec_plot)\n",
322
    "    return plots, rec_plots\n",
323
324
    "\n",
    "\n",
325
    "def update_mouse_graph(x, y, rec_x, rec_y, plots, rec_plots, edges):\n",
326
327
328
329
330
331
    "    \"\"\"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",
332
333
334
335
336
    "        )\n",
    "    for plot, edge in zip(rec_plots, edges):\n",
    "        plot.set_data(\n",
    "            [float(rec_x[edge[0]]), float(rec_x[edge[1]])],\n",
    "            [float(rec_y[edge[0]]), float(rec_y[edge[1]])],\n",
337
338
339
340
341
    "        )"
   ]
  },
  {
   "cell_type": "code",
342
   "execution_count": null,
343
344
345
   "metadata": {
    "scrolled": false
   },
346
   "outputs": [],
347
348
349
   "source": [
    "# Display a video with the original data superimposed with the reconstructions\n",
    "\n",
350
    "coords = proj.get_coords(center=\"Center\", align=\"Spine_1\", align_inplace=True)\n",
351
    "random_exp = np.random.choice(list(coords.keys()), 1)[0]\n",
352
    "print(random_exp)\n",
353
354
    "\n",
    "\n",
355
    "def animate_mice_across_time(random_exp):\n",
356
    "\n",
357
    "    # Define canvas\n",
358
359
    "    fig, ax = plt.subplots(1, 1, figsize=(10, 10))\n",
    "\n",
360
    "    # Retrieve body graph\n",
361
362
363
364
365
366
367
368
369
370
    "    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",
371
372
373
374
375
376
377
378
379
    "    # Compute observed and predicted data to plot\n",
    "    data = coords[random_exp]\n",
    "    coords_rec = coords.filter_videos([random_exp])\n",
    "    data_prep = coords_rec.preprocess(\n",
    "        test_videos=0, window_step=1, window_size=window_size, shuffle=False\n",
    "    )[0]\n",
    "\n",
    "    data_rec = gmvaep.predict(data_prep)\n",
    "    data_rec = pd.DataFrame(coords_rec._scaler.inverse_transform(data_rec[:, 6, :]))\n",
380
    "    data_rec.columns = data.columns\n",
381
382
    "    data = pd.DataFrame(coords_rec._scaler.inverse_transform(data_prep[:, 6, :]))\n",
    "    data.columns = data_rec.columns\n",
383
    "\n",
384
    "    # Add Central coordinate, lost during alignment\n",
385
386
387
388
389
    "    data[\"Center\", \"x\"] = 0\n",
    "    data[\"Center\", \"y\"] = 0\n",
    "    data_rec[\"Center\", \"x\"] = 0\n",
    "    data_rec[\"Center\", \"y\"] = 0\n",
    "\n",
390
    "    # Plot!\n",
391
392
393
394
395
    "    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",
396
397
398
399
400
401
    "    plots, rec_plots = plot_mouse_graph(\n",
    "        init_x, init_y, init_rec_x, init_rec_y, ax, edges\n",
    "    )\n",
    "    scatter = ax.scatter(\n",
    "        x=np.array(init_x), y=np.array(init_y), color=\"#006699\", label=\"Original\"\n",
    "    )\n",
402
    "    rec_scatter = ax.scatter(\n",
403
404
405
406
    "        x=np.array(init_rec_x),\n",
    "        y=np.array(init_rec_y),\n",
    "        color=\"red\",\n",
    "        label=\"Reconstruction\",\n",
407
408
409
410
411
412
413
414
415
    "    )\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",
416
    "\n",
417
    "        scatter.set_offsets(np.c_[np.array(x), np.array(y)])\n",
418
419
    "        rec_scatter.set_offsets(np.c_[np.array(rec_x), np.array(rec_y)])\n",
    "        update_mouse_graph(x, y, rec_x, rec_y, plots, rec_plots, edges)\n",
420
421
422
    "\n",
    "        return scatter\n",
    "\n",
423
    "    animation = FuncAnimation(fig, func=animation_frame, frames=250, interval=75,)\n",
424
    "\n",
425
    "    ax.set_title(\"Original versus reconstructed data\")\n",
426
427
428
429
    "    ax.set_ylim(-100, 60)\n",
    "    ax.set_xlim(-60, 60)\n",
    "    ax.set_xlabel(\"x\")\n",
    "    ax.set_ylabel(\"y\")\n",
430
    "    plt.legend()\n",
431
432
433
434
    "\n",
    "    video = animation.to_html5_video()\n",
    "    html = display.HTML(video)\n",
    "    display.display(html)\n",
435
436
437
438
    "    plt.close()\n",
    "\n",
    "\n",
    "animate_mice_across_time(random_exp)"
439
440
441
442
443
444
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
445
    "### 5. Evaluate latent space (to be incorporated into deepof.evaluate)"
446
447
448
449
   ]
  },
  {
   "cell_type": "code",
450
   "execution_count": null,
451
452
   "metadata": {},
   "outputs": [],
453
454
455
456
457
458
459
460
461
462
   "source": [
    "# Get encodings and groupings for the same random video as above\n",
    "data_prep = coords.preprocess(\n",
    "    test_videos=0, window_step=1, window_size=window_size, shuffle=False\n",
    ")[0]\n",
    "\n",
    "encodings = encoder.predict(data_prep)\n",
    "groupings = grouper.predict(data_prep)\n",
    "hard_groups = np.argmax(groupings, axis=1)"
   ]
463
  },
464
465
  {
   "cell_type": "code",
466
   "execution_count": null,
467
   "metadata": {},
468
   "outputs": [],
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
   "source": [
    "@interact(minimum_confidence=(0.0, 1.0, 0.01))\n",
    "def plot_cluster_confidence(minimum_confidence):\n",
    "    plt.figure(figsize=(12, 8))\n",
    "\n",
    "    groups = hard_groups[np.max(groupings, axis=1) > minimum_confidence].flatten()\n",
    "    groups = np.concatenate([groups, np.arange(25)])\n",
    "    sns.countplot(groups)\n",
    "    plt.xlabel(\"Cluster\")\n",
    "    plt.title(\"Training instances per cluster\")\n",
    "    plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The slider in the figure above lets you set the minimum confidence the model may yield when assigning a training instance to a cluster in order to be visualized."
   ]
  },
  {
   "cell_type": "code",
491
   "execution_count": null,
492
   "metadata": {},
493
   "outputs": [],
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
   "source": [
    "# Plot real data in the latent space\n",
    "\n",
    "\n",
    "@interact(\n",
    "    samples=(1000, 10000, 500),\n",
    "    minimum_confidence=(0.0, 0.99, 0.01),\n",
    "    dim_red=[\"LDA\", \"PCA\", \"umap\", \"tSNE\"],\n",
    ")\n",
    "def plot_cluster_confidence(samples, minimum_confidence, dim_red):\n",
    "    if dim_red == \"umap\":\n",
    "        reducer = umap.UMAP(n_components=2)\n",
    "    elif dim_red == \"LDA\":\n",
    "        reducer = LinearDiscriminantAnalysis(n_components=2)\n",
    "    elif dim_red == \"PCA\":\n",
    "        reducer = PCA(n_components=2)\n",
    "    else:\n",
    "        reducer = TSNE(n_components=2)\n",
    "\n",
    "    encods = encodings[np.max(groupings, axis=1) > minimum_confidence]\n",
    "    groups = groupings[np.max(groupings, axis=1) > minimum_confidence]\n",
    "    hgroups = hard_groups[np.max(groupings, axis=1) > minimum_confidence].flatten()\n",
    "\n",
    "    samples = np.random.choice(range(encods.shape[0]), samples)\n",
    "    sample_enc = encods[samples, :]\n",
    "    sample_grp = groups[samples, :]\n",
    "    sample_hgr = hgroups[samples]\n",
    "\n",
    "    if dim_red != \"LDA\":\n",
    "        enc = reducer.fit_transform(sample_enc)\n",
    "    else:\n",
    "        enc = reducer.fit_transform(sample_enc, sample_hgr)\n",
    "\n",
    "    plt.figure(figsize=(12, 8))\n",
    "\n",
529
530
531
532
533
534
535
536
    "    sns.scatterplot(\n",
    "        x=enc[:, 0],\n",
    "        y=enc[:, 1],\n",
    "        hue=sample_hgr,\n",
    "        size=np.max(sample_grp, axis=1),\n",
    "        sizes=(1, 100),\n",
    "        palette=\"muted\",\n",
    "    )\n",
537
538
    "    plt.xlabel(\"{} 1\".format(dim_red))\n",
    "    plt.ylabel(\"{} 2\".format(dim_red))\n",
539
    "    plt.suptitle(\"Static view of trained latent space\")\n",
540
541
    "    plt.show()"
   ]
542
  },
543
544
545
546
547
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
548
   "source": [
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
    "def plot_mouse_graph(instant_x, instant_y, ax, edges):\n",
    "    \"\"\"Generates a graph plot of the mouse\"\"\"\n",
    "    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",
    "            linewidth=2.0,\n",
    "        )\n",
    "        plots.append(temp_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",
    "        )"
571
   ]
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "scrolled": false
   },
   "outputs": [],
   "source": [
    "# Plot trajectory of a video in latent space\n",
    "\n",
    "\n",
    "@interact(\n",
    "    samples=(1000, 10000, 500),\n",
    "    trajectory=(100, 500),\n",
    "    trace=False,\n",
    "    dim_red=[\"LDA\", \"PCA\", \"umap\", \"tSNE\"],\n",
    ")\n",
    "def plot_cluster_confidence(samples, trajectory, trace, dim_red):\n",
    "    if dim_red == \"umap\":\n",
    "        reducer = umap.UMAP(n_components=2)\n",
    "    elif dim_red == \"LDA\":\n",
    "        reducer = LinearDiscriminantAnalysis(n_components=2)\n",
    "    elif dim_red == \"PCA\":\n",
    "        reducer = PCA(n_components=2)\n",
    "    else:\n",
    "        reducer = TSNE(n_components=2)\n",
    "\n",
    "    sample_enc = encodings[:samples, :]\n",
    "    sample_grp = groupings[:samples, :]\n",
    "    sample_hgr = hard_groups[:samples]\n",
    "\n",
    "    if dim_red != \"LDA\":\n",
    "        enc = reducer.fit_transform(sample_enc)\n",
    "    else:\n",
    "        enc = reducer.fit_transform(sample_enc, sample_hgr)\n",
    "\n",
    "    # Define two figures arranged horizontally\n",
    "    fig, (ax, ax2) = plt.subplots(\n",
    "        1, 2, figsize=(12, 8), gridspec_kw={\"width_ratios\": [3, 1.5]}\n",
    "    )\n",
    "\n",
    "    # Plot the animated embedding trajectory on the left\n",
    "    sns.scatterplot(\n",
    "        x=enc[:, 0],\n",
    "        y=enc[:, 1],\n",
    "        hue=sample_hgr,\n",
    "        size=np.max(sample_grp, axis=1),\n",
    "        sizes=(1, 100),\n",
    "        palette=\"muted\",\n",
    "        ax=ax,\n",
    "    )\n",
    "\n",
    "    traj_init = enc[0, :]\n",
    "    scatter = ax.scatter(\n",
    "        x=[traj_init[0]], y=[traj_init[1]], s=100, color=\"red\", edgecolor=\"black\"\n",
    "    )\n",
    "    (lineplt,) = ax.plot([traj_init[0]], [traj_init[1]], color=\"red\", linewidth=2.0)\n",
    "    tracking_line_x = []\n",
    "    tracking_line_y = []\n",
    "\n",
    "    # Plot the initial data (before feeding it to the encoder) on the right\n",
    "    edges = deepof.utils.connect_mouse_topview()\n",
    "\n",
    "    for bpart in exclude_bodyparts:\n",
    "        if bpart:\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",
    "        if (\"Tail_base\", limb) in list(edges.edges()):\n",
    "            edges.remove_edge(\"Tail_base\", limb)\n",
    "\n",
    "    edges = edges.edges()\n",
    "\n",
    "    inv_coords = coords._scaler.inverse_transform(data_prep)[:, window_size // 2, :]\n",
    "    data = pd.DataFrame(inv_coords, columns=coords[random_exp].columns)\n",
    "\n",
    "    data[\"Center\", \"x\"] = 0\n",
    "    data[\"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",
    "\n",
    "    plots = plot_mouse_graph(init_x, init_y, ax2, edges)\n",
    "    track = ax2.scatter(x=np.array(init_x), y=np.array(init_y), color=\"#006699\",)\n",
    "\n",
    "    # Update data in both plots\n",
    "    def animation_frame(i):\n",
    "        # Update scatter plot\n",
    "        offset = enc[i, :]\n",
    "\n",
    "        prev_t = scatter.get_offsets()[0]\n",
    "\n",
    "        if trace:\n",
    "            tracking_line_x.append([prev_t[0], offset[0]])\n",
    "            tracking_line_y.append([prev_t[1], offset[1]])\n",
    "            lineplt.set_xdata(tracking_line_x)\n",
    "            lineplt.set_ydata(tracking_line_y)\n",
    "\n",
    "        scatter.set_offsets(np.c_[np.array(offset[0]), np.array(offset[1])])\n",
    "        \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",
    "        track.set_offsets(np.c_[np.array(x), np.array(y)])\n",
    "        update_mouse_graph(x, y, plots, edges)\n",
    "\n",
    "        return scatter\n",
    "\n",
    "    animation = FuncAnimation(\n",
    "        fig, func=animation_frame, frames=trajectory, interval=75,\n",
    "    )\n",
    "\n",
    "    ax.set_xlabel(\"{} 1\".format(dim_red))\n",
    "    ax.set_ylabel(\"{} 2\".format(dim_red))\n",
    "\n",
    "    ax2.set_xlabel(\"x\")\n",
    "    ax2.set_xlabel(\"y\")\n",
    "    ax2.set_ylim(-90, 60)\n",
    "    ax2.set_xlim(-60, 60)\n",
    "\n",
    "    plt.tight_layout()\n",
    "\n",
    "    video = animation.to_html5_video()\n",
    "    html = display.HTML(video)\n",
    "    display.display(html)\n",
    "    plt.close()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 6. Sample from latent space (to be incorporated into deepof.evaluate)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
  }
 ],
 "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
}