├── .gitignore ├── LICENSE.md ├── README.md ├── assets ├── results.png └── vin.png ├── data.py ├── data └── gridworld_8.mat ├── model.py ├── train.py └── utils.py /.gitignore: -------------------------------------------------------------------------------- 1 | *.DS_Store 2 | __pycache__/* 3 | env/* 4 | misc/* -------------------------------------------------------------------------------- /LICENSE.md: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright 2019, Abhishek Kumar 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # [Value Iteration Networks](https://arxiv.org/abs/1602.02867) in TensorFlow 2 | 3 | > Tamar, A., Wu, Y., Thomas, G., Levine, S., and Abbeel, P. _Value Iteration Networks_. Neural Information Processing Systems (NIPS) 2016 4 | 5 | This repository contains an implementation of Value Iteration Networks in TensorFlow which won the Best Paper Award at NIPS 2016. This code is based on the original Theano implementation by the authors. 6 | 7 | ![Value Iteration Network and Module](assets/vin.png) 8 | 9 | ## Training 10 | 11 | - Download the 16x16 and 28x28 GridWorld datasets from the [author's repository](https://github.com/avivt/VIN/tree/master/data). This repository contains the 8x8 GridWorld dataset for convenience and its small size. 12 | 13 | ``` 14 | # Runs the 8x8 Gridworld with default parameters 15 | python3 train.py 16 | ``` 17 | 18 | If you want to monitor training progress change `config.log` to `True` and launch `tensorboard --logdir /tmp/vintf/`. The log directory is `/tmp/vintf/` by default, but can be changed in `config.logdir`. The code currently runs the 8x8 GridWorld model by default. 19 | 20 | The 8x8 GridWorld model converges in under 30 epochs with about ~98.5% accuracy. The paper lists that it should be around 99.6% and I was able to reproduce this with the Theano code. Results for 16x16 and 28x28 can be seen [here](https://github.com/TheAbhiKumar/tensorflow-value-iteration-networks/issues/6) 21 | 22 | ## Dependencies 23 | * Python >= 3.6 24 | * TensorFlow >= 1.0 25 | * SciPy >= 0.18.1 (to load the data) 26 | 27 | ## Datasets 28 | * The GridWorld dataset used is from the author's repository. It also contains Matlab scripts to generate the dataset. The code to process the dataset is from the original repository with minor modifications under this [license](https://github.com/avivt/VIN/blob/master/LICENSE.md) 29 | * The model was also originally tested on three other domains and the author's original code will be [released eventually](https://github.com/avivt/VIN/issues/4) 30 | * Mars Rover Navigation 31 | * Continuous control 32 | * WebNav 33 | 34 | ## Resources 35 | 36 | * [Value Iteration Networks on arXiv](https://arxiv.org/abs/1602.02867) 37 | * [Aviv Tamar's (author) original implementation in Theano](https://github.com/avivt/VIN) 38 | * [ICML Slides](http://docs.wixstatic.com/ugd/3195dc_6ab5cea3189741a3b605fc6fc1d79bb8.pdf) 39 | -------------------------------------------------------------------------------- /assets/results.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hi-abhi/tensorflow-value-iteration-networks/3b77bbebd5ee637cc874fdbbe1058c5e02780e33/assets/results.png -------------------------------------------------------------------------------- /assets/vin.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hi-abhi/tensorflow-value-iteration-networks/3b77bbebd5ee637cc874fdbbe1058c5e02780e33/assets/vin.png -------------------------------------------------------------------------------- /data.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | import scipy.io as sio 3 | 4 | def process_gridworld_data(input, imsize): 5 | # run training from input matlab data file, and save test data prediction in output file 6 | # load data from Matlab file, including 7 | # im_data: flattened images 8 | # state_data: concatenated one-hot vectors for each state variable 9 | # state_xy_data: state variable (x,y position) 10 | # label_data: one-hot vector for action (state difference) 11 | im_size=[imsize, imsize] 12 | matlab_data = sio.loadmat(input) 13 | im_data = matlab_data["batch_im_data"] 14 | im_data = (im_data - 1)/255 # obstacles = 1, free zone = 0 15 | value_data = matlab_data["batch_value_data"] 16 | state1_data = matlab_data["state_x_data"] 17 | state2_data = matlab_data["state_y_data"] 18 | label_data = matlab_data["batch_label_data"] 19 | ydata = label_data.astype('int8') 20 | Xim_data = im_data.astype('float32') 21 | Xim_data = Xim_data.reshape(-1, 1, im_size[0], im_size[1]) 22 | Xval_data = value_data.astype('float32') 23 | Xval_data = Xval_data.reshape(-1, 1, im_size[0], im_size[1]) 24 | Xdata = np.append(Xim_data, Xval_data, axis=1) 25 | # Need to transpose because Theano is NCHW, while TensorFlow is NHWC 26 | Xdata = np.transpose(Xdata, (0, 2, 3, 1)) 27 | S1data = state1_data.astype('int8') 28 | S2data = state2_data.astype('int8') 29 | 30 | all_training_samples = int(6/7.0*Xdata.shape[0]) 31 | training_samples = all_training_samples 32 | Xtrain = Xdata[0:training_samples] 33 | S1train = S1data[0:training_samples] 34 | S2train = S2data[0:training_samples] 35 | ytrain = ydata[0:training_samples] 36 | 37 | Xtest = Xdata[all_training_samples:] 38 | S1test = S1data[all_training_samples:] 39 | S2test = S2data[all_training_samples:] 40 | ytest = ydata[all_training_samples:] 41 | ytest = ytest.flatten() 42 | 43 | sortinds = np.random.permutation(training_samples) 44 | Xtrain = Xtrain[sortinds] 45 | S1train = S1train[sortinds] 46 | S2train = S2train[sortinds] 47 | ytrain = ytrain[sortinds] 48 | ytrain = ytrain.flatten() 49 | return Xtrain, S1train, S2train, ytrain, Xtest, S1test, S2test, ytest 50 | -------------------------------------------------------------------------------- /data/gridworld_8.mat: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hi-abhi/tensorflow-value-iteration-networks/3b77bbebd5ee637cc874fdbbe1058c5e02780e33/data/gridworld_8.mat -------------------------------------------------------------------------------- /model.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | import tensorflow as tf 3 | from utils import conv2d_flipkernel 4 | 5 | def VI_Block(X, S1, S2, config): 6 | k = config.k # Number of value iterations performed 7 | ch_i = config.ch_i # Channels in input layer 8 | ch_h = config.ch_h # Channels in initial hidden layer 9 | ch_q = config.ch_q # Channels in q layer (~actions) 10 | state_batch_size = config.statebatchsize # k+1 state inputs for each channel 11 | 12 | bias = tf.Variable(np.random.randn(1, 1, 1, ch_h) * 0.01, dtype=tf.float32) 13 | # weights from inputs to q layer (~reward in Bellman equation) 14 | w0 = tf.Variable(np.random.randn(3, 3, ch_i, ch_h) * 0.01, dtype=tf.float32) 15 | w1 = tf.Variable(np.random.randn(1, 1, ch_h, 1) * 0.01, dtype=tf.float32) 16 | w = tf.Variable(np.random.randn(3, 3, 1, ch_q) * 0.01, dtype=tf.float32) 17 | # feedback weights from v layer into q layer (~transition probabilities in Bellman equation) 18 | w_fb = tf.Variable(np.random.randn(3, 3, 1, ch_q) * 0.01, dtype=tf.float32) 19 | w_o = tf.Variable(np.random.randn(ch_q, 8) * 0.01, dtype=tf.float32) 20 | 21 | # initial conv layer over image+reward prior 22 | h = conv2d_flipkernel(X, w0, name="h0") + bias 23 | 24 | r = conv2d_flipkernel(h, w1, name="r") 25 | q = conv2d_flipkernel(r, w, name="q") 26 | v = tf.reduce_max(q, axis=3, keep_dims=True, name="v") 27 | 28 | for i in range(0, k-1): 29 | rv = tf.concat([r, v], 3) 30 | wwfb = tf.concat([w, w_fb], 2) 31 | q = conv2d_flipkernel(rv, wwfb, name="q") 32 | v = tf.reduce_max(q, axis=3, keep_dims=True, name="v") 33 | 34 | # do one last convolution 35 | q = conv2d_flipkernel(tf.concat([r, v], 3), 36 | tf.concat([w, w_fb], 2), name="q") 37 | 38 | # CHANGE TO THEANO ORDERING 39 | # Since we are selecting over channels, it becomes easier to work with 40 | # the tensor when it is in NCHW format vs NHWC 41 | q = tf.transpose(q, perm=[0, 3, 1, 2]) 42 | 43 | # Select the conv-net channels at the state position (S1,S2). 44 | # This intuitively corresponds to each channel representing an action, and the convnet the Q function. 45 | # The tricky thing is we want to select the same (S1,S2) position *for each* channel and for each sample 46 | # TODO: performance can be improved here by substituting expensive 47 | # transpose calls with better indexing for gather_nd 48 | bs = tf.shape(q)[0] 49 | rprn = tf.reshape(tf.tile(tf.reshape(tf.range(bs), [-1, 1]), [1, state_batch_size]), [-1]) 50 | ins1 = tf.cast(tf.reshape(S1, [-1]), tf.int32) 51 | ins2 = tf.cast(tf.reshape(S2, [-1]), tf.int32) 52 | idx_in = tf.transpose(tf.stack([ins1, ins2, rprn]), [1, 0]) 53 | q_out = tf.gather_nd(tf.transpose(q, [2, 3, 0, 1]), idx_in, name="q_out") 54 | 55 | # add logits 56 | logits = tf.matmul(q_out, w_o) 57 | # softmax output weights 58 | output = tf.nn.softmax(logits, name="output") 59 | return logits, output 60 | 61 | # similar to the normal VI_Block except there are separate weights for each q layer 62 | def VI_Untied_Block(X, S1, S2, config): 63 | k = config.k # Number of value iterations performed 64 | ch_i = config.ch_i # Channels in input layer 65 | ch_h = config.ch_h # Channels in initial hidden layer 66 | ch_q = config.ch_q # Channels in q layer (~actions) 67 | state_batch_size = config.statebatchsize # k+1 state inputs for each channel 68 | 69 | bias = tf.Variable(np.random.randn(1, 1, 1, ch_h) * 0.01, dtype=tf.float32) 70 | # weights from inputs to q layer (~reward in Bellman equation) 71 | w0 = tf.Variable(np.random.randn(3, 3, ch_i, ch_h) * 0.01, dtype=tf.float32) 72 | w1 = tf.Variable(np.random.randn(1, 1, ch_h, 1) * 0.01, dtype=tf.float32) 73 | w_l = [tf.Variable(np.random.randn(3, 3, 1, ch_q) * 0.01, dtype=tf.float32) for i in range(0, k+1)] 74 | # feedback weights from v layer into q layer (~transition probabilities in Bellman equation) 75 | w_fb_l = [tf.Variable(np.random.randn(3, 3, 1, ch_q) * 0.01, dtype=tf.float32) for i in range(0,k)] 76 | w_o = tf.Variable(np.random.randn(ch_q, 8) * 0.01, dtype=tf.float32) 77 | 78 | # initial conv layer over image+reward prior 79 | h = conv2d_flipkernel(X, w0, name="h0") + bias 80 | 81 | r = conv2d_flipkernel(h, w1, name="r") 82 | q = conv2d_flipkernel(r, w_l[0], name="q") 83 | v = tf.reduce_max(q, axis=3, keep_dims=True, name="v") 84 | 85 | for i in range(0, k-1): 86 | rv = tf.concat([r, v], 3) 87 | wwfb = tf.concat([w_l[i+1], w_fb_l[i]], 2) 88 | q = conv2d_flipkernel(rv, wwfb, name="q") 89 | v = tf.reduce_max(q, axis=3, keep_dims=True, name="v") 90 | 91 | # do one last convolution 92 | q = conv2d_flipkernel(tf.concat([r, v], 3), 93 | tf.concat([w_l[k], w_fb_l[k-1]], 2), name="q") 94 | 95 | # CHANGE TO THEANO ORDERING 96 | # Since we are selecting over channels, it becomes easier to work with 97 | # the tensor when it is in NCHW format vs NHWC 98 | q = tf.transpose(q, perm=[0, 3, 1, 2]) 99 | 100 | # Select the conv-net channels at the state position (S1,S2). 101 | # This intuitively corresponds to each channel representing an action, and the convnet the Q function. 102 | # The tricky thing is we want to select the same (S1,S2) position *for each* channel and for each sample 103 | # TODO: performance can be improved here by substituting expensive 104 | # transpose calls with better indexing for gather_nd 105 | bs = tf.shape(q)[0] 106 | rprn = tf.reshape(tf.tile(tf.reshape(tf.range(bs), [-1, 1]), [1, state_batch_size]), [-1]) 107 | ins1 = tf.cast(tf.reshape(S1, [-1]), tf.int32) 108 | ins2 = tf.cast(tf.reshape(S2, [-1]), tf.int32) 109 | idx_in = tf.transpose(tf.stack([ins1, ins2, rprn]), [1, 0]) 110 | q_out = tf.gather_nd(tf.transpose(q, [2, 3, 0, 1]), idx_in, name="q_out") 111 | 112 | # add logits 113 | logits = tf.matmul(q_out, w_o) 114 | # softmax output weights 115 | output = tf.nn.softmax(logits, name="output") 116 | return logits, output 117 | -------------------------------------------------------------------------------- /train.py: -------------------------------------------------------------------------------- 1 | import time 2 | import numpy as np 3 | import tensorflow as tf 4 | from data import process_gridworld_data 5 | from model import VI_Block, VI_Untied_Block 6 | from utils import fmt_row 7 | 8 | # Data 9 | tf.app.flags.DEFINE_string('input', 'data/gridworld_8.mat', 'Path to data') 10 | tf.app.flags.DEFINE_integer('imsize', 8, 'Size of input image') 11 | # Parameters 12 | tf.app.flags.DEFINE_float('lr', 0.001, 'Learning rate for RMSProp') 13 | tf.app.flags.DEFINE_integer('epochs', 30, 'Maximum epochs to train for') 14 | tf.app.flags.DEFINE_integer('k', 10, 'Number of value iterations') 15 | tf.app.flags.DEFINE_integer('ch_i', 2, 'Channels in input layer') 16 | tf.app.flags.DEFINE_integer('ch_h', 150, 'Channels in initial hidden layer') 17 | tf.app.flags.DEFINE_integer('ch_q', 10, 'Channels in q layer (~actions)') 18 | tf.app.flags.DEFINE_integer('batchsize', 12, 'Batch size') 19 | tf.app.flags.DEFINE_integer('statebatchsize', 10, 'Number of state inputs for each sample (real number, technically is k+1)') 20 | tf.app.flags.DEFINE_boolean('untied_weights', False, 'Untie weights of VI network') 21 | # Misc. 22 | tf.app.flags.DEFINE_integer('seed', 0, 'Random seed for numpy') 23 | tf.app.flags.DEFINE_integer('display_step', 1, 'Print summary output every n epochs') 24 | tf.app.flags.DEFINE_boolean('log', False, 'Enable for tensorboard summary') 25 | tf.app.flags.DEFINE_string('logdir', '/tmp/vintf/', 'Directory to store tensorboard summary') 26 | 27 | config = tf.app.flags.FLAGS 28 | 29 | np.random.seed(config.seed) 30 | 31 | # symbolic input image tensor where typically first channel is image, second is the reward prior 32 | X = tf.placeholder(tf.float32, name="X", shape=[None, config.imsize, config.imsize, config.ch_i]) 33 | # symbolic input batches of vertical positions 34 | S1 = tf.placeholder(tf.int32, name="S1", shape=[None, config.statebatchsize]) 35 | # symbolic input batches of horizontal positions 36 | S2 = tf.placeholder(tf.int32, name="S2", shape=[None, config.statebatchsize]) 37 | y = tf.placeholder(tf.int32, name="y", shape=[None]) 38 | 39 | # Construct model (Value Iteration Network) 40 | if (config.untied_weights): 41 | logits, nn = VI_Untied_Block(X, S1, S2, config) 42 | else: 43 | logits, nn = VI_Block(X, S1, S2, config) 44 | 45 | # Define loss and optimizer 46 | y_ = tf.cast(y, tf.int64) 47 | cross_entropy = tf.nn.sparse_softmax_cross_entropy_with_logits( 48 | logits=logits, labels=y_, name='cross_entropy') 49 | cross_entropy_mean = tf.reduce_mean(cross_entropy, name='cross_entropy_mean') 50 | tf.add_to_collection('losses', cross_entropy_mean) 51 | 52 | cost = tf.add_n(tf.get_collection('losses'), name='total_loss') 53 | optimizer = tf.train.RMSPropOptimizer(learning_rate=config.lr, epsilon=1e-6, centered=True).minimize(cost) 54 | 55 | # Test model & calculate accuracy 56 | cp = tf.cast(tf.argmax(nn, 1), tf.int32) 57 | err = tf.reduce_mean(tf.cast(tf.not_equal(cp, y), dtype=tf.float32)) 58 | 59 | # Initializing the variables 60 | init = tf.global_variables_initializer() 61 | saver = tf.train.Saver() 62 | 63 | Xtrain, S1train, S2train, ytrain, Xtest, S1test, S2test, ytest = process_gridworld_data(input=config.input, imsize=config.imsize) 64 | 65 | # Launch the graph 66 | with tf.Session() as sess: 67 | if config.log: 68 | for var in tf.trainable_variables(): 69 | tf.summary.histogram(var.op.name, var) 70 | summary_op = tf.summary.merge_all() 71 | summary_writer = tf.summary.FileWriter(config.logdir, sess.graph) 72 | sess.run(init) 73 | 74 | batch_size = config.batchsize 75 | print(fmt_row(10, ["Epoch", "Train Cost", "Train Err", "Epoch Time"])) 76 | for epoch in range(int(config.epochs)): 77 | tstart = time.time() 78 | avg_err, avg_cost = 0.0, 0.0 79 | num_batches = int(Xtrain.shape[0]/batch_size) 80 | # Loop over all batches 81 | for i in range(0, Xtrain.shape[0], batch_size): 82 | j = i + batch_size 83 | if j <= Xtrain.shape[0]: 84 | # Run optimization op (backprop) and cost op (to get loss value) 85 | fd = {X: Xtrain[i:j], S1: S1train[i:j], S2: S2train[i:j], 86 | y: ytrain[i * config.statebatchsize:j * config.statebatchsize]} 87 | _, e_, c_ = sess.run([optimizer, err, cost], feed_dict=fd) 88 | avg_err += e_ 89 | avg_cost += c_ 90 | # Display logs per epoch step 91 | if epoch % config.display_step == 0: 92 | elapsed = time.time() - tstart 93 | print(fmt_row(10, [epoch, avg_cost/num_batches, avg_err/num_batches, elapsed])) 94 | if config.log: 95 | summary = tf.Summary() 96 | summary.ParseFromString(sess.run(summary_op)) 97 | summary.value.add(tag='Average error', simple_value=float(avg_err/num_batches)) 98 | summary.value.add(tag='Average cost', simple_value=float(avg_cost/num_batches)) 99 | summary_writer.add_summary(summary, epoch) 100 | print("Finished training!") 101 | 102 | # Test model 103 | correct_prediction = tf.cast(tf.argmax(nn, 1), tf.int32) 104 | # Calculate accuracy 105 | accuracy = tf.reduce_mean(tf.cast(tf.not_equal(correct_prediction, y), dtype=tf.float32)) 106 | acc = accuracy.eval({X: Xtest, S1: S1test, S2: S2test, y: ytest}) 107 | print(f'Accuracy: {100 * (1 - acc)}%') 108 | -------------------------------------------------------------------------------- /utils.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | import tensorflow as tf 3 | 4 | # helper methods to print nice table (taken from CGT code) 5 | def fmt_item(x, l): 6 | if isinstance(x, np.ndarray): 7 | assert x.ndim==0 8 | x = x.item() 9 | if isinstance(x, float): rep = "%g"%x 10 | else: rep = str(x) 11 | return " "*(l - len(rep)) + rep 12 | 13 | def fmt_row(width, row): 14 | out = " | ".join(fmt_item(x, width) for x in row) 15 | return out 16 | 17 | def flipkernel(kern): 18 | return kern[(slice(None, None, -1),) * 2 + (slice(None), slice(None))] 19 | 20 | def conv2d_flipkernel(x, k, name=None): 21 | return tf.nn.conv2d(x, flipkernel(k), name=name, 22 | strides=(1, 1, 1, 1), padding='SAME') --------------------------------------------------------------------------------