├── .gitignore ├── CapsLayers.py ├── CapsNet.py ├── LICENSE ├── README.md ├── data ├── t10k-images-idx3-ubyte.gz ├── t10k-labels-idx1-ubyte.gz ├── train-images-idx3-ubyte.gz └── train-labels-idx1-ubyte.gz ├── test_mxnet_function.ipynb ├── test_net.py └── utils.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 | -------------------------------------------------------------------------------- /CapsLayers.py: -------------------------------------------------------------------------------- 1 | from mxnet import nd 2 | from mxnet.gluon import nn,Parameter 3 | from mxnet import init 4 | from mxnet import cpu 5 | from mxnet.gluon.loss import Loss, L2Loss, _apply_weighting 6 | 7 | 8 | 9 | 10 | 11 | class PrimaryConv(nn.Block): 12 | def __init__(self,dim_vector,n_channels,kernel_size,padding,context=cpu,strides=(1,1),**kwargs): 13 | super(PrimaryConv, self).__init__(**kwargs) 14 | 15 | 16 | self.dim_vector = dim_vector 17 | self.n_channels= n_channels 18 | # self.conv_vector = nn.Conv2D(channels=dim_vector, kernel_size=kernel_size,strides=strides,padding=padding,activation='relu') 19 | 20 | # self.caps = [self.conv_vector for x in range(self.n_channels)] 21 | 22 | self.batch_size = 0 23 | 24 | self.capsules_index = ['dim_'+str(i) for i in range(n_channels)] 25 | 26 | for idx in self.capsules_index: 27 | setattr(self, idx, nn.Conv2D(channels=dim_vector, 28 | kernel_size=kernel_size, strides=strides, 29 | padding=padding,activation='relu')) 30 | 31 | 32 | def reshape_conv(self,conv_vector): 33 | return nd.reshape(conv_vector,shape=(self.batch_size, self.dim_vector,-1)) 34 | 35 | 36 | def concat_outputs(self,conv_list,axis): 37 | 38 | concat_vec = conv_list[0] 39 | # print(concat_vec.shape) 40 | concat_vec = self.reshape_conv(concat_vec) 41 | for i in range(1, len(conv_list)): 42 | concat_vec = nd.concat(concat_vec, self.reshape_conv(conv_list[i]), dim=axis) 43 | 44 | return concat_vec 45 | 46 | def squash(self,vectors,axis): 47 | epsilon = 1e-9 48 | vectors_l2norm = nd.square(vectors).sum(axis=axis,keepdims=True)#.expand_dims(axis=axis) 49 | 50 | scale_factor = vectors_l2norm / (1 + vectors_l2norm) 51 | vectors_squashed = scale_factor * (vectors / nd.sqrt(vectors_l2norm+epsilon)) # element-wise 52 | 53 | return vectors_squashed 54 | 55 | def forward(self, x): 56 | 57 | self.batch_size = x.shape[0] 58 | 59 | conv_list = [getattr(self,idx)(x).expand_dims(axis=-1) for idx in self.capsules_index] 60 | 61 | # conv_list = [ self.conv_vector(x) for i in range(self.n_channels)] 62 | 63 | outputs = self.concat_outputs(conv_list,axis=2) 64 | assert outputs.shape == (self.batch_size, 8, 1152) 65 | 66 | v_primary = self.squash(outputs,axis=1) 67 | assert outputs.shape == (self.batch_size, 8, 1152) 68 | 69 | return outputs 70 | 71 | 72 | class DigitCaps(nn.Block): 73 | def __init__(self,num_capsule,dim_vector,context=cpu,iter_routing=1,**kwargs): 74 | super(DigitCaps, self).__init__(**kwargs) 75 | self.num_capsule = num_capsule #10 76 | self.dim_vector = dim_vector #16 77 | 78 | self.iter_routing = iter_routing #3 79 | 80 | self.batch_size = 1 81 | self.input_num_capsule = 1152 82 | self.input_dim_vector = 8 83 | self.context = context 84 | 85 | self.routing_weight_initial = True 86 | 87 | if self.routing_weight_initial: 88 | self.routing_weight = nd.random_normal(shape=( 89 | 1, 90 | self.input_num_capsule, 91 | self.num_capsule, 92 | self.input_dim_vector, 93 | self.dim_vector), name='routing_weight').as_in_context(self.context) 94 | self.routing_weight_initial = False 95 | 96 | self.routing_weight.attach_grad() 97 | 98 | # (1, 1152, 10, 8, 16) 99 | self.W_ij = self.params.get( 100 | 'weight',shape=( 101 | 1, 102 | self.input_num_capsule, 103 | self.num_capsule, 104 | self.input_dim_vector, 105 | self.dim_vector 106 | )) 107 | 108 | def squash(self,vectors,axis): 109 | epsilon = 1e-9 110 | vectors_l2norm = nd.square(vectors).sum(axis=axis,keepdims=True) 111 | 112 | assert vectors_l2norm.shape == (self.batch_size, 1, self.num_capsule, 1, 1) # 1,10,1,1 113 | 114 | scale_factor = vectors_l2norm / (1 + vectors_l2norm) 115 | vectors_squashed = scale_factor * (vectors / nd.sqrt(vectors_l2norm+epsilon)) # element-wise 116 | 117 | return vectors_squashed 118 | 119 | 120 | def forward(self, x): 121 | 122 | self.batch_size, self.input_dim_vector, self.input_num_capsule = x.shape 123 | 124 | assert (self.batch_size, self.input_dim_vector, self.input_num_capsule) == (self.batch_size,8,1152) 125 | 126 | x_exp = x.expand_dims(axis=1) 127 | x_exp = x_exp.expand_dims(axis=4) 128 | assert x_exp.shape == (self.batch_size, 1, 8, 1152, 1) 129 | 130 | 131 | x_tile = x_exp.tile(reps=[1, self.num_capsule, 1, 1, 1]) 132 | assert x_tile.shape == (self.batch_size,10, 8, 1152, 1) 133 | 134 | 135 | x_trans = x_tile.transpose(axes=(0,3,1,2,4)) 136 | assert x_trans.shape == (self.batch_size, 1152, 10, 8,1) 137 | 138 | # W = self.W_ij.data() 139 | print(self.W_ij.data()[0,0,0,0]) 140 | # W = self.routing_weight 141 | # print('W',W[0,0,0,0]) 142 | 143 | W = self.W_ij.data().tile(reps=[self.batch_size,1,1,1,1]) 144 | 145 | assert W.shape == (self.batch_size, 1152, 10, 8, 16) 146 | 147 | 148 | # [8, 16].T x [8, 1] => [16, 1] 149 | x_dot = x_trans.reshape(shape=(-1,self.input_dim_vector,1))#(8,1) 150 | W_dot = W.reshape(shape=(-1,self.input_dim_vector,self.dim_vector))#(8,16) 151 | 152 | 153 | u_hat = nd.batch_dot(W_dot,x_dot,transpose_a=True) 154 | 155 | u_hat = u_hat.reshape(shape=(self.batch_size,self.input_num_capsule,self.num_capsule,self.dim_vector,-1)) 156 | assert u_hat.shape == (self.batch_size, 1152, 10, 16, 1) 157 | 158 | 159 | b_IJ = nd.zeros((self.batch_size, self.input_num_capsule,self.num_capsule,1,1),ctx=self.context) 160 | 161 | assert b_IJ.shape == ((self.batch_size,1152,10,1,1)) 162 | 163 | u_hat_stopped = nd.stop_gradient(u_hat, name='stop_gradient') 164 | 165 | 166 | for r_iter in range(self.iter_routing): 167 | c_IJ = nd.softmax(b_IJ, axis=2) 168 | 169 | s_J = nd.multiply(c_IJ, u_hat) 170 | s_J = s_J.sum(axis=1,keepdims=True) 171 | # print('s_J',s_J[0,0,0]) 172 | 173 | assert s_J.shape == (self.batch_size, 1, 10, 16, 1) 174 | 175 | v_J = self.squash(s_J,axis=3) 176 | 177 | assert v_J.shape == (self.batch_size, 1, 10, 16, 1) 178 | 179 | v_J_tiled = v_J.tile(reps=[1, 1152, 1, 1, 1]) 180 | 181 | if self.iter_routing > 1: 182 | # u_hat_stopped (self.batch_size, 1152, 10, 16, 1) 183 | # v_J_tiled (self.batch_size, 1152, 10, 16, 1) 184 | # u_hat_stopped = u_hat_stopped.reshape(shape=(-1,self.dim_vector,1)) 185 | # v_J_tiled = v_J_tiled.reshape(shape=(-1,self.dim_vector,1)) 186 | # 187 | u_produce_v = nd.stop_gradient(nd.multiply(u_hat_stopped, v_J_tiled, transpose_a=True)) 188 | 189 | # u_produce_v = u_produce_v.reshape(shape=(self.batch_size, self.input_num_capsule, self.num_capsule, 1, 1)) 190 | assert u_produce_v.shape == (self.batch_size, 1152, 10, 1, 1) 191 | 192 | b_IJ = nd.stop_gradient(b_IJ+u_produce_v, name ="update_b_IJ" ) 193 | 194 | #(batch_size,1,10,16,1) 195 | assert v_J.shape == (self.batch_size,1,self.num_capsule,self.dim_vector,1) 196 | # print('v_J',v_J[0,0,0,0]) 197 | return v_J 198 | 199 | 200 | 201 | class Length(nn.Block): 202 | def __init__(self, **kwargs): 203 | super(Length, self).__init__(**kwargs) 204 | 205 | def forward(self, x): 206 | #(batch_size, 1, 10, 16, 1) =>(batch_size,10, 16)=> (batch_size, 10, 1) 207 | x_shape = x.shape 208 | x = x.reshape(shape=(x_shape[0],x_shape[2],x_shape[3])) 209 | 210 | x_l2norm = nd.sqrt((x.square()).sum(axis=-1)) 211 | # prob = nd.softmax(x_l2norm, axis=-1) 212 | return x_l2norm 213 | 214 | class CapsuleMarginLoss(Loss): 215 | """Calculates margin loss for CapsuleNet between output and label: 216 | 217 | .. math:: 218 | 219 | 220 | Output and label can have arbitrary shape as long as they have the same 221 | number of elements. 222 | 223 | Parameters 224 | ---------- 225 | weight : float or None 226 | Global scalar weight for loss. 227 | sample_weight : Symbol or None 228 | Per sample weighting. Must be broadcastable to 229 | the same shape as loss. For example, if loss has 230 | shape (64, 10) and you want to weight each sample 231 | in the batch, `sample_weight` should have shape (64, 1). 232 | batch_axis : int, default 0 233 | The axis that represents mini-batch. 234 | """ 235 | def __init__(self, weight=1., batch_axis=0, num_classes=10, sample_weight=None, **kwargs): 236 | super(CapsuleMarginLoss, self).__init__(weight, batch_axis, **kwargs) 237 | self.lambda_value = 0.5 238 | self.num_classes = num_classes 239 | self.sample_weight = sample_weight 240 | 241 | def forward(self,labels,y_pred): 242 | 243 | labels_onehot = labels #nd.one_hot(labels, self.num_classes) 244 | 245 | 246 | first_term_base = nd.square(nd.maximum(0.9-y_pred,0)) 247 | second_term_base = nd.square(nd.maximum(y_pred -0.1, 0)) 248 | # import pdb; pdb.set_trace() 249 | margin_loss = labels_onehot * first_term_base + self.lambda_value * (1-labels_onehot) * second_term_base 250 | margin_loss = margin_loss.sum(axis=1) 251 | 252 | loss = nd.mean(margin_loss, axis=self._batch_axis, exclude=True) 253 | loss = _apply_weighting(nd, loss, self._weight/2, self.sample_weight) 254 | return nd.mean(loss, axis=self._batch_axis, exclude=True) 255 | 256 | 257 | -------------------------------------------------------------------------------- /CapsNet.py: -------------------------------------------------------------------------------- 1 | """ 2 | MxNet implementation of CapsNet in Hinton's paper Dynamic Routing Between Capsules. 3 | 4 | Usage: 5 | python CapsNet.py 6 | 7 | Result: 8 | 9 | """ 10 | import mxnet as mx 11 | from mxnet import init 12 | from mxnet import nd 13 | from mxnet.gluon import nn,Trainer 14 | from CapsLayers import DigitCaps, PrimaryConv, Length, CapsuleMarginLoss 15 | from mxnet.gluon.loss import L2Loss 16 | import utils 17 | 18 | 19 | 20 | def CapsNet(batch_size, ctx): 21 | 22 | net = nn.Sequential() 23 | with net.name_scope(): 24 | 25 | net.add(nn.Conv2D(channels=256, kernel_size=9, strides=1, padding=(0,0), activation='relu')) 26 | net.add(PrimaryConv(dim_vector=8, n_channels=32, kernel_size=9, strides=2, context=ctx, padding=(0,0))) 27 | net.add(DigitCaps(num_capsule=10, dim_vector=16, context=ctx)) 28 | net.add(Length()) 29 | 30 | net.initialize(ctx=ctx, init=init.Xavier()) 31 | return net 32 | 33 | 34 | 35 | def loss(y_pred,y_true): 36 | 37 | L = y_true * nd.square(nd.maximum(0., 0.9 - y_pred)) + \ 38 | 0.5 * (1 - y_true) * nd.square(nd.maximum(0., y_pred - 0.1)) 39 | 40 | return nd.mean(nd.sum(L, 1)) 41 | 42 | 43 | if __name__ == "__main__": 44 | # setting the hyper parameters 45 | import argparse 46 | parser = argparse.ArgumentParser() 47 | parser.add_argument('--batch_size', default=16, type=int) 48 | parser.add_argument('--epochs', default=1, type=int) 49 | parser.add_argument('--train', default=False, type=bool) 50 | args = parser.parse_args() 51 | print(args) 52 | 53 | ctx = utils.try_gpu() 54 | # ctx = mx.cpu() 55 | 56 | train_data, test_data = utils.load_data_mnist(batch_size=args.batch_size,resize=28) 57 | 58 | net = CapsNet(batch_size=args.batch_size,ctx=ctx) 59 | margin_loss = CapsuleMarginLoss() 60 | 61 | print('====================================net====================================') 62 | print(net) 63 | 64 | if args.train: 65 | print('====================================train====================================') 66 | 67 | trainer = Trainer(net.collect_params(),'adam', {'learning_rate': 0.01}) 68 | 69 | utils.train(train_data, test_data, net, margin_loss, trainer, ctx, num_epochs=args.epochs) 70 | -------------------------------------------------------------------------------- /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-Mxnet 2 | 3 | A Mxnet implementation of CapsNet in Hinton's paper [Dynamic Routing Between Capsules](https://arxiv.org/abs/1710.09829) 4 | 5 | 6 | ## Requirements 7 | - [Mxnet](https://github.com/apache/incubator-mxnet) 8 | 9 | ## Usage 10 | 11 | ### Training 12 | **Step 1.** 13 | Install Mxnet: 14 | 15 | `$ pip install mxnet` 16 | 17 | **Step 2.** 18 | Clone this repository with ``git``. 19 | 20 | ``` 21 | $ git clone https://github.com/AaronLeong/CapsNet_Mxnet.git 22 | $ cd CapsNet_Mxnet 23 | ``` 24 | 25 | **Step 3.** 26 | Training: 27 | ``` 28 | $ python CapsNet.py 29 | ``` 30 | 31 | ## Results 32 | 33 | Maybe there're some problems in my implementation. Contributions are welcome. 34 | 35 | ## TODO: 36 | - Add reconstruction part, which should be easy. 37 | - Optimize the code implementation and comments 38 | 39 | ## Other Implementations 40 | - [CapsNet-Keras](https://github.com/naturomics/XifengGuo/CapsNet-Keras.git): 41 | Very good implementation. I referred to this repository in my code. 42 | 43 | - [CapsNet-Tensorflow](https://github.com/naturomics/CapsNet-Tensorflow.git) 44 | 45 | - [CapsNet-PyTorch](https://github.com/nishnik/CapsNet-PyTorch.git) 46 | 47 | - [capsnet.pytorch](https://github.com/andreaazzini/capsnet.pytorch.git) 48 | -------------------------------------------------------------------------------- /data/t10k-images-idx3-ubyte.gz: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sxhxliang/CapsNet_Mxnet/95803cc3e83df346fba66d0390326d91b3d89586/data/t10k-images-idx3-ubyte.gz -------------------------------------------------------------------------------- /data/t10k-labels-idx1-ubyte.gz: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sxhxliang/CapsNet_Mxnet/95803cc3e83df346fba66d0390326d91b3d89586/data/t10k-labels-idx1-ubyte.gz -------------------------------------------------------------------------------- /data/train-images-idx3-ubyte.gz: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sxhxliang/CapsNet_Mxnet/95803cc3e83df346fba66d0390326d91b3d89586/data/train-images-idx3-ubyte.gz -------------------------------------------------------------------------------- /data/train-labels-idx1-ubyte.gz: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sxhxliang/CapsNet_Mxnet/95803cc3e83df346fba66d0390326d91b3d89586/data/train-labels-idx1-ubyte.gz -------------------------------------------------------------------------------- /test_mxnet_function.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "code", 5 | "execution_count": 22, 6 | "metadata": { 7 | "ExecuteTime": { 8 | "end_time": "2017-11-02T08:42:32.105937Z", 9 | "start_time": "2017-11-02T08:42:32.101557Z" 10 | }, 11 | "collapsed": true 12 | }, 13 | "outputs": [], 14 | "source": [ 15 | "import mxnet as mx\n", 16 | "from mxnet import nd" 17 | ] 18 | }, 19 | { 20 | "cell_type": "code", 21 | "execution_count": 26, 22 | "metadata": { 23 | "ExecuteTime": { 24 | "end_time": "2017-11-02T08:45:34.568006Z", 25 | "start_time": "2017-11-02T08:45:34.561268Z" 26 | }, 27 | "collapsed": true 28 | }, 29 | "outputs": [], 30 | "source": [ 31 | "w = nd.ones(shape=(1,6,6,32,8,10,16))\n", 32 | "x = nd.ones(shape=(1,6,6,32,8,1,1))\n", 33 | "b = nd.ones(shape=(1,6,6,32,1,10,1))" 34 | ] 35 | }, 36 | { 37 | "cell_type": "code", 38 | "execution_count": 27, 39 | "metadata": { 40 | "ExecuteTime": { 41 | "end_time": "2017-11-02T08:45:43.110594Z", 42 | "start_time": "2017-11-02T08:45:43.102675Z" 43 | } 44 | }, 45 | "outputs": [ 46 | { 47 | "data": { 48 | "text/plain": [ 49 | "(1, 6, 6, 32, 8, 10, 16)" 50 | ] 51 | }, 52 | "execution_count": 27, 53 | "metadata": {}, 54 | "output_type": "execute_result" 55 | } 56 | ], 57 | "source": [ 58 | "y = x*w\n", 59 | "y.shape" 60 | ] 61 | }, 62 | { 63 | "cell_type": "code", 64 | "execution_count": 29, 65 | "metadata": { 66 | "ExecuteTime": { 67 | "end_time": "2017-11-02T08:46:52.704751Z", 68 | "start_time": "2017-11-02T08:46:52.696586Z" 69 | } 70 | }, 71 | "outputs": [ 72 | { 73 | "data": { 74 | "text/plain": [ 75 | "(1, 6, 6, 32, 8, 10, 1)" 76 | ] 77 | }, 78 | "execution_count": 29, 79 | "metadata": {}, 80 | "output_type": "execute_result" 81 | } 82 | ], 83 | "source": [ 84 | "z = x*b\n", 85 | "z.shape" 86 | ] 87 | }, 88 | { 89 | "cell_type": "code", 90 | "execution_count": 30, 91 | "metadata": { 92 | "ExecuteTime": { 93 | "end_time": "2017-11-02T10:38:36.186617Z", 94 | "start_time": "2017-11-02T10:38:36.141115Z" 95 | } 96 | }, 97 | "outputs": [ 98 | { 99 | "ename": "AttributeError", 100 | "evalue": "'NDArray' object has no attribute 'argmax'", 101 | "output_type": "error", 102 | "traceback": [ 103 | "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", 104 | "\u001b[0;31mAttributeError\u001b[0m Traceback (most recent call last)", 105 | "\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m()\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0mz\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0margmax\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", 106 | "\u001b[0;31mAttributeError\u001b[0m: 'NDArray' object has no attribute 'argmax'" 107 | ] 108 | } 109 | ], 110 | "source": [ 111 | "z.argmax" 112 | ] 113 | }, 114 | { 115 | "cell_type": "code", 116 | "execution_count": null, 117 | "metadata": { 118 | "collapsed": true 119 | }, 120 | "outputs": [], 121 | "source": [] 122 | } 123 | ], 124 | "metadata": { 125 | "kernelspec": { 126 | "display_name": "Python 3", 127 | "language": "python", 128 | "name": "python3" 129 | }, 130 | "language_info": { 131 | "codemirror_mode": { 132 | "name": "ipython", 133 | "version": 3 134 | }, 135 | "file_extension": ".py", 136 | "mimetype": "text/x-python", 137 | "name": "python", 138 | "nbconvert_exporter": "python", 139 | "pygments_lexer": "ipython3", 140 | "version": "3.5.2" 141 | } 142 | }, 143 | "nbformat": 4, 144 | "nbformat_minor": 2 145 | } 146 | -------------------------------------------------------------------------------- /test_net.py: -------------------------------------------------------------------------------- 1 | import mxnet as mx 2 | from mxnet import init 3 | from mxnet import nd 4 | from mxnet import autograd 5 | from mxnet.gluon import nn,Trainer,loss 6 | from CapsLayers import DigitCaps, PrimaryConv, Length 7 | import utils 8 | 9 | net = nn.Sequential() 10 | batch_size =2 11 | ctx = utils.try_gpu() 12 | 13 | 14 | net.add(nn.Conv2D(channels=256, kernel_size=9, strides=1, padding=(0,0), activation='relu')) 15 | net.add(PrimaryConv(dim_vector=8, n_channels=32, kernel_size=9, strides=2, context=ctx, padding=(0,0))) 16 | net.add(DigitCaps(num_capsule=10, dim_vector=16, context=ctx)) 17 | net.add(Length()) 18 | 19 | net.initialize(ctx=ctx) 20 | 21 | # net.collect_params().initialize(ctx=ctx) 22 | 23 | 24 | 25 | 26 | 27 | 28 | # train_data, test_data = utils.load_data_mnist(batch_size=2,resize=20) 29 | 30 | 31 | # for data, label in train_data: 32 | # break 33 | data = nd.random_normal(shape=(2,1,28,28),ctx=ctx) 34 | with autograd.record(): 35 | output = net(data) 36 | 37 | 38 | print('output',output) 39 | 40 | print(net.collect_params()) 41 | 42 | 43 | -------------------------------------------------------------------------------- /utils.py: -------------------------------------------------------------------------------- 1 | from mxnet import gluon 2 | from mxnet import autograd 3 | from mxnet import nd 4 | from mxnet import image 5 | import mxnet as mx 6 | from tqdm import tqdm 7 | 8 | def load_data_fashion_mnist(batch_size, resize=None): 9 | """download the fashion mnist dataest and then load into memory""" 10 | def transform_mnist(data, label): 11 | if resize: 12 | # resize to resize x resize 13 | data = image.imresize(data, resize, resize) 14 | # change data from height x weight x channel to channel x height x weight 15 | return nd.transpose(data.astype('float32'), (2,0,1))/255, label.astype('float32') 16 | mnist_train = gluon.data.vision.FashionMNIST(root='./data', 17 | train=True, transform=transform_mnist) 18 | mnist_test = gluon.data.vision.FashionMNIST(root='./data', 19 | train=False, transform=transform_mnist) 20 | train_data = gluon.data.DataLoader( 21 | mnist_train, batch_size, shuffle=True) 22 | test_data = gluon.data.DataLoader( 23 | mnist_test, batch_size, shuffle=False) 24 | return (train_data, test_data) 25 | 26 | def load_data_mnist(batch_size, resize=None): 27 | """download the fashion mnist dataest and then load into memory""" 28 | def transform_mnist(data, label): 29 | if resize: 30 | # resize to resize x resize 31 | data = image.imresize(data, resize, resize) 32 | # change data from height x weight x channel to channel x height x weight 33 | return nd.transpose(data.astype('float32'), (2,0,1))/255, label.astype('float32') 34 | mnist_train = gluon.data.vision.MNIST(root='./data', 35 | train=True, transform=transform_mnist) 36 | mnist_test = gluon.data.vision.MNIST(root='./data', 37 | train=False, transform=transform_mnist) 38 | train_data = gluon.data.DataLoader( 39 | mnist_train, batch_size, shuffle=True) 40 | test_data = gluon.data.DataLoader( 41 | mnist_test, batch_size, shuffle=False) 42 | return (train_data, test_data) 43 | 44 | 45 | def try_gpu(): 46 | """If GPU is available, return mx.gpu(0); else return mx.cpu()""" 47 | try: 48 | ctx = mx.gpu() 49 | _ = nd.zeros((1,), ctx=ctx) 50 | except: 51 | ctx = mx.cpu() 52 | return ctx 53 | 54 | def SGD(params, lr): 55 | for param in params: 56 | param[:] = param - lr * param.grad 57 | 58 | def accuracy(output, label): 59 | # print('accuracy',output, label) 60 | return nd.mean(nd.argmax(output,axis=1)==label).asscalar() 61 | 62 | def _get_batch(batch, ctx): 63 | """return data and label on ctx""" 64 | if isinstance(batch, mx.io.DataBatch): 65 | data = batch.data[0] 66 | label = batch.label[0] 67 | else: 68 | data, label = batch 69 | return data.as_in_context(ctx), label.as_in_context(ctx) 70 | 71 | 72 | 73 | def evaluate_accuracy(data_iterator, net, ctx=mx.cpu()): 74 | acc = 0. 75 | if isinstance(data_iterator, mx.io.MXDataIter): 76 | data_iterator.reset() 77 | for i, batch in enumerate(data_iterator): 78 | data, label = _get_batch(batch, ctx) 79 | output = net(data) 80 | print(output) 81 | acc += accuracy(output, label) 82 | 83 | return acc / (i+1) 84 | 85 | def train(train_data, test_data, net, loss, trainer, ctx, num_epochs, print_batches=100): 86 | """Train a network""" 87 | for epoch in range(num_epochs): 88 | train_loss = 0. 89 | train_acc = 0. 90 | n = 0 91 | for i, (data, label) in tqdm(enumerate(train_data), total=len(train_data), ncols=70, leave=False, unit='b'): 92 | # for i, batch in enumerate(train_data): 93 | # data, label = batch 94 | one_hot_label = nd.one_hot(label,10) 95 | 96 | label = label.as_in_context(ctx) 97 | one_hot_label = one_hot_label.as_in_context(ctx) 98 | data = data.as_in_context(ctx) 99 | 100 | with autograd.record(): 101 | output = net(data) 102 | L = loss(output, one_hot_label) 103 | 104 | L.backward() 105 | 106 | trainer.step(data.shape[0]) 107 | 108 | train_loss += nd.mean(L).asscalar() 109 | # print('nd.mean(L).asscalar()',nd.mean(L).asscalar()) 110 | 111 | train_acc += accuracy(output, label) 112 | 113 | n = i + 1 114 | if print_batches and n % print_batches == 0: 115 | print('output',output) 116 | print("Batch %d. Loss: %f, Train acc %f" % ( 117 | n, train_loss/n, train_acc/n 118 | )) 119 | # print('train_loss',train_loss) 120 | test_acc = evaluate_accuracy(test_data, net, ctx) 121 | print("Epoch %d. Loss: %f, Train acc %f, Test acc %f" % ( 122 | epoch, train_loss/n, train_acc/n, test_acc 123 | )) 124 | --------------------------------------------------------------------------------