main.ipynb 11.9 KB
Newer Older
lucas_miranda's avatar
lucas_miranda committed
1
{
2
3
4
 "cells": [
  {
   "cell_type": "code",
5
   "execution_count": null,
6
7
8
9
10
11
12
13
14
15
16
17
   "metadata": {},
   "outputs": [],
   "source": [
    "%load_ext autoreload\n",
    "%autoreload 2\n",
    "\n",
    "import warnings\n",
    "warnings.filterwarnings(\"ignore\")"
   ]
  },
  {
   "cell_type": "code",
18
   "execution_count": null,
19
20
21
22
23
24
25
26
27
28
29
30
31
32
   "metadata": {},
   "outputs": [],
   "source": [
    "#from source.utils import *\n",
    "from source.preprocess import *\n",
    "import pickle\n",
    "import matplotlib.pyplot as plt\n",
    "import pandas as pd\n",
    "from collections import defaultdict\n",
    "from tqdm import tqdm_notebook as tqdm"
   ]
  },
  {
   "cell_type": "code",
33
   "execution_count": null,
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
   "metadata": {
    "tags": [
     "parameters"
    ]
   },
   "outputs": [],
   "source": [
    "path = \"../../Desktop/DLC_social_1/\""
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Set up and design the project"
   ]
  },
  {
   "cell_type": "code",
53
   "execution_count": null,
54
55
56
57
58
59
60
61
62
   "metadata": {},
   "outputs": [],
   "source": [
    "with open('{}DLC_social_1_exp_conditions.pickle'.format(path), 'rb') as handle:\n",
    "    Treatment_dict = pickle.load(handle)"
   ]
  },
  {
   "cell_type": "code",
63
   "execution_count": null,
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
   "metadata": {},
   "outputs": [],
   "source": [
    "#Which angles to compute?\n",
    "bp_dict = {'B_Nose':['B_Left_ear','B_Right_ear'],\n",
    "          'B_Left_ear':['B_Nose','B_Right_ear','B_Center','B_Left_flank'],\n",
    "          'B_Right_ear':['B_Nose','B_Left_ear','B_Center','B_Right_flank'],\n",
    "          'B_Center':['B_Left_ear','B_Right_ear','B_Left_flank','B_Right_flank','B_Tail_base'],\n",
    "          'B_Left_flank':['B_Left_ear','B_Center','B_Tail_base'],\n",
    "          'B_Right_flank':['B_Right_ear','B_Center','B_Tail_base'],\n",
    "          'B_Tail_base':['B_Center','B_Left_flank','B_Right_flank']}"
   ]
  },
  {
   "cell_type": "code",
79
   "execution_count": null,
80
   "metadata": {},
81
   "outputs": [],
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
   "source": [
    "%%time\n",
    "DLC_social_1 = project(path=path,#Path where to find the required files\n",
    "                   smooth_alpha=0.85,                    #Alpha value for exponentially weighted smoothing\n",
    "                   distances=['B_Center','B_Nose','B_Left_ear','B_Right_ear','B_Left_flank',\n",
    "                              'B_Right_flank','B_Tail_base'],\n",
    "                   ego=False,\n",
    "                   angles=True,\n",
    "                   connectivity=bp_dict,\n",
    "                   arena='circular',                  #Type of arena used in the experiments\n",
    "                   arena_dims=[380],                  #Dimensions of the arena. Just one if it's circular\n",
    "                   video_format='.mp4',\n",
    "                   table_format='.h5',\n",
    "                   exp_conditions=Treatment_dict)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Run project"
   ]
  },
  {
   "cell_type": "code",
107
108
109
   "execution_count": null,
   "metadata": {},
   "outputs": [],
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
   "source": [
    "%%time\n",
    "DLC_social_1_coords = DLC_social_1.run(verbose=True)\n",
    "print(DLC_social_1_coords)\n",
    "type(DLC_social_1_coords)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Generate coords"
   ]
  },
  {
   "cell_type": "code",
126
   "execution_count": null,
127
128
129
   "metadata": {
    "scrolled": true
   },
130
   "outputs": [],
131
132
133
134
135
136
137
138
   "source": [
    "%%time\n",
    "ptest = DLC_social_1_coords.get_coords(center=True, polar=False, speed=0, length='00:10:00')\n",
    "ptest._type"
   ]
  },
  {
   "cell_type": "code",
139
   "execution_count": null,
140
   "metadata": {},
141
   "outputs": [],
142
143
144
145
146
147
148
149
   "source": [
    "%%time\n",
    "dtest = DLC_social_1_coords.get_distances(speed=0, length='00:10:00')\n",
    "dtest._type"
   ]
  },
  {
   "cell_type": "code",
150
   "execution_count": null,
151
   "metadata": {},
152
   "outputs": [],
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
   "source": [
    "%%time\n",
    "atest = DLC_social_1_coords.get_angles(degrees=True, speed=0, length='00:10:00')\n",
    "atest._type"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Visualization playground"
   ]
  },
  {
   "cell_type": "code",
168
   "execution_count": null,
169
170
171
172
173
174
175
176
   "metadata": {},
   "outputs": [],
   "source": [
    "#ptest.plot_heatmaps(['B_Center', 'W_Center'], i=1)"
   ]
  },
  {
   "cell_type": "code",
177
   "execution_count": null,
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
   "metadata": {},
   "outputs": [],
   "source": [
    "#Plot animation of trajectory over time with different smoothings\n",
    "#plt.plot(ptest['Day2Test13DLC']['B_Center'].iloc[:5000]['x'],\n",
    "#         ptest['Day2Test13DLC']['B_Center'].iloc[:5000]['y'], label='alpha=0.85')\n",
    "\n",
    "#plt.xlabel('x')\n",
    "#plt.ylabel('y')\n",
    "#plt.title('Mouse Center Trajectory using different exponential smoothings')\n",
    "#plt.legend()\n",
    "#plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Dimensionality reduction playground"
   ]
  },
  {
   "cell_type": "code",
201
   "execution_count": null,
202
203
204
205
206
207
208
209
   "metadata": {},
   "outputs": [],
   "source": [
    "#pca = ptest.pca(4, 1000)"
   ]
  },
  {
   "cell_type": "code",
210
   "execution_count": null,
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
   "metadata": {},
   "outputs": [],
   "source": [
    "#plt.scatter(*pca[0].T)\n",
    "#plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Preprocessing playground"
   ]
  },
  {
   "cell_type": "code",
227
   "execution_count": null,
228
229
230
231
232
233
234
235
236
237
   "metadata": {},
   "outputs": [],
   "source": [
    "mtest = merge_tables(DLC_social_1_coords.get_coords(center=True, polar=True, length='00:10:00'))#,\n",
    "#                      DLC_social_1_coords.get_distances(speed=0, length='00:10:00'),\n",
    "#                      DLC_social_1_coords.get_angles(degrees=True, speed=0, length='00:10:00'))"
   ]
  },
  {
   "cell_type": "code",
238
   "execution_count": null,
239
240
241
242
243
244
245
246
   "metadata": {},
   "outputs": [],
   "source": [
    "#pptest = mtest.preprocess(window_size=51, filter='gaussian', sigma=10, shift=20)"
   ]
  },
  {
   "cell_type": "code",
247
   "execution_count": null,
248
   "metadata": {},
249
   "outputs": [],
250
251
252
253
254
255
256
   "source": [
    "pttest = mtest.preprocess(window_size=11, window_step=6, filter=None, standard_scaler=True)\n",
    "pttest.shape"
   ]
  },
  {
   "cell_type": "code",
257
   "execution_count": null,
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
   "metadata": {},
   "outputs": [],
   "source": [
    "#plt.plot(pttest[2,:,2], label='normal')\n",
    "#plt.plot(pptest[2,:,2], label='gaussian')\n",
    "#plt.legend()\n",
    "#plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Trained models playground"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Seq 2 seq Variational Auto Encoder"
   ]
  },
  {
   "cell_type": "code",
283
   "execution_count": null,
284
   "metadata": {},
285
   "outputs": [],
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
   "source": [
    "from datetime import datetime\n",
    "from tensorflow.keras import Input, Model, Sequential\n",
    "from tensorflow.keras.constraints import UnitNorm\n",
    "from tensorflow.keras.layers import Bidirectional, Dense, Dropout\n",
    "from tensorflow.keras.layers import Lambda, LSTM\n",
    "from tensorflow.keras.layers import RepeatVector, TimeDistributed\n",
    "from tensorflow.keras.losses import Huber\n",
    "from tensorflow.keras.optimizers import Adam\n",
    "from source.model_utils import *\n",
    "import keras as k\n",
    "import tensorflow as tf"
   ]
  },
  {
   "cell_type": "code",
302
   "execution_count": null,
303
304
305
   "metadata": {},
   "outputs": [],
   "source": [
306
    "NAME = 'Baseline_VAE_short_512_10=warmup_begin'\n",
307
308
309
310
311
312
313
314
    "log_dir = os.path.abspath(\n",
    "    \"logs/fit/{}_{}\".format(NAME, datetime.now().strftime(\"%Y%m%d-%H%M%S\"))\n",
    ")\n",
    "tensorboard_callback = k.callbacks.TensorBoard(log_dir=log_dir, histogram_freq=1)"
   ]
  },
  {
   "cell_type": "code",
315
   "execution_count": null,
316
317
318
319
320
321
322
323
   "metadata": {},
   "outputs": [],
   "source": [
    "from source.models import SEQ_2_SEQ_AE, SEQ_2_SEQ_VAE, SEQ_2_SEQ_VAEP"
   ]
  },
  {
   "cell_type": "code",
324
   "execution_count": null,
325
326
327
328
329
330
331
332
   "metadata": {},
   "outputs": [],
   "source": [
    "encoder, decoder, ae = SEQ_2_SEQ_AE(pttest.shape).build()"
   ]
  },
  {
   "cell_type": "code",
333
   "execution_count": null,
334
335
336
   "metadata": {},
   "outputs": [],
   "source": [
337
338
339
340
341
    "def kl_rate(y_true, y_pred):\n",
    "    return 0\n",
    "\n",
    "def mmd_rate(y_true, y_pred):\n",
    "    return 0"
342
343
344
345
   ]
  },
  {
   "cell_type": "code",
346
   "execution_count": null,
347
348
349
   "metadata": {},
   "outputs": [],
   "source": [
350
351
352
353
    "encoder, generator, vae, kl_warmup_callback, mmd_warmup_callback = SEQ_2_SEQ_VAE(pttest.shape,\n",
    "                                                                   loss='ELBO+MMD',\n",
    "                                                                   kl_warmup_epochs=10,\n",
    "                                                                   mmd_warmup_epochs=10).build()"
354
355
356
357
   ]
  },
  {
   "cell_type": "code",
358
   "execution_count": null,
359
360
361
362
363
364
365
366
367
368
369
   "metadata": {},
   "outputs": [],
   "source": [
    "encoder, generator, vaep, kl_warmup_callback, mmd_warmup_callback = SEQ_2_SEQ_VAEP(pttest.shape,\n",
    "                                                                    loss='ELBO+MMD',\n",
    "                                                                    kl_warmup_epochs=10,\n",
    "                                                                    mmd_warmup_epochs=10).build()"
   ]
  },
  {
   "cell_type": "code",
370
   "execution_count": null,
371
372
373
374
375
376
377
378
379
380
   "metadata": {},
   "outputs": [],
   "source": [
    "#ae.summary()\n",
    "#vae.summary()\n",
    "#vaep.summary()"
   ]
  },
  {
   "cell_type": "code",
381
   "execution_count": null,
382
383
384
385
386
387
388
389
390
391
392
   "metadata": {
    "scrolled": false
   },
   "outputs": [],
   "source": [
    "#from tensorflow.keras.utils import plot_model\n",
    "#plot_model(vaep, show_shapes=True)"
   ]
  },
  {
   "cell_type": "code",
393
   "execution_count": null,
394
395
396
397
398
399
400
401
402
403
   "metadata": {
    "scrolled": false
   },
   "outputs": [],
   "source": [
    "#plot_model(vae)"
   ]
  },
  {
   "cell_type": "code",
404
   "execution_count": null,
405
406
407
408
409
   "metadata": {},
   "outputs": [],
   "source": [
    "#np.random.shuffle(pttest)\n",
    "pttrain = pttest[:-15000]\n",
410
    "pttest  = pttest[-15000:]"
411
412
413
414
   ]
  },
  {
   "cell_type": "code",
415
   "execution_count": null,
416
417
418
   "metadata": {},
   "outputs": [],
   "source": [
419
420
    "#lr_schedule = tf.keras.callbacks.LearningRateScheduler(\n",
    "#    lambda epoch: 1e-3 * 10**(epoch / 20))"
421
422
423
424
   ]
  },
  {
   "cell_type": "code",
425
   "execution_count": null,
426
   "metadata": {},
427
   "outputs": [],
428
429
   "source": [
    "#tf.config.experimental_run_functions_eagerly(False)\n",
430
431
432
    "history = vae.fit(x=pttrain[:-1], y=pttrain[:-1], epochs=100, batch_size=512, verbose=1,\n",
    "                  validation_data=(pttest[:-1], pttest[:-1]),\n",
    "                  callbacks=[tensorboard_callback, kl_warmup_callback, mmd_warmup_callback])"
433
434
435
436
   ]
  },
  {
   "cell_type": "code",
437
   "execution_count": null,
438
439
440
   "metadata": {
    "scrolled": true
   },
441
   "outputs": [],
442
443
   "source": [
    "#tf.config.experimental_run_functions_eagerly(False)\n",
444
445
446
    "#history = vaep.fit(x=pttrain[:-1], y=[pttrain[:-1],pttrain[1:]], epochs=100, batch_size=512, verbose=1,\n",
    "#                   validation_data=(pttest[:-1], [pttest[:-1],pttest[1:]]),\n",
    "#                   callbacks=[tensorboard_callback, kl_warmup_callback, mmd_warmup_callback])"
447
   ]
448
449
450
451
452
453
454
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
  }
 ],
 "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
lucas_miranda's avatar
lucas_miranda committed
478
}