├── .gitignore
├── .idea
├── misc.xml
├── modules.xml
├── vcs.xml
├── visual-interaction-networks-pytorch.iml
└── workspace.xml
├── LICENSE
├── README.md
├── config.py
├── figures
├── 1.gif
└── 2.png
├── logger.py
├── model.py
├── train.py
├── utils.py
├── vin.py
└── vin_dataset.py
/.gitignore:
--------------------------------------------------------------------------------
1 | # Byte-compiled / optimized / DLL files
2 | __pycache__/
3 | *.py[cod]
4 | *$py.class
5 |
6 | # C extensions
7 | *.so
8 |
9 | # Distribution / packaging
10 | .Python
11 | env/
12 | build/
13 | develop-eggs/
14 | dist/
15 | downloads/
16 | eggs/
17 | .eggs/
18 | lib/
19 | lib64/
20 | parts/
21 | sdist/
22 | var/
23 | wheels/
24 | *.egg-info/
25 | .installed.cfg
26 | *.egg
27 |
28 | # PyInstaller
29 | # Usually these files are written by a python script from a template
30 | # before PyInstaller builds the exe, so as to inject date/other infos into it.
31 | *.manifest
32 | *.spec
33 |
34 | # Installer logs
35 | pip-log.txt
36 | pip-delete-this-directory.txt
37 |
38 | # Unit test / coverage reports
39 | htmlcov/
40 | .tox/
41 | .coverage
42 | .coverage.*
43 | .cache
44 | nosetests.xml
45 | coverage.xml
46 | *.cover
47 | .hypothesis/
48 |
49 | # Translations
50 | *.mo
51 | *.pot
52 |
53 | # Django stuff:
54 | *.log
55 | local_settings.py
56 |
57 | # Flask stuff:
58 | instance/
59 | .webassets-cache
60 |
61 | # Scrapy stuff:
62 | .scrapy
63 |
64 | # Sphinx documentation
65 | docs/_build/
66 |
67 | # PyBuilder
68 | target/
69 |
70 | # Jupyter Notebook
71 | .ipynb_checkpoints
72 |
73 | # pyenv
74 | .python-version
75 |
76 | # celery beat schedule file
77 | celerybeat-schedule
78 |
79 | # SageMath parsed files
80 | *.sage.py
81 |
82 | # dotenv
83 | .env
84 |
85 | # virtualenv
86 | .venv
87 | venv/
88 | ENV/
89 |
90 | # Spyder project settings
91 | .spyderproject
92 | .spyproject
93 |
94 | # Rope project settings
95 | .ropeproject
96 |
97 | # mkdocs documentation
98 | /site
99 |
100 | # mypy
101 | .mypy_cache/
102 | /vin/
103 | /checkpoint/
104 | /log/
105 |
--------------------------------------------------------------------------------
/.idea/misc.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | ApexVCS
5 |
6 |
7 |
8 |
9 |
10 |
--------------------------------------------------------------------------------
/.idea/modules.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
--------------------------------------------------------------------------------
/.idea/vcs.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/.idea/visual-interaction-networks-pytorch.iml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
--------------------------------------------------------------------------------
/.idea/workspace.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
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 |
62 |
63 |
64 |
65 | h1
66 | floa
67 | df
68 | prin
69 | tensorflo
70 | ToTensor
71 | roll_num
72 |
73 |
74 | $PROJECT_DIR$
75 |
76 |
77 |
78 |
79 |
80 |
81 |
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 |
107 | Python
108 |
109 |
110 |
111 |
112 | PyCompatibilityInspection
113 |
114 |
115 |
116 |
117 |
118 |
119 |
120 |
121 |
122 |
123 |
124 |
125 |
126 |
127 |
128 |
129 |
130 |
131 |
132 |
133 |
134 |
135 |
136 |
137 |
138 |
139 |
140 |
141 |
142 |
143 |
144 |
145 |
146 |
147 |
148 |
149 |
150 |
151 |
152 |
153 |
154 |
155 |
156 |
157 |
158 |
159 |
160 |
161 |
162 |
163 |
164 |
165 |
166 |
167 |
168 |
169 |
170 |
171 |
172 |
173 |
174 |
175 |
176 |
177 |
178 |
179 |
180 |
181 |
182 |
183 |
184 |
185 |
186 |
187 |
188 |
189 |
190 |
191 |
192 |
193 |
194 |
195 |
196 |
197 |
198 |
199 |
200 |
201 |
202 |
203 |
204 |
205 |
206 |
207 |
208 |
209 |
210 |
211 |
212 |
213 |
214 |
215 |
216 |
217 |
218 |
219 |
220 |
221 |
222 |
223 |
224 |
225 |
226 |
227 |
228 |
229 |
230 |
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 | 1507892075184
266 |
267 |
268 | 1507892075184
269 |
270 |
271 | 1508032485281
272 |
273 |
274 |
275 | 1508032485281
276 |
277 |
278 | 1508103493397
279 |
280 |
281 |
282 | 1508103493397
283 |
284 |
285 | 1508627356892
286 |
287 |
288 |
289 | 1508627356893
290 |
291 |
292 | 1508627404110
293 |
294 |
295 |
296 | 1508627404110
297 |
298 |
299 | 1517451718479
300 |
301 |
302 |
303 | 1517451718479
304 |
305 |
306 | 1517451863831
307 |
308 |
309 |
310 | 1517451863831
311 |
312 |
313 | 1517452097316
314 |
315 |
316 |
317 | 1517452097316
318 |
319 |
320 | 1517578336046
321 |
322 |
323 |
324 | 1517578336046
325 |
326 |
327 | 1517578504638
328 |
329 |
330 |
331 | 1517578504638
332 |
333 |
334 | 1517579627185
335 |
336 |
337 |
338 | 1517579627185
339 |
340 |
341 | 1517580467254
342 |
343 |
344 |
345 | 1517580467254
346 |
347 |
348 | 1517580531371
349 |
350 |
351 |
352 | 1517580531371
353 |
354 |
355 | 1517581131236
356 |
357 |
358 |
359 | 1517581131236
360 |
361 |
362 | 1517581264349
363 |
364 |
365 |
366 | 1517581264349
367 |
368 |
369 | 1517581563420
370 |
371 |
372 |
373 | 1517581563420
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 | file://$PROJECT_DIR$/vin_dataset.py
436 | 153
437 |
438 |
439 |
440 |
441 |
442 |
443 |
444 |
445 |
446 |
447 |
448 |
449 |
450 |
451 |
452 |
453 |
454 |
455 |
456 |
457 |
458 |
459 |
460 |
461 |
462 |
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 |
493 |
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 |
529 |
530 |
531 |
532 |
533 |
534 |
535 |
536 |
537 |
538 |
539 |
540 |
541 |
542 |
543 |
544 |
545 |
546 |
547 |
548 |
549 |
550 |
551 |
552 |
553 |
554 |
555 |
556 |
557 |
558 |
559 |
560 |
561 |
562 |
563 |
564 |
565 |
566 |
567 |
568 |
569 |
570 |
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 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2017 Mahmoud Gemy
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
22 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Visual-Interaction-Networks
2 | An implementation of Deepmind visual interaction networks in Pytorch.
3 | # Introduction
4 | > For the purpose of understanding the challenge of relational reasoning. they publised VIN that involves predicting the future in a physical scene. From just a glance, humans can infer not only what objects are where, but also what will happen to them over the upcoming seconds, minutes and even longer in some cases. For example, if you kick a football against a wall, your brain predicts what will happen when the ball hits the wall and how their movements will be affected afterwards (the ball will ricochet at a speed proportional to the kick and - in most cases - the wall will remain where it is).
5 |
6 |
7 |
8 |

