├── .gitignore ├── CONTRIBUTING.md ├── LICENSE ├── README.md ├── capsLayer.py ├── capsNet.py ├── config.py ├── eval.py ├── imgs ├── margin_loss.png ├── my_wechat_QR.png ├── reconstruction_loss.png ├── total_loss.png ├── training_loss.png └── wechat_group.png ├── results ├── test_000.png ├── test_005.png ├── test_010.png ├── test_015.png ├── test_020.png ├── test_025.png ├── test_030.png ├── test_035.png ├── test_040.png ├── test_045.png ├── test_050.png ├── test_055.png ├── test_060.png ├── test_065.png ├── test_070.png └── test_075.png ├── train.py └── utils.py /.gitignore: -------------------------------------------------------------------------------- 1 | *__pycache__ 2 | data* 3 | .ropeproject 4 | logdir 5 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | This repo is under development, your contribution is welcome. 2 | 3 | - If you have a question, feel free to open an issues. **No email!** Recently I can't access my gmail. 4 | - If you want to contribue your code, fork it, and open your Pull Requests. I'm working on this repo these days, so I can review your code within an hour. 5 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 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 {yyyy} {name of copyright owner} 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 | # CapsNet-Tensorflow 2 | 3 | [![Contributions welcome](https://img.shields.io/badge/contributions-welcome-brightgreen.svg?style=plastic)](CONTRIBUTING.md) 4 | [![License](https://img.shields.io/badge/license-Apache%202.0-blue.svg?style=plastic)](https://opensource.org/licenses/Apache-2.0) 5 | ![completion](https://img.shields.io/badge/completion%20state-90%25-blue.svg?style=plastic) 6 | 7 | A Tensorflow implementation of CapsNet in Hinton's paper [Dynamic Routing Between Capsules](https://arxiv.org/abs/1710.09829) 8 | 9 | > - **Note:** 10 | 11 | > 1. The routing algorithm has been found not implemented as the same as the one in the paper!(#8, thanks very much, it's my carelessness) Although the current version works, but not effective as the results in the paper, I've paste out some results of the 'wrong' version(It's really interesting). I'll analyze the reasons of this interesting thing 12 | > 2. I've been working continuously for the last few days, coding, talking, writing docs, so I would like to give myself half a day. I will be back tomorrow, and keep updating this repo 13 | > 3. [Here(知乎)](https://zhihu.com/question/67287444/answer/251460831) is my understanding of the section 4 of the paper (the core part of CapsNet), it might be helpful for understanding the code. Thanks for your focus 14 | > 4. If you find out any problems, please let me know. I will try my best to 'kill' it as quickly as possible. 15 | 16 | In the day of waiting, be patient: Merry days will come, believe. ---- Alexander PuskinIf :blush: 17 | 18 | ## Requirements 19 | - Python 20 | - NumPy 21 | - [Tensorflow](https://github.com/tensorflow/tensorflow) (I'm using 1.3.0, others should work, too) 22 | - tqdm (for showing training progress info) 23 | 24 | ## Usage 25 | 26 | ### Training 27 | **Step 1.** 28 | Clone this repository with ``git``. 29 | 30 | ``` 31 | $ git clone https://github.com/naturomics/CapsNet-Tensorflow.git 32 | $ cd CapsNet-Tensorflow 33 | ``` 34 | 35 | **Step 2.** 36 | Download [MNIST dataset](http://yann.lecun.com/exdb/mnist/), ``mv`` and extract them into ``data/mnist`` directory.(Be careful the backslash appeared around the curly braces when you copy the ``wget `` command to your terminal, remove it) 37 | 38 | ``` 39 | $ mkdir -p data/mnist 40 | $ wget -c -P data/mnist http://yann.lecun.com/exdb/mnist/{train-images-idx3-ubyte.gz,train-labels-idx1-ubyte.gz,t10k-images-idx3-ubyte.gz,t10k-labels-idx1-ubyte.gz} 41 | $ gunzip data/mnist/*.gz 42 | ``` 43 | 44 | **Step 3.** 45 | Start training with command line: 46 | ``` 47 | $ pip install tqdm # install it if you haven't installed yes 48 | $ python train.py 49 | ``` 50 | 51 | the tqdm package is not necessary, just a tool for showing the training progress. If you don't want it, change the loop ``for in step ...`` to ``for step in range(num_batch)`` in ``train.py`` 52 | 53 | ### Evaluation 54 | ``` 55 | $ python eval.py --is_training False 56 | ``` 57 | 58 | 59 | ## Results 60 | Results for the 'wrong' version(Issues #8): 61 | 62 | - training loss 63 | ![total_loss](imgs/total_loss.png) 64 | 65 | ![margin_loss](imgs/margin_loss.png) 66 | ![reconstruction_loss](imgs/reconstruction_loss.png) 67 | 68 | - test acc 69 | ------------ 70 | |Epoch|49|51| 71 | |:----:|:----:|:--:| 72 | |test acc|94.69|94.71| 73 | 74 | ![test_img1](results/test_000.png) 75 | ![test_img2](results/test_015.png) 76 | ![test_img3](results/test_030.png) 77 | ![test_img4](results/test_045.png) 78 | ![test_img5](results/test_075.png) 79 | 80 | Results after fix Issues #8: 81 | 82 | ### TODO: 83 | - Finish the MNIST version of capsNet (progress:90%) 84 | - Do some different experiments for capsNet: 85 | * Using other datasets such as CIFAR 86 | * Adjusting model structure 87 | 88 | - There is [another new paper](https://openreview.net/pdf?id=HJWLfGWRb) about capsules(submitted to ICLR 2018), follow-up. 89 | -------------------------------------------------------------------------------- /capsLayer.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | import tensorflow as tf 3 | 4 | from config import cfg 5 | 6 | 7 | class CapsConv(object): 8 | ''' Capsule layer. 9 | Args: 10 | input: A 4-D tensor. 11 | num_units: integer, the length of the output vector of a capsule. 12 | with_routing: boolean, this capsule is routing with the 13 | lower-level layer capsule. 14 | num_outputs: the number of capsule in this layer. 15 | 16 | Returns: 17 | A 4-D tensor. 18 | ''' 19 | def __init__(self, num_units, with_routing=True): 20 | self.num_units = num_units 21 | self.with_routing = with_routing 22 | 23 | def __call__(self, input, num_outputs, kernel_size=None, stride=None): 24 | self.num_outputs = num_outputs 25 | self.kernel_size = kernel_size 26 | self.stride = stride 27 | 28 | if not self.with_routing: 29 | # the PrimaryCaps layer 30 | # input: [batch_size, 20, 20, 256] 31 | assert input.get_shape() == [cfg.batch_size, 20, 20, 256] 32 | 33 | capsules = [] 34 | for i in range(self.num_units): 35 | # each capsule i: [batch_size, 6, 6, 32] 36 | with tf.variable_scope('ConvUnit_' + str(i)): 37 | caps_i = tf.contrib.layers.conv2d(input, 38 | self.num_outputs, 39 | self.kernel_size, 40 | self.stride, 41 | padding="VALID") 42 | caps_i = tf.reshape(caps_i, shape=(cfg.batch_size, -1, 1, 1)) 43 | capsules.append(caps_i) 44 | 45 | assert capsules[0].get_shape() == [cfg.batch_size, 1152, 1, 1] 46 | 47 | # [batch_size, 1152, 8, 1] 48 | capsules = tf.concat(capsules, axis=2) 49 | capsules = squash(capsules) 50 | assert capsules.get_shape() == [cfg.batch_size, 1152, 8, 1] 51 | 52 | else: 53 | # the DigitCaps layer 54 | # Reshape the input into shape [batch_size, 1152, 8, 1] 55 | self.input = tf.reshape(input, shape=(cfg.batch_size, 1152, 8, 1)) 56 | 57 | # b_IJ: [1, num_caps_l, num_caps_l_plus_1, 1] 58 | b_IJ = tf.zeros(shape=[1, 1152, 10, 1], dtype=np.float32) 59 | capsules = [] 60 | for j in range(self.num_outputs): 61 | with tf.variable_scope('caps_' + str(j)): 62 | caps_j, b_IJ = capsule(input, b_IJ, j) 63 | capsules.append(caps_j) 64 | 65 | # Return a tensor with shape [batch_size, 10, 16, 1] 66 | capsules = tf.concat(capsules, axis=1) 67 | assert capsules.get_shape() == [cfg.batch_size, 10, 16, 1] 68 | 69 | return(capsules) 70 | 71 | 72 | def capsule(input, b_IJ, idx_j): 73 | ''' The routing algorithm for one capsule in the layer l+1. 74 | 75 | Args: 76 | input: A Tensor with [batch_size, num_caps_l=1152, length(u_i)=8, 1] 77 | shape, num_caps_l meaning the number of capsule in the layer l. 78 | Returns: 79 | A Tensor of shape [batch_size, 1, length(v_j)=16, 1] representing the 80 | vector output `v_j` of capsule j in the layer l+1 81 | Notes: 82 | u_i represents the vector output of capsule i in the layer l, and 83 | v_j the vector output of capsule j in the layer l+1. 84 | ''' 85 | 86 | with tf.variable_scope('routing'): 87 | w_initializer = np.random.normal(size=[1, 1152, 8, 16], scale=0.01) 88 | W_Ij = tf.Variable(w_initializer, dtype=tf.float32) 89 | # repeat W_Ij with batch_size times to shape [batch_size, 1152, 8, 16] 90 | W_Ij = tf.tile(W_Ij, [cfg.batch_size, 1, 1, 1]) 91 | 92 | # calc u_hat 93 | # [8, 16].T x [8, 1] => [16, 1] => [batch_size, 1152, 16, 1] 94 | u_hat = tf.matmul(W_Ij, input, transpose_a=True) 95 | assert u_hat.get_shape() == [cfg.batch_size, 1152, 16, 1] 96 | 97 | shape = b_IJ.get_shape().as_list() 98 | size_splits = [idx_j, 1, shape[2] - idx_j - 1] 99 | for r_iter in range(cfg.iter_routing): 100 | # line 4: 101 | # [1, 1152, 10, 1] 102 | c_IJ = tf.nn.softmax(b_IJ, dim=2) 103 | assert c_IJ.get_shape() == [1, 1152, 10, 1] 104 | 105 | # line 5: 106 | # weighting u_hat with c_I in the third dim, 107 | # then sum in the second dim, resulting in [batch_size, 1, 16, 1] 108 | b_Il, b_Ij, b_Ir = tf.split(b_IJ, size_splits, axis=2) 109 | c_Il, c_Ij, b_Ir = tf.split(c_IJ, size_splits, axis=2) 110 | assert c_Ij.get_shape() == [1, 1152, 1, 1] 111 | 112 | s_j = tf.multiply(c_Ij, u_hat) 113 | s_j = tf.reduce_sum(tf.multiply(c_Ij, u_hat), 114 | axis=1, keep_dims=True) 115 | assert s_j.get_shape() == [cfg.batch_size, 1, 16, 1] 116 | 117 | # line 6: 118 | # squash using Eq.1, resulting in [batch_size, 1, 16, 1] 119 | v_j = squash(s_j) 120 | assert s_j.get_shape() == [cfg.batch_size, 1, 16, 1] 121 | 122 | # line 7: 123 | # tile v_j from [batch_size ,1, 16, 1] to [batch_size, 1152, 16, 1] 124 | # [16, 1].T x [16, 1] => [1, 1], then reduce mean in the 125 | # batch_size dim, resulting in [1, 1152, 1, 1] 126 | v_j_tiled = tf.tile(v_j, [1, 1152, 1, 1]) 127 | u_produce_v = tf.matmul(u_hat, v_j_tiled, transpose_a=True) 128 | assert u_produce_v.get_shape() == [cfg.batch_size, 1152, 1, 1] 129 | b_Ij += tf.reduce_sum(u_produce_v, axis=0, keep_dims=True) 130 | b_IJ = tf.concat([b_Il, b_Ij, b_Ir], axis=2) 131 | 132 | return(v_j, b_IJ) 133 | 134 | 135 | def squash(vector): 136 | '''Squashing function. 137 | Args: 138 | vector: A 4-D tensor with shape [batch_size, num_caps, vec_len, 1], 139 | Returns: 140 | A 4-D tensor with the same shape as vector but 141 | squashed in 3rd and 4th dimensions. 142 | ''' 143 | vec_abs = tf.sqrt(tf.reduce_sum(tf.square(vector))) # a scalar 144 | scalar_factor = tf.square(vec_abs) / (1 + tf.square(vec_abs)) 145 | vec_squashed = scalar_factor * tf.divide(vector, vec_abs) # element-wise 146 | return(vec_squashed) 147 | -------------------------------------------------------------------------------- /capsNet.py: -------------------------------------------------------------------------------- 1 | import tensorflow as tf 2 | 3 | from config import cfg 4 | from utils import get_batch_data 5 | from capsLayer import CapsConv 6 | 7 | 8 | class CapsNet(object): 9 | def __init__(self, is_training=True): 10 | self.graph = tf.Graph() 11 | with self.graph.as_default(): 12 | if is_training: 13 | self.X, self.Y = get_batch_data() 14 | 15 | self.build_arch() 16 | self.loss() 17 | 18 | # t_vars = tf.trainable_variables() 19 | self.optimizer = tf.train.AdamOptimizer() 20 | self.global_step = tf.Variable(0, name='global_step', trainable=False) 21 | self.train_op = self.optimizer.minimize(self.total_loss, global_step=self.global_step) # var_list=t_vars) 22 | else: 23 | self.X = tf.placeholder(tf.float32, 24 | shape=(cfg.batch_size, 28, 28, 1)) 25 | self.build_arch() 26 | 27 | tf.logging.info('Seting up the main structure') 28 | 29 | def build_arch(self): 30 | with tf.variable_scope('Conv1_layer'): 31 | # Conv1, [batch_size, 20, 20, 256] 32 | conv1 = tf.contrib.layers.conv2d(self.X, num_outputs=256, 33 | kernel_size=9, stride=1, 34 | padding='VALID') 35 | assert conv1.get_shape() == [cfg.batch_size, 20, 20, 256] 36 | 37 | # TODO: Rewrite the 'CapsConv' class as a function, the capsLay 38 | # function should be encapsulated into tow function, one like conv2d 39 | # and another is fully_connected in Tensorflow. 40 | # Primary Capsules, [batch_size, 1152, 8, 1] 41 | with tf.variable_scope('PrimaryCaps_layer'): 42 | primaryCaps = CapsConv(num_units=8, with_routing=False) 43 | caps1 = primaryCaps(conv1, num_outputs=32, kernel_size=9, stride=2) 44 | assert caps1.get_shape() == [cfg.batch_size, 1152, 8, 1] 45 | 46 | # DigitCaps layer, [batch_size, 10, 16, 1] 47 | with tf.variable_scope('DigitCaps_layer'): 48 | digitCaps = CapsConv(num_units=16, with_routing=True) 49 | self.caps2 = digitCaps(caps1, num_outputs=10) 50 | 51 | # Decoder structure in Fig. 2 52 | # 1. Do masking, how: 53 | with tf.variable_scope('Masking'): 54 | # a). calc ||v_c||, then do softmax(||v_c||) 55 | # [batch_size, 10, 16, 1] => [batch_size, 10, 1, 1] 56 | self.v_length = tf.sqrt(tf.reduce_sum(tf.square(self.caps2), 57 | axis=2, keep_dims=True)) 58 | self.softmax_v = tf.nn.softmax(self.v_length, dim=1) 59 | assert self.softmax_v.get_shape() == [cfg.batch_size, 10, 1, 1] 60 | 61 | # b). pick out the index of max softmax val of the 10 caps 62 | # [batch_size, 10, 1, 1] => [batch_size] (index) 63 | argmax_idx = tf.argmax(self.softmax_v, axis=1, output_type=tf.int32) 64 | assert argmax_idx.get_shape() == [cfg.batch_size, 1, 1] 65 | 66 | # c). indexing 67 | # It's not easy to understand the indexing process with argmax_idx 68 | # as we are 3-dim animal 69 | masked_v = [] 70 | argmax_idx = tf.reshape(argmax_idx, shape=(cfg.batch_size, )) 71 | for batch_size in range(cfg.batch_size): 72 | v = self.caps2[batch_size][argmax_idx[batch_size], :] 73 | masked_v.append(tf.reshape(v, shape=(1, 1, 16, 1))) 74 | 75 | self.masked_v = tf.concat(masked_v, axis=0) 76 | assert self.masked_v.get_shape() == [cfg.batch_size, 1, 16, 1] 77 | 78 | # 2. Reconstructe the MNIST images with 3 FC layers 79 | # [batch_size, 1, 16, 1] => [batch_size, 16] => [batch_size, 512] 80 | with tf.variable_scope('Decoder'): 81 | vector_j = tf.reshape(self.masked_v, shape=(cfg.batch_size, -1)) 82 | fc1 = tf.contrib.layers.fully_connected(vector_j, num_outputs=512) 83 | assert fc1.get_shape() == [cfg.batch_size, 512] 84 | fc2 = tf.contrib.layers.fully_connected(fc1, num_outputs=1024) 85 | assert fc2.get_shape() == [cfg.batch_size, 1024] 86 | self.decoded = tf.contrib.layers.fully_connected(fc2, num_outputs=784, activation_fn=tf.sigmoid) 87 | 88 | def loss(self): 89 | # 1. The margin loss 90 | 91 | # [batch_size, 10, 1, 1] 92 | # max_l = max(0, m_plus-||v_c||)^2 93 | max_l = tf.square(tf.maximum(0., cfg.m_plus - self.v_length)) 94 | # max_r = max(0, ||v_c||-m_minus)^2 95 | max_r = tf.square(tf.maximum(0., self.v_length - cfg.m_minus)) 96 | assert max_l.get_shape() == [cfg.batch_size, 10, 1, 1] 97 | 98 | # reshape: [batch_size, 10, 1, 1] => [batch_size, 10] 99 | max_l = tf.reshape(max_l, shape=(cfg.batch_size, -1)) 100 | max_r = tf.reshape(max_r, shape=(cfg.batch_size, -1)) 101 | 102 | # calc T_c: [batch_size, 10] 103 | # T_c = Y, is my understanding correct? Try it. 104 | T_c = self.Y 105 | # [batch_size, 10], element-wise multiply 106 | L_c = T_c * max_l + cfg.lambda_val * (1 - T_c) * max_r 107 | 108 | self.margin_loss = tf.reduce_mean(tf.reduce_sum(L_c, axis=1)) 109 | 110 | # 2. The reconstruction loss 111 | orgin = tf.reshape(self.X, shape=(cfg.batch_size, -1)) 112 | squared = tf.square(self.decoded - orgin) 113 | self.reconstruction_err = tf.reduce_mean(squared) 114 | 115 | # 3. Total loss 116 | self.total_loss = self.margin_loss + 0.0005 * self.reconstruction_err 117 | 118 | # Summary 119 | tf.summary.scalar('margin_loss', self.margin_loss) 120 | tf.summary.scalar('reconstruction_loss', self.reconstruction_err) 121 | tf.summary.scalar('total_loss', self.total_loss) 122 | recon_img = tf.reshape(self.decoded, shape=(cfg.batch_size, 28, 28, 1)) 123 | tf.summary.image('reconstruction_img', recon_img) 124 | self.merged_sum = tf.summary.merge_all() 125 | -------------------------------------------------------------------------------- /config.py: -------------------------------------------------------------------------------- 1 | import tensorflow as tf 2 | 3 | flags = tf.app.flags 4 | 5 | 6 | ############################ 7 | # hyper parameters # 8 | ############################ 9 | 10 | # For separate margin loss 11 | flags.DEFINE_float('m_plus', 0.9, 'the parameter of m plus') 12 | flags.DEFINE_float('m_minus', 0.1, 'the parameter of m minus') 13 | flags.DEFINE_float('lambda_val', 0.5, 'down weight of the loss for absent digit classes') 14 | flags.DEFINE_integer('batch_size', 128, 'batch size') 15 | flags.DEFINE_integer('epoch', 500, 'epoch') 16 | flags.DEFINE_integer('iter_routing', 3, 'number of iterations in routing algorithm') 17 | 18 | 19 | ############################ 20 | # environment setting # 21 | ############################ 22 | flags.DEFINE_string('dataset', 'data/mnist', 'the path for dataset') 23 | flags.DEFINE_boolean('is_training', True, 'train or predict phase') 24 | flags.DEFINE_integer('num_threads', 8, 'number of threads of enqueueing exampls') 25 | flags.DEFINE_string('logdir', 'logdir', 'logs directory') 26 | 27 | cfg = tf.app.flags.FLAGS 28 | tf.logging.set_verbosity(tf.logging.INFO) 29 | -------------------------------------------------------------------------------- /eval.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | import tensorflow as tf 3 | 4 | from config import cfg 5 | from utils import load_mnist 6 | from utils import save_images 7 | from capsNet import CapsNet 8 | 9 | 10 | if __name__ == '__main__': 11 | capsNet = CapsNet(is_training=cfg.is_training) 12 | tf.logging.info('Graph loaded') 13 | 14 | teX, teY = load_mnist(cfg.dataset, cfg.is_training) 15 | with capsNet.graph.as_default(): 16 | sv = tf.train.Supervisor(logdir=cfg.logdir) 17 | # with sv.managed_session(config=tf.ConfigProto(allow_soft_placement=True)) as sess: 18 | with sv.managed_session() as sess: 19 | sv.saver.restore(sess, tf.train.latest_checkpoint(cfg.logdir)) 20 | tf.logging.info('Restored') 21 | 22 | reconstruction_err = [] 23 | for i in range(10000 // cfg.batch_size): 24 | start = i * cfg.batch_size 25 | end = start + cfg.batch_size 26 | recon_imgs = sess.run(capsNet.decoded, {capsNet.X: teX[start:end]}) 27 | orgin_imgs = np.reshape(teX[start:end], (cfg.batch_size, -1)) 28 | squared = np.square(recon_imgs - orgin_imgs) 29 | reconstruction_err.append(np.mean(squared)) 30 | 31 | if i % 5 == 0: 32 | imgs = np.reshape(recon_imgs, (cfg.batch_size, 28, 28, 1)) 33 | size = 6 34 | save_images(imgs[0:size * size, :], [size, size], 'results/test_%03d.png' % i) 35 | print('test acc:') 36 | print((1. - np.mean(reconstruction_err)) * 100) 37 | -------------------------------------------------------------------------------- /imgs/margin_loss.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/debarko/CapsNet-Tensorflow/80aa82d4974435a5c3bc268d017922ea539cce30/imgs/margin_loss.png -------------------------------------------------------------------------------- /imgs/my_wechat_QR.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/debarko/CapsNet-Tensorflow/80aa82d4974435a5c3bc268d017922ea539cce30/imgs/my_wechat_QR.png -------------------------------------------------------------------------------- /imgs/reconstruction_loss.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/debarko/CapsNet-Tensorflow/80aa82d4974435a5c3bc268d017922ea539cce30/imgs/reconstruction_loss.png -------------------------------------------------------------------------------- /imgs/total_loss.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/debarko/CapsNet-Tensorflow/80aa82d4974435a5c3bc268d017922ea539cce30/imgs/total_loss.png -------------------------------------------------------------------------------- /imgs/training_loss.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/debarko/CapsNet-Tensorflow/80aa82d4974435a5c3bc268d017922ea539cce30/imgs/training_loss.png -------------------------------------------------------------------------------- /imgs/wechat_group.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/debarko/CapsNet-Tensorflow/80aa82d4974435a5c3bc268d017922ea539cce30/imgs/wechat_group.png -------------------------------------------------------------------------------- /results/test_000.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/debarko/CapsNet-Tensorflow/80aa82d4974435a5c3bc268d017922ea539cce30/results/test_000.png -------------------------------------------------------------------------------- /results/test_005.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/debarko/CapsNet-Tensorflow/80aa82d4974435a5c3bc268d017922ea539cce30/results/test_005.png -------------------------------------------------------------------------------- /results/test_010.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/debarko/CapsNet-Tensorflow/80aa82d4974435a5c3bc268d017922ea539cce30/results/test_010.png -------------------------------------------------------------------------------- /results/test_015.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/debarko/CapsNet-Tensorflow/80aa82d4974435a5c3bc268d017922ea539cce30/results/test_015.png -------------------------------------------------------------------------------- /results/test_020.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/debarko/CapsNet-Tensorflow/80aa82d4974435a5c3bc268d017922ea539cce30/results/test_020.png -------------------------------------------------------------------------------- /results/test_025.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/debarko/CapsNet-Tensorflow/80aa82d4974435a5c3bc268d017922ea539cce30/results/test_025.png -------------------------------------------------------------------------------- /results/test_030.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/debarko/CapsNet-Tensorflow/80aa82d4974435a5c3bc268d017922ea539cce30/results/test_030.png -------------------------------------------------------------------------------- /results/test_035.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/debarko/CapsNet-Tensorflow/80aa82d4974435a5c3bc268d017922ea539cce30/results/test_035.png -------------------------------------------------------------------------------- /results/test_040.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/debarko/CapsNet-Tensorflow/80aa82d4974435a5c3bc268d017922ea539cce30/results/test_040.png -------------------------------------------------------------------------------- /results/test_045.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/debarko/CapsNet-Tensorflow/80aa82d4974435a5c3bc268d017922ea539cce30/results/test_045.png -------------------------------------------------------------------------------- /results/test_050.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/debarko/CapsNet-Tensorflow/80aa82d4974435a5c3bc268d017922ea539cce30/results/test_050.png -------------------------------------------------------------------------------- /results/test_055.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/debarko/CapsNet-Tensorflow/80aa82d4974435a5c3bc268d017922ea539cce30/results/test_055.png -------------------------------------------------------------------------------- /results/test_060.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/debarko/CapsNet-Tensorflow/80aa82d4974435a5c3bc268d017922ea539cce30/results/test_060.png -------------------------------------------------------------------------------- /results/test_065.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/debarko/CapsNet-Tensorflow/80aa82d4974435a5c3bc268d017922ea539cce30/results/test_065.png -------------------------------------------------------------------------------- /results/test_070.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/debarko/CapsNet-Tensorflow/80aa82d4974435a5c3bc268d017922ea539cce30/results/test_070.png -------------------------------------------------------------------------------- /results/test_075.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/debarko/CapsNet-Tensorflow/80aa82d4974435a5c3bc268d017922ea539cce30/results/test_075.png -------------------------------------------------------------------------------- /train.py: -------------------------------------------------------------------------------- 1 | import tensorflow as tf 2 | from tqdm import tqdm 3 | 4 | from config import cfg 5 | from capsNet import CapsNet 6 | 7 | 8 | if __name__ == "__main__": 9 | capsNet = CapsNet(is_training=cfg.is_training) 10 | tf.logging.info('Graph loaded') 11 | sv = tf.train.Supervisor(graph=capsNet.graph, 12 | logdir=cfg.logdir, 13 | save_model_secs=0) 14 | 15 | with sv.managed_session() as sess: 16 | num_batch = int(60000 / cfg.batch_size) 17 | for epoch in range(cfg.epoch): 18 | if sv.should_stop(): 19 | break 20 | for step in tqdm(range(num_batch), total=num_batch, ncols=70, leave=False, unit='b'): 21 | sess.run(capsNet.train_op) 22 | 23 | global_step = sess.run(capsNet.global_step) 24 | sv.saver.save(sess, cfg.logdir + '/model_epoch_%04d_step_%02d' % (epoch, global_step)) 25 | 26 | tf.logging.info('Training done') 27 | -------------------------------------------------------------------------------- /utils.py: -------------------------------------------------------------------------------- 1 | import os 2 | import scipy 3 | import numpy as np 4 | import tensorflow as tf 5 | 6 | from config import cfg 7 | 8 | 9 | def load_mnist(path, is_training): 10 | fd = open(os.path.join(cfg.dataset, 'train-images-idx3-ubyte')) 11 | loaded = np.fromfile(file=fd, dtype=np.uint8) 12 | trX = loaded[16:].reshape((60000, 28, 28, 1)).astype(np.float) 13 | 14 | fd = open(os.path.join(cfg.dataset, 'train-labels-idx1-ubyte')) 15 | loaded = np.fromfile(file=fd, dtype=np.uint8) 16 | trY = loaded[8:].reshape((60000)).astype(np.float) 17 | 18 | fd = open(os.path.join(cfg.dataset, 't10k-images-idx3-ubyte')) 19 | loaded = np.fromfile(file=fd, dtype=np.uint8) 20 | teX = loaded[16:].reshape((10000, 28, 28, 1)).astype(np.float) 21 | 22 | fd = open(os.path.join(cfg.dataset, 't10k-labels-idx1-ubyte')) 23 | loaded = np.fromfile(file=fd, dtype=np.uint8) 24 | teY = loaded[8:].reshape((10000)).astype(np.float) 25 | 26 | # normalization and convert to a tensor [60000, 28, 28, 1] 27 | trX = tf.convert_to_tensor(trX / 255., tf.float32) 28 | 29 | # => [num_samples, 10] 30 | trY = tf.one_hot(trY, depth=10, axis=1, dtype=tf.float32) 31 | teY = tf.one_hot(teY, depth=10, axis=1, dtype=tf.float32) 32 | 33 | if is_training: 34 | return trX, trY 35 | else: 36 | return teX / 255., teY 37 | 38 | 39 | def get_batch_data(): 40 | trX, trY = load_mnist(cfg.dataset, cfg.is_training) 41 | 42 | data_queues = tf.train.slice_input_producer([trX, trY]) 43 | X, Y = tf.train.shuffle_batch(data_queues, num_threads=cfg.num_threads, 44 | batch_size=cfg.batch_size, 45 | capacity=cfg.batch_size * 64, 46 | min_after_dequeue=cfg.batch_size * 32, 47 | allow_smaller_final_batch=False) 48 | 49 | return(X, Y) 50 | 51 | 52 | def save_images(imgs, size, path): 53 | ''' 54 | Args: 55 | imgs: [batch_size, image_height, image_width] 56 | size: a list with tow int elements, [image_height, image_width] 57 | path: the path to save images 58 | ''' 59 | imgs = (imgs + 1.) / 2 # inverse_transform 60 | return(scipy.misc.imsave(path, mergeImgs(imgs, size))) 61 | 62 | 63 | def mergeImgs(images, size): 64 | h, w = images.shape[1], images.shape[2] 65 | imgs = np.zeros((h * size[0], w * size[1], 3)) 66 | for idx, image in enumerate(images): 67 | i = idx % size[1] 68 | j = idx // size[1] 69 | imgs[j * h:j * h + h, i * w:i * w + w, :] = image 70 | 71 | return imgs 72 | 73 | 74 | if __name__ == '__main__': 75 | X, Y = load_mnist(cfg.dataset, cfg.is_training) 76 | print(X.get_shape()) 77 | print(X.dtype) 78 | --------------------------------------------------------------------------------