Capsule Tutorial(WIP).ipynb 8.92 KB
Newer Older
VoVAllen's avatar
VoVAllen committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Capsule Network\n",
    "================\n",
    "**Author**: `Jinjing Zhou`\n",
    "\n",
    "This tutorial explains how to use DGL library and its language to implement the [capsule network](http://arxiv.org/abs/1710.09829) proposed by Geoffrey Hinton and his team. The algorithm aims to provide a better alternative to current neural network structures. By using DGL library, users can implement the algorithm in a more intuitive way."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Model Overview\n",
    "\n",
    "### Introduction\n",
VoVAllen's avatar
VoVAllen committed
21
    "Capsule Network were first introduced in 2011 by Geoffrey Hinton, et al., in a paper called [Transforming Autoencoders](https://www.cs.toronto.edu/~fritz/absps/transauto6.pdf), but it was only a few months ago, in November 2017, that Sara Sabour, Nicholas Frosst, and Geoffrey Hinton published a paper called Dynamic Routing between Capsules, where they introduced a CapsNet architecture that reached state-of-the-art performance on MNIST.\n",
VoVAllen's avatar
VoVAllen committed
22
23
24
25
    "\n",
    "### What's a capsule?\n",
    "> A capsule is a group of neurons whose activity vector represents the instantiation parameters of a specific type of entity such as an object or an object part.    \n",
    "\n",
VoVAllen's avatar
VoVAllen committed
26
    "Generally Speaking, the idea of capsule is to encode all the information about the features into a vector form, by substituting scalars in traditional neural network with vectors. And use the norm of the vector to represents the meaning of original scalars. \n",
VoVAllen's avatar
VoVAllen committed
27
28
29
    "![figure_1](./capsule_f1.png)\n",
    "\n",
    "### Dynamic Routing Algorithm\n",
VoVAllen's avatar
VoVAllen committed
30
31
32
33
    "Due to the different structure of network, capsules network has different operations to calculate results. This figure shows the comparison, drawn by [Max Pechyonkin](https://medium.com/ai%C2%B3-theory-practice-business/understanding-hintons-capsule-networks-part-ii-how-capsules-work-153b6ade9f66O).   \n",
    "<img src=\"./capsule_f2.png\" style=\"height:250px;\"/><br/>\n",
    "\n",
    "The key idea is that the output of each capsule is the sum of weighted input vectors. We will go into details in the later section with code implementations.\n"
VoVAllen's avatar
VoVAllen committed
34
35
36
37
38
39
40
41
42
43
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Model Implementations\n",
    "\n",
    "### 1. Consider capsule routing  as a graph structure\n",
    "\n",
VoVAllen's avatar
VoVAllen committed
44
    "We can consider each capsule as a node in a graph, and connect all the nodes between layers.\n",
VoVAllen's avatar
VoVAllen committed
45
46
47
48
49
50
51
52
53
54
55
    "<img src=\"./capsule_f3.png\" style=\"height:200px;\"/>"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def construct_graph(self):\n",
    "    g = dgl.DGLGraph()\n",
VoVAllen's avatar
VoVAllen committed
56
57
58
    "    g.add_nodes(self.input_capsule_num + self.output_capsule_num)\n",
    "    input_nodes = list(range(self.input_capsule_num))\n",
    "    output_nodes = list(range(self.input_capsule_num, self.input_capsule_num + self.output_capsule_num))\n",
VoVAllen's avatar
VoVAllen committed
59
    "    u, v = [], []\n",
VoVAllen's avatar
VoVAllen committed
60
61
    "    for i in input_nodes:\n",
    "        for j in output_nodes:\n",
VoVAllen's avatar
VoVAllen committed
62
63
64
    "            u.append(i)\n",
    "            v.append(j)\n",
    "    g.add_edges(u, v)\n",
VoVAllen's avatar
VoVAllen committed
65
    "    return g, input_nodes, output_nodes"
VoVAllen's avatar
VoVAllen committed
66
67
68
69
70
71
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
VoVAllen's avatar
VoVAllen committed
72
73
74
    "### 2. Initialization & Affine Transformation\n",
    "- Pre-compute $\\hat{u}_{j|i}$, initialize $b_{ij}$ and store them as edge attribute\n",
    "- Initialize node features as zero\n",
VoVAllen's avatar
VoVAllen committed
75
76
77
78
79
80
81
82
83
    "<img src=\"./capsule_f4.png\" style=\"height:200px;\"/>"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
VoVAllen's avatar
VoVAllen committed
84
85
    "# x is the input vextor with shape [batch_size, input_capsule_dim, input_num]\n",
    "# Transpose x to [batch_size, input_num, input_capsule_dim]        \n",
VoVAllen's avatar
VoVAllen committed
86
    "x = x.transpose(1, 2)\n",
VoVAllen's avatar
VoVAllen committed
87
88
89
90
91
92
    "# Expand x to [batch_size, input_num, output_num, input_capsule_dim, 1]\n",
    "x = torch.stack([x] * self.output_capsule_num, dim=2).unsqueeze(4)\n",
    "# Expand W from [input_num, output_num, input_capsule_dim, output_capsule_dim] \n",
    "# to [batch_size, input_num, output_num, output_capsule_dim, input_capsule_dim] \n",
    "W = self.weight.expand(self.batch_size, *self.weight.size())\n",
    "# u_hat's shape is [input_num, output_num, batch_size, output_capsule_dim]\n",