9 |
10 |
11 |
12 | ## Architecture
13 |
14 |

15 |
16 |
17 |
18 | ### Data
19 | I used [I@jaesik817](https://github.com/jaesik817/Interaction-networks_tensorflow) physics engine to generate the data.
20 |
21 | Just run the `physics_engine.py`
22 |
23 |
24 | ## Usage
25 | ### Main Dependencies
26 | ```
27 | Python 3.5
28 | pytorch 0.3
29 | numpy 1.13.1
30 | ```
31 |
32 | ### RUN
33 | - Edit configration file to meet your need.
34 | - Run `vin.py`
35 |
36 | ### References
37 | * https://github.com/jaesik817/visual-interaction-networks_tensorflow
38 |
--------------------------------------------------------------------------------
/config.py:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 | class VinConfig():
9 | No = 3 # the number of object
10 | img_folder = "./vin/img/" # image folder
11 | data_folder = "./vin/data/" # data folder
12 | frame_num = 50 # The Number of Saved Frame per each simul
13 | frame_step = 1 # The difference between saved frames
14 | roll_num = 20 # The Number of Rollout
15 | set_num = 10 # The Number of set
16 | weight=32
17 | height=32
18 | col_dim=4
19 | batch_size=4
20 | checkpoint_dir="./checkpoint/"
21 | load=False
22 | log_dir="./log"
--------------------------------------------------------------------------------
/figures/1.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/MrGemy95/visual-interaction-networks-pytorch/27ae3ffd0c68643d61a6dda9235c80b5c20165ac/figures/1.gif
--------------------------------------------------------------------------------
/figures/2.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/MrGemy95/visual-interaction-networks-pytorch/27ae3ffd0c68643d61a6dda9235c80b5c20165ac/figures/2.png
--------------------------------------------------------------------------------
/logger.py:
--------------------------------------------------------------------------------
1 | # Code referenced from https://gist.github.com/gyglim/1f8dfb1b5c82627ae3efcfbbadb9f514
2 |
3 | import numpy as np
4 | import scipy.misc
5 | import os
6 | import tensorflow as tf
7 | try:
8 | from StringIO import StringIO
9 | except ImportError:
10 | from io import BytesIO
11 |
12 |
13 | class Logger(object):
14 | def __init__(self, log_dir):
15 | import tensorflow as tf
16 |
17 | self.summary_writer = tf.summary.FileWriter(log_dir)
18 | self.summary_ops = {}
19 |
20 | def graph_summary(self, graph):
21 | self.summary_writer.add_graph(graph)
22 | self.summary_writer.flush()
23 |
24 | def scalar_summary(self, tag, value, step, scope):
25 | summary = tf.Summary(value=[tf.Summary.Value(tag=os.path.join(scope, tag), simple_value=value)])
26 | self.summary_writer.add_summary(summary, step)
27 | self.summary_writer.flush()
28 |
29 | def image_summary(self, tag, images, step, scope, max_output=4, random_summarization=False):
30 | """Log a list of images."""
31 | assert len(images.shape) == 4, "the input image shape should be in form [batch,hight,width,channels]"
32 | img_summaries = []
33 | if random_summarization:
34 | idxs = np.random.choice(images.shape[0], min(max_output, images.shape[0]))
35 | images = images[idxs]
36 | else:
37 | images = images[:max_output]
38 | if images.shape[-1]==1:
39 | images=np.squeeze(images)
40 | for i in range(images.shape[0]):
41 | img=images[i]
42 | try:
43 | s = StringIO()
44 | except:
45 | s = BytesIO()
46 | scipy.misc.toimage(img).save(s, format="png")
47 |
48 | # Create an Image object
49 | img_sum = tf.Summary.Image(encoded_image_string=s.getvalue(),
50 | height=img.shape[0],
51 | width=img.shape[1])
52 | # Create a Summary value
53 | img_summaries.append(tf.Summary.Value(tag=os.path.join(scope, '%s/%d' % (tag, i)), image=img_sum))
54 |
55 | # Create and write Summary
56 | summary = tf.Summary(value=img_summaries)
57 | self.summary_writer.add_summary(summary, step)
58 | self.summary_writer.flush()
59 |
60 | def histo_summary(self, tag, values, step, scope, bins=1000, ):
61 | """Log a histogram of the tensor of values."""
62 | counts, bin_edges = np.histogram(values, bins=bins)
63 | # Fill the fields of the histogram proto
64 | hist = tf.HistogramProto()
65 | hist.min = float(np.min(values))
66 | hist.max = float(np.max(values))
67 | hist.num = int(np.prod(values.shape))
68 | hist.sum = float(np.sum(values))
69 | hist.sum_squares = float(np.sum(values ** 2))
70 |
71 | # Drop the start of the first bin
72 | bin_edges = bin_edges[1:]
73 |
74 | # Add bin edges and counts
75 | for edge in bin_edges:
76 | hist.bucket_limit.append(edge)
77 | for c in counts:
78 | hist.bucket.append(c)
79 |
80 | # Create and write Summary
81 | summary = tf.Summary(value=[tf.Summary.Value(tag=os.path.join(scope, tag), histo=hist)])
82 | self.summary_writer.add_summary(summary, step)
83 | self.summary_writer.flush()
84 |
85 | # summarize tenorflow tenosrs or images or merged summary, but this requires tensorflow session run
86 | def summarize(self, sess, step, scope='train', summaries_dict=None, summaries_merged=None):
87 | """
88 | Add the summaries to tensorboard
89 | :param step:
90 | :param summaries_dict:
91 | :param summaries_merged:
92 | :return:
93 | """
94 | with tf.variable_scope(scope):
95 | if summaries_dict is not None:
96 | summary_list = []
97 | for tag, value in summaries_dict.items():
98 | if tag not in self.summary_ops:
99 | self.summary_placeholders[tag] = tf.placeholder('float32', value.shape, name=tag)
100 | if len(value.shape) <= 1:
101 | self.summary_ops[tag] = tf.summary.scalar(tag, self.summary_placeholders[tag])
102 | else:
103 | self.summary_ops[tag] = tf.summary.image(tag, self.summary_placeholders[tag])
104 |
105 | summary_list.append(sess.run(self.summary_ops[tag], {self.summary_placeholders[tag]: value}))
106 |
107 | for summary in summary_list:
108 | self.summary_writer.add_summary(summary, step)
109 | if summaries_merged is not None:
110 | self.summary_writer.add_summary(summaries_merged, step)
111 | self.summary_writer.flush()
--------------------------------------------------------------------------------
/model.py:
--------------------------------------------------------------------------------
1 | from __future__ import print_function
2 |
3 | import torch
4 | from torch.autograd import Variable
5 | import torch.nn as nn
6 | import torch.nn.functional as F
7 |
8 | class Net(nn.Module):
9 | def __init__(self, config):
10 | super(Net, self).__init__()
11 | self.config = config
12 | self.pool = nn.MaxPool2d(2, 2)
13 |
14 | # visual encoder modules
15 | self.conv1 = nn.Conv2d(10, 128, 3, padding=1)
16 | self.conv2 = nn.Conv2d(128, 128, 3, padding=1)
17 | self.conv3 = nn.Conv2d(128, 128, 3, padding=1)
18 | self.conv4 = nn.Conv2d(128, 128, 3, padding=1)
19 | self.conv5 = nn.Conv2d(128, 128, 3, padding=1)
20 | # shared linear layer to convert the tensors to shape N_obj*64
21 | self.fc1 = nn.Linear(128, 3 * 64)
22 | # shared MLP layer to output the encoded state code N_obj*64
23 | self.fc2 = nn.Linear(64 * 2, 64)
24 | self.fc3 = nn.Linear(64, 64)
25 | self.fc4 = nn.Linear(64, 64)
26 | # end of visual encoder
27 |
28 | # dynamic predictor modules
29 | self.self_cores = {}
30 | for i in range(3):
31 | self.self_cores[i] = []
32 | self.self_cores[i].append(nn.Linear(64, 64).double().cuda())
33 | self.self_cores[i].append(nn.Linear(64, 64).double().cuda())
34 | self.rel_cores = {}
35 | for i in range(3):
36 | self.rel_cores[i] = []
37 | self.rel_cores[i].append(nn.Linear(64 * 2, 64).double().cuda())
38 | self.rel_cores[i].append(nn.Linear(64, 64).double().cuda())
39 | self.rel_cores[i].append(nn.Linear(64, 64).double().cuda())
40 |
41 | self.affector = {}
42 | for i in range(3):
43 | self.affector[i] = []
44 | self.affector[i].append(nn.Linear(64, 64).double().cuda())
45 | self.affector[i].append(nn.Linear(64, 64).double().cuda())
46 | self.affector[i].append(nn.Linear(64, 64).double().cuda())
47 | self.out = {}
48 | for i in range(3):
49 | self.out[i] = []
50 | self.out[i].append(nn.Linear(64 + 64, 64).double().cuda())
51 | self.out[i].append(nn.Linear(64, 64).double().cuda())
52 | self.aggregator1 = nn.Linear(64 * 3, 64)
53 | self.aggregator2 = nn.Linear(64, 64)
54 | self.state_decoder = nn.Linear(64, 4)
55 |
56 | def core(self, s, core_idx):
57 | objects = torch.chunk(s, 3, 1)
58 |
59 | s_reshaped = s.view(-1, 64)
60 | self_sd_h1 = F.relu(self.self_cores[core_idx][0](s_reshaped))
61 | self_sd_h2 = self.self_cores[core_idx][1](self_sd_h1) + self_sd_h1
62 | self_dynamic = self_sd_h2.view(-1, 3, 64)
63 |
64 | rel_combination = []
65 | for i in range(6):
66 | row_idx = int(i / (2));
67 | col_idx = int(i % (2));
68 | rel_combination.append(torch.cat([objects[row_idx], objects[col_idx]], 1))
69 | rel_combination = torch.cat(rel_combination)
70 | rel_combination=rel_combination.view(-1,64*2)
71 | rel_sd_h1 = F.relu(self.rel_cores[core_idx][0](rel_combination))
72 | rel_sd_h2 = F.relu(self.rel_cores[core_idx][1](rel_sd_h1) + rel_sd_h1)
73 | rel_sd_h3 = self.rel_cores[core_idx][2](rel_sd_h2) + rel_sd_h2
74 | rel_objects = torch.chunk(rel_sd_h3, 6)
75 | obj1 = rel_objects[0] + rel_objects[1]
76 | obj2 = rel_objects[2] + rel_objects[3]
77 | obj3 = rel_objects[4] + rel_objects[5]
78 | rel_dynamic = torch.stack([obj1, obj2, obj3], 1)
79 | dynamic_pred = self_dynamic + rel_dynamic
80 | dynamic_pred = dynamic_pred.view(-1, 64)
81 | aff1 = F.relu(self.affector[core_idx][0](dynamic_pred))
82 | aff2 = F.relu(self.affector[core_idx][1](aff1) + aff1)
83 | aff3 = self.affector[core_idx][2](aff2) + aff2
84 | aff3 = aff3.view(-1, 3, 64)
85 | aff_s = torch.cat([aff3, s], 2)
86 | aff_s = aff_s.view(-1, 64 + 64)
87 |
88 | out1 = F.relu(self.out[core_idx][0](aff_s))
89 | out2 = self.out[core_idx][1](out1) + out1
90 | out2 = out2.view(-1, 3, 64)
91 |
92 | return out2
93 |
94 | def forward(self, x, x_cor, y_cor):
95 | f1, f2, f3, f4, f5, f6 = torch.chunk(x, 6,1)
96 | f1, f2, f3, f4, f5, f6=f1.squeeze(), f2.squeeze(), f3.squeeze(), f4.squeeze(), f5.squeeze(), f6.squeeze()
97 | f1f2 = torch.cat([f1, f2], 1)
98 | f2f3 = torch.cat([f2, f3], 1)
99 | f3f4 = torch.cat([f3, f4], 1)
100 | f4f5 = torch.cat([f4, f5], 1)
101 | f5f6 = torch.cat([f5, f6], 1)
102 |
103 | pairs = torch.cat([f1f2, f2f3, f3f4, f4f5, f5f6])
104 | pairs = torch.cat([pairs, x_cor, y_cor], dim=1)
105 | ve_h1 = F.relu(self.conv1(pairs))
106 | ve_h1 = self.pool(ve_h1)
107 | ve_h2 = F.relu(self.conv2(ve_h1) + ve_h1)
108 | ve_h2 = self.pool(ve_h2)
109 | ve_h3 = F.relu(self.conv3(ve_h2) + ve_h2)
110 | ve_h3 = self.pool(ve_h3)
111 | ve_h4 = F.relu(self.conv4(ve_h3) + ve_h3)
112 | ve_h4 = self.pool(ve_h4)
113 | ve_h5 = F.relu(self.conv5(ve_h4) + ve_h4)
114 | ve_h5 = self.pool(ve_h5)
115 | unit_pairs = ve_h5.view(-1, 128)
116 | # p1,p2,p3,p4,p5=torch.chunk(unit_pairs, 5)
117 | encoded_pairs = self.fc1(unit_pairs)
118 | p1, p2, p3, p4, p5 = torch.chunk(encoded_pairs, 5)
119 | p1 = p1.view(-1, 3, 64)
120 | p2 = p2.view(-1, 3, 64)
121 | p3 = p3.view(-1, 3, 64)
122 | p4 = p4.view(-1, 3, 64)
123 | p5 = p5.view(-1, 3, 64)
124 |
125 | pair1 = torch.cat([p1, p2], 2)
126 | pair2 = torch.cat([p2, p3], 2)
127 | pair3 = torch.cat([p3, p4], 2)
128 | pair4 = torch.cat([p4, p5], 2)
129 |
130 | diff_pairs = torch.cat([pair1, pair2, pair3, pair4])
131 | diff_pairs = diff_pairs.view(-1, 64 * 2)
132 | shared_h1 = F.relu(self.fc2(diff_pairs))
133 | shared_h2 = F.relu(self.fc3(shared_h1) + shared_h1)
134 | shared_h3 = self.fc4(shared_h2) + shared_h2
135 | state_codes = shared_h3.view(-1, 3, 64)
136 | s1, s2, s3, s4 = torch.chunk(state_codes, 4)
137 | rolls = []
138 | for i in range(20):
139 | c1 = self.core(s1, 0)
140 | c2 = self.core(s2, 1)
141 | c3 = self.core(s3, 2)
142 | all_c = torch.cat([c1, c2, c3], 2)
143 | all_c = all_c.view(-1, 64 * 3)
144 | aggregator1 = F.relu(self.aggregator1(all_c))
145 | aggregator2 = self.aggregator2(aggregator1)
146 | aggregator2 = aggregator2.view(-1, 3, 64)
147 | rolls.append(aggregator2)
148 | s1, s2, s3, s4 = s2, s3, s4, aggregator2
149 | rollouts=torch.stack(rolls)
150 | rollouts=rollouts.view(80,3,64)
151 | rollouts=torch.cat([s1,s2,s3,s4,rollouts])
152 | rollouts=rollouts.view(-1,64)
153 | state_decoder=self.state_decoder(rollouts)
154 | state_decoder=state_decoder.view(-1,3,4)
155 | aux_out=state_decoder[:4*4]
156 | aux_out=aux_out.view(4,4,3,4)
157 |
158 |
159 |
160 | net_out=state_decoder[4*4:]
161 | net_out=net_out.view(-1,20,3,4)
162 | net_out2=torch.chunk(net_out, 20,1)
163 |
164 | net_out2=net_out2[:8]
165 | return net_out2,aux_out,net_out
166 |
167 |
168 | def num_flat_features(self, x):
169 | size = x.size()[1:] # all dimensions except the batch dimension
170 | num_features = 1
171 | for s in size:
172 | num_features *= s
173 | return num_features
174 |
--------------------------------------------------------------------------------
/train.py:
--------------------------------------------------------------------------------
1 | from vin_dataset import VinDataset, VinTestDataset, ToTensor, ToTensorV2
2 | from torchvision import transforms, datasets
3 | from torch.utils.data import DataLoader
4 | from torch.autograd import Variable
5 | import torch.optim as optim
6 | from torch import nn
7 | import numpy as np
8 | import torch
9 | from logger import Logger
10 | from utils import create_dir
11 | import os
12 | from utils import make_image2
13 |
14 |
15 | class Trainer():
16 | def __init__(self, config, net):
17 | self.net = net
18 | self.config = config
19 | create_dir(self.config.checkpoint_dir)
20 |
21 | dataset = VinDataset(self.config, transform=ToTensor())
22 | test_dataset = VinTestDataset(self.config, transform=ToTensorV2())
23 | self.dataloader = DataLoader(dataset, batch_size=self.config.batch_size,
24 | shuffle=True, num_workers=4)
25 | self.test_dataloader = DataLoader(test_dataset, batch_size=1,
26 | shuffle=True, num_workers=1)
27 | self.optimizer = optim.Adam(self.net.parameters(), lr=0.0005)
28 | self.logger = Logger(self.config.log_dir)
29 | self.construct_cors()
30 | self.save()
31 | if config.load:
32 | self.load()
33 |
34 | def save(self):
35 | torch.save(self.net.state_dict(), os.path.join(self.config.checkpoint_dir, "checkpoint"))
36 |
37 | def load(self):
38 | self.net.load_state_dict(torch.load(os.path.join(self.config.checkpoint_dir, "checkpoint")))
39 |
40 | def construct_cors(self):
41 | # x-cor and y-cor setting
42 | nx, ny = (self.config.weight, self.config.height)
43 | x = np.linspace(0, 1, nx)
44 | y = np.linspace(0, 1, ny)
45 | xv, yv = np.meshgrid(x, y)
46 | xv = np.reshape(xv, [self.config.height, self.config.weight, 1])
47 | yv = np.reshape(yv, [self.config.height, self.config.weight, 1])
48 | xcor = np.zeros((self.config.batch_size * 5, self.config.height, self.config.weight, 1), dtype=float)
49 | ycor = np.zeros((self.config.batch_size * 5, self.config.height, self.config.weight, 1), dtype=float)
50 | for i in range(self.config.batch_size * 5):
51 | xcor[i] = xv
52 | ycor[i] = yv
53 | xcor = xcor.transpose((0, 3, 1, 2))
54 | ycor = ycor.transpose((0, 3, 1, 2))
55 | self.xcor, self.ycor = Variable(torch.from_numpy(xcor)).cuda(), Variable(torch.from_numpy(ycor)).cuda()
56 |
57 | def train(self):
58 | total_step = 0
59 | df = Variable(torch.ones(1)).double().cuda()
60 | for epoch in range(100): # loop over the dataset multiple times
61 | running_loss = 0.0
62 | for i, data in enumerate(self.dataloader, 0):
63 | total_step += 1
64 | data = data[0]
65 | if data['image'].size()[0] < self.config.batch_size:
66 | print(data['image'].size()[0])
67 | continue
68 | inputs, output_label, output_S_label = data['image'], data['output_label'], data[
69 | 'output_S_label']
70 |
71 | inputs, output_label, output_S_label = Variable(inputs).cuda(), Variable(output_label).cuda(), Variable(
72 | output_S_label).cuda()
73 |
74 | self.optimizer.zero_grad()
75 |
76 | net_out, aux_out, _ = self.net(inputs, self.xcor, self.ycor)
77 |
78 | # loss and optimizer
79 | loss = nn.MSELoss()
80 | mse = df * loss(net_out[0], output_label[:, 0])
81 |
82 | for i in range(1, 8):
83 | mse += (df ** (i + 1)) * loss(net_out[i], output_label[:, i])
84 | mse = mse / 8;
85 | ve_loss = loss(aux_out, output_S_label)
86 | total_loss = mse + ve_loss
87 | total_loss.backward()
88 |
89 | self.optimizer.step()
90 | # tensorboard_logging
91 | self.logger.scalar_summary("mse", mse.data[0], total_step, "train")
92 | self.logger.scalar_summary("ve_loss", ve_loss.data[0], total_step, "train")
93 | self.logger.scalar_summary("total_loss", total_loss.data[0], total_step, "train")
94 | print("epoch ", epoch, " Finished")
95 | print("testing................")
96 | self.test()
97 | print('Finished Training')
98 |
99 | def test(self):
100 | test_data = None
101 | for i, data in enumerate(self.test_dataloader, 0):
102 | test_data = data
103 |
104 | data = test_data[0]
105 | inputs, output_label, output_S_label, xy_origin, xy_estimated = data['image'][0], data['output_label'], data[
106 | 'output_S_label'], data['xy_origin'], data['xy_estimated']
107 | xy_origin = Variable(xy_origin).data.cpu().numpy()[0]
108 | xy_estimated = Variable(xy_estimated).data.cpu().numpy()[0]
109 | inputs, output_label, output_S_label = Variable(inputs).cuda(), Variable(output_label).cuda(), Variable(
110 | output_S_label).cuda()
111 |
112 | out, aux_out, posi = self.net(inputs[:4], self.xcor, self.ycor)
113 | velo = posi[0][:, :, 2:4];
114 | xy_estimated[0] = output_S_label[0][3][3][:, :2].data.cpu().numpy() + (velo[0] * 0.01).data.cpu().numpy()
115 | for i in range(1, len([0])):
116 | xy_estimated[i] = xy_estimated[i - 1] + velo[i] * 0.01
117 |
118 | # Saving
119 | print("Image Making")
120 | make_image2(xy_origin, self.config.img_folder + "../results/", "true")
121 | make_image2(xy_estimated, self.config.img_folder + "../results/", "modeling")
122 | print("Done")
123 | yield
--------------------------------------------------------------------------------
/utils.py:
--------------------------------------------------------------------------------
1 | import os
2 | import matplotlib.pyplot as plt
3 | def create_dir(path):
4 | if not os.path.exists(path):
5 | os.makedirs(path)
6 | def make_image2(xy,img_folder,prefix):
7 | if not os.path.exists(img_folder):
8 | os.makedirs(img_folder);
9 | fig_num=len(xy);
10 | mydpi=100;
11 | for i in range(fig_num):
12 | #fig = plt.figure(figsize=(32/mydpi,32/mydpi))
13 | fig = plt.figure(figsize=(128/mydpi,128/mydpi))
14 | plt.xlim(-200, 200)
15 | plt.ylim(-200, 200)
16 | plt.axis('off');
17 | color=['r','b','g','k','y','m','c'];
18 | for j in range(len(xy[0])):
19 | #plt.scatter(xy[i,j,1],xy[i,j,0],c=color[j%len(color)],s=0.5);
20 | plt.scatter(xy[i,j,1],xy[i,j,0],c=color[j%len(color)],s=5);
21 | fig.savefig(img_folder+prefix+"_"+str(i)+".png",dpi=mydpi);
--------------------------------------------------------------------------------
/vin.py:
--------------------------------------------------------------------------------
1 | from model import Net
2 | from config import VinConfig
3 | import tensorflow as tf
4 |
5 |
6 | def main():
7 | from train import Trainer
8 | net=Net(VinConfig)
9 | net=net.cuda()
10 | net=net.double()
11 | trainer=Trainer(VinConfig,net)
12 | trainer.train()
13 |
14 |
15 |
16 |
17 | if __name__ == '__main__':
18 | main()
--------------------------------------------------------------------------------
/vin_dataset.py:
--------------------------------------------------------------------------------
1 | from torch.utils.data import Dataset
2 | import os
3 | import numpy as np
4 | import matplotlib.image as mpimg
5 | import torch
6 |
7 |
8 | class VinDataset(Dataset):
9 | """Face Landmarks dataset."""
10 |
11 | def __init__(self, config, transform=None):
12 |
13 | self.config = config
14 | self.transform = transform
15 |
16 | total_img = np.zeros((self.config.set_num, int(self.config.frame_num), self.config.height, self.config.weight,
17 | self.config.col_dim))
18 | for i in range(self.config.set_num):
19 | for j in range(int(self.config.frame_num)):
20 | total_img[i, j] = mpimg.imread(self.config.img_folder + "train/" + str(i) + '_' + str(j) + '.png')[:, :,
21 | :self.config.col_dim]
22 |
23 | total_data = np.zeros((self.config.set_num, int(self.config.frame_num), self.config.No * 5))
24 | for i in range(self.config.set_num):
25 | f = open(self.config.data_folder + "train/" + str(i) + ".csv", "r")
26 | total_data[i] = [line[:-1].split(",") for line in f.readlines()]
27 | total_data = np.reshape(total_data, [self.config.set_num, int(self.config.frame_num), self.config.No, 5])
28 |
29 | # reshape img and data
30 | input_img = np.zeros((self.config.set_num * (int(self.config.frame_num) - 14 + 1), 6, self.config.height,
31 | self.config.weight, self.config.col_dim)
32 | )
33 | output_label = np.zeros((self.config.set_num * (int(self.config.frame_num) - 14 + 1), 8, self.config.No, 4)
34 | )
35 | output_S_label = np.zeros((self.config.set_num * (int(self.config.frame_num) - 14 + 1), 4, self.config.No, 4)
36 | )
37 | for i in range(self.config.set_num):
38 | for j in range(int(self.config.frame_num) - 14 + 1):
39 | input_img[i * (int(self.config.frame_num) - 14 + 1) + j] = total_img[i, j:j + 6]
40 | output_label[i * (int(self.config.frame_num) - 14 + 1) + j] = np.reshape(total_data[i, j + 6:j + 14],
41 | [8, self.config.No, 5])[
42 | :, :, 1:5]
43 | output_S_label[i * (int(self.config.frame_num) - 14 + 1) + j] = np.reshape(total_data[i, j + 2:j + 6],
44 | [4, self.config.No, 5])[:, :,
45 | 1:5]
46 |
47 | # shuffle
48 | tr_data_num = int(len(input_img) * 1)
49 | total_idx = np.arange(len(input_img))
50 | np.random.shuffle(total_idx)
51 | self.tr_data = input_img[total_idx]
52 | self.tr_label = output_label[total_idx]
53 | self.tr_S_label = output_S_label[total_idx]
54 |
55 | def __len__(self):
56 | return len(self.tr_data)
57 |
58 | def __getitem__(self, idx):
59 |
60 | sample = {'image': self.tr_data[idx], 'output_label': self.tr_label[idx],
61 | 'output_S_label': self.tr_S_label[idx]}
62 |
63 | if self.transform:
64 | sample = self.transform(sample),
65 |
66 | return sample
67 |
68 |
69 | class ToTensor(object):
70 | """Convert ndarrays in sample to Tensors."""
71 |
72 | def __call__(self, sample):
73 | image, output_label, output_S_label = sample['image'], sample['output_label'], sample[
74 | 'output_S_label']
75 |
76 | # swap color axis because
77 | # numpy image: H x W x C
78 | # torch image: C X H X W
79 | image = image.transpose((0, 3, 1, 2))
80 | sample['image']=torch.from_numpy(image)
81 | sample['output_label']=torch.from_numpy(output_label)
82 | sample['output_S_label']=torch.from_numpy(output_S_label)
83 | return sample
84 |
85 | class ToTensorV2(object):
86 | """Convert ndarrays in sample to Tensors."""
87 |
88 | def __call__(self, sample):
89 | image, output_label, output_S_label = sample['image'], sample['output_label'], sample[
90 | 'output_S_label']
91 |
92 | # swap color axis because
93 | # numpy image: H x W x C
94 | # torch image: C X H X W
95 | image = image.transpose((0, 1, 4, 2,3))
96 | sample['image']=torch.from_numpy(image)
97 | sample['output_label']=torch.from_numpy(output_label)
98 | sample['output_S_label']=torch.from_numpy(output_S_label)
99 | return sample
100 |
101 |
102 | class VinTestDataset(Dataset):
103 | """Face Landmarks dataset."""
104 |
105 | def __init__(self, config, transform=None):
106 |
107 | self.config = config
108 | self.transform = transform
109 |
110 | def __len__(self):
111 | return 1
112 |
113 | def __getitem__(self, idx):
114 |
115 | total_img = np.zeros((self.config.set_num, int(self.config.frame_num), self.config.height, self.config.weight,
116 | self.config.col_dim))
117 | for i in range(self.config.set_num):
118 | for j in range(int(self.config.frame_num)):
119 | total_img[i, j] = mpimg.imread(self.config.img_folder + "train/" + str(i) + '_' + str(j) + '.png')[:, :,
120 | :self.config.col_dim]
121 | ts_img = np.zeros(
122 | (1, int(self.config.frame_num), self.config.height, self.config.weight, self.config.col_dim),
123 | dtype=float)
124 | for i in range(1):
125 | for j in range(int(self.config.frame_num)):
126 | ts_img[i, j] = mpimg.imread(self.config.img_folder + "test/" + str(i) + "_" + str(j) + '.png')[:, :,
127 | :self.config.col_dim]
128 | ts_data = np.zeros((1, int(self.config.frame_num), self.config.No * 5), dtype=float)
129 | for i in range(1):
130 | f = open(self.config.data_folder + "test/" + str(i) + ".csv", "r")
131 | ts_data[i] = [line[:-1].split(",") for line in f.readlines()]
132 |
133 | # reshape img and data
134 | input_img = np.zeros(
135 | (1 * (int(self.config.frame_num) - 14 + 1), 6, self.config.height, self.config.weight,
136 | self.config.col_dim),
137 | dtype=float);
138 | output_label = np.zeros((1 * (int(self.config.frame_num) - 14 + 1), 8, self.config.No, 4), dtype=float)
139 | output_S_label = np.zeros((1 * (int(self.config.frame_num) - 14 + 1), 4, self.config.No, 4), dtype=float)
140 | for i in range(1):
141 | for j in range(int(self.config.frame_num) - 14 + 1):
142 | input_img[i * (int(self.config.frame_num) - 14 + 1) + j] = total_img[i, j:j + 6]
143 | output_label[i * (int(self.config.frame_num) - 14 + 1) + j] = np.reshape(ts_data[i, j + 6:j + 14],
144 | [8, self.config.No, 5])[:,
145 | :, 1:5]
146 | output_S_label[i * (int(self.config.frame_num) - 14 + 1) + j] = np.reshape(ts_data[i, j + 2:j + 6],
147 | [4, self.config.No, 5])[
148 | :,
149 | :, 1:5]
150 |
151 | xy_origin = output_label[:(int(self.config.frame_num) - 14 + 1 - 4 + 1), 0, :, 0:2]
152 | xy_estimated = np.zeros((self.config.roll_num, self.config.No, 2), dtype=float)
153 |
154 | sample = {'image': input_img, 'output_label': output_label,
155 | 'output_S_label': output_S_label,'xy_origin':xy_origin,'xy_estimated':xy_estimated}
156 |
157 | if self.transform:
158 | sample = self.transform(sample),
159 |
160 | return sample
161 |
162 |
--------------------------------------------------------------------------------