VoVAllen's avatar
VoVAllen committed
93
    "u_hat = torch.matmul(W, x).permute(1, 2, 0, 3, 4).squeeze().contiguous()\n",
VoVAllen's avatar
VoVAllen committed
94
95
96
97
98
99
100
101
102
103
    "\n",
    "b_ij = torch.zeros(self.input_capsule_num, self.output_capsule_num).to(self.device)\n",
    "\n",
    "self.g.set_e_repr({'b_ij': b_ij.view(-1)})\n",
    "self.g.set_e_repr({'u_hat': u_hat.view(-1, self.batch_size, self.unit_size)})\n",
    "\n",
    "# Initialize all node features as zero\n",
    "node_features = torch.zeros(self.input_capsule_num + self.output_capsule_num, self.batch_size,\n",
    "                            self.output_capsule_dim).to(self.device)\n",
    "self.g.set_n_repr({'h': node_features})"
VoVAllen's avatar
VoVAllen committed
104
105
106
107
108
109
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
VoVAllen's avatar
VoVAllen committed
110
111
112
113
114
115
116
117
118
119
    "### 3. Write Message Passing functions and Squash function"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 3.1 Squash function\n",
    "Squashing function is to ensure that short vectors get shrunk to almost zero length and long vectors get shrunk to a length slightly below 1.\n",
    "![squash](./squash.png)"
VoVAllen's avatar
VoVAllen committed
120
121
122
123
   ]
  },
  {
   "cell_type": "code",
VoVAllen's avatar
VoVAllen committed
124
   "execution_count": 6,
VoVAllen's avatar
VoVAllen committed
125
126
127
   "metadata": {},
   "outputs": [],
   "source": [
VoVAllen's avatar
VoVAllen committed
128
129
130
131
132
    "def squash(s):\n",
    "    msg_sq = torch.sum(s ** 2, dim=2, keepdim=True)\n",
    "    msg = torch.sqrt(msg_sq)\n",
    "    s = (msg_sq / (1.0 + msg_sq)) * (s / msg)\n",
    "    return s"
VoVAllen's avatar
VoVAllen committed
133
134
135
136
137
138
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
VoVAllen's avatar
VoVAllen committed
139
140
    "#### 3.2 Message Functions\n",
    "At first stage, we need to define a message function to get all the attributes we need in the further computations."
VoVAllen's avatar
VoVAllen committed
141
142
143
144
145
146
147
148
149
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def capsule_msg(src, edge):\n",
VoVAllen's avatar
VoVAllen committed
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
    "    return {'b_ij': edge['b_ij'], 'h': src['h'], 'u_hat': edge['u_hat']}"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 3.3 Reduce Functions\n",
    "At this stage, we need to define a reduce function to aggregate all the information we get from message function into node features.\n",
    "This step implements the line 4 and line 5 in routing algorithms, which softmax over $b_{ij}$ and calculate weighted sum of input features. Note that softmax operation is over dimension $j$ instead of $i$. \n",
    "<img src=\"./capsule_f5.png\" style=\"height:300px\">"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [],
   "source": [
VoVAllen's avatar
VoVAllen committed
169
170
171
172
173
174
    "def capsule_reduce(node, msg):\n",
    "    b_ij_c, u_hat = msg['b_ij'], msg['u_hat']\n",
    "    # line 4\n",
    "    c_i = F.softmax(b_ij_c, dim=0)\n",
    "    # line 5\n",
    "    s_j = (c_i.unsqueeze(2).unsqueeze(3) * u_hat).sum(dim=1)\n",
VoVAllen's avatar
VoVAllen committed
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
    "    return {'h': s_j}"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 3.4 Node Update Functions\n",
    "Squash the intermidiate representations into node features $v_j$\n",
    "![step6](./step6.png)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def capsule_update(msg):\n",
VoVAllen's avatar
VoVAllen committed
194
    "    # line 6\n",
VoVAllen's avatar
VoVAllen committed
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
    "    v_j = squash(msg['h'])\n",
    "    return {'h': v_j}"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 3.5 Edge Update Functions\n",
    "Update the routing parameters\n",
    "![step7](./step7.png)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
VoVAllen's avatar
VoVAllen committed
214
    "def update_edge(self, u, v, edge):\n",
VoVAllen's avatar
VoVAllen committed
215
    "    return {'b_ij': edge['b_ij'] + (v['h'] * edge['u_hat']).mean(dim=1).sum(dim=1)}"
VoVAllen's avatar
VoVAllen committed
216
217
218
219
220
221
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
VoVAllen's avatar
VoVAllen committed
222
223
    "### 4. Executing algorithm\n",
    "Call `update_all` and `update_edge` functions to execute the algorithms"
VoVAllen's avatar
VoVAllen committed
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "for i in range(self.num_routing):\n",
    "    self.g.update_all(self.capsule_msg, self.capsule_reduce, self.capsule_update)\n",
    "    self.g.update_edge(edge_func=self.update_edge)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3.6",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.1"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